Home | History | Annotate | Download | only in qemu
      1 /*
      2  * QEMU VNC display driver
      3  *
      4  * Copyright (C) 2006 Anthony Liguori <anthony (at) codemonkey.ws>
      5  * Copyright (C) 2006 Fabrice Bellard
      6  * Copyright (C) 2009 Red Hat, Inc
      7  *
      8  * Permission is hereby granted, free of charge, to any person obtaining a copy
      9  * of this software and associated documentation files (the "Software"), to deal
     10  * in the Software without restriction, including without limitation the rights
     11  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
     12  * copies of the Software, and to permit persons to whom the Software is
     13  * furnished to do so, subject to the following conditions:
     14  *
     15  * The above copyright notice and this permission notice shall be included in
     16  * all copies or substantial portions of the Software.
     17  *
     18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     19  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     20  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
     21  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
     22  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
     23  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
     24  * THE SOFTWARE.
     25  */
     26 
     27 #include "vnc.h"
     28 #include "sysemu.h"
     29 #include "qemu_socket.h"
     30 #include "qemu-timer.h"
     31 #include "acl.h"
     32 
     33 #define VNC_REFRESH_INTERVAL (1000 / 30)
     34 
     35 #include "vnc_keysym.h"
     36 #include "d3des.h"
     37 
     38 #define count_bits(c, v) { \
     39     for (c = 0; v; v >>= 1) \
     40     { \
     41         c += v & 1; \
     42     } \
     43 }
     44 
     45 
     46 static VncDisplay *vnc_display; /* needed for info vnc */
     47 static DisplayChangeListener *dcl;
     48 
     49 static char *addr_to_string(const char *format, SockAddress*  sa)
     50 {
     51     char *addr;
     52     char host[256];
     53     char serv[32];
     54     int err;
     55     size_t addrlen;
     56 
     57 #if 1 /* ANDROID */
     58     err = sock_address_get_numeric_info (sa, host, sizeof(host),
     59                                          serv, sizeof(serv));
     60     if (err != 0) {
     61         VNC_DEBUG("Cannot resolve address '%s': %s\n",
     62                   sock_address_to_string(sa), errno_str);
     63         return NULL;
     64     }
     65 #else
     66     if ((err = getnameinfo((struct sockaddr *)sa, salen,
     67                            host, sizeof(host),
     68                            serv, sizeof(serv),
     69                            NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
     70         VNC_DEBUG("Cannot resolve address %d: %s\n",
     71                   err, gai_strerror(err));
     72         return NULL;
     73     }
     74 #endif
     75 
     76     /* Enough for the existing format + the 2 vars we're
     77      * substituting in. */
     78     addrlen = strlen(format) + strlen(host) + strlen(serv);
     79     addr = qemu_malloc(addrlen + 1);
     80     snprintf(addr, addrlen, format, host, serv);
     81     addr[addrlen] = '\0';
     82 
     83     return addr;
     84 }
     85 
     86 
     87 char *vnc_socket_local_addr(const char *format, int fd) {
     88     SockAddress  sa;
     89 
     90     if (socket_get_address(fd, &sa) < 0)
     91         return NULL;
     92 
     93     return addr_to_string(format, &sa);
     94 }
     95 
     96 
     97 char *vnc_socket_remote_addr(const char *format, int fd) {
     98     SockAddress  sa;
     99 
    100     if (socket_get_peer_address(fd, &sa) < 0)
    101         return NULL;
    102 
    103     return addr_to_string(format, &sa);
    104 }
    105 
    106 static const char *vnc_auth_name(VncDisplay *vd) {
    107     switch (vd->auth) {
    108     case VNC_AUTH_INVALID:
    109         return "invalid";
    110     case VNC_AUTH_NONE:
    111         return "none";
    112     case VNC_AUTH_VNC:
    113         return "vnc";
    114     case VNC_AUTH_RA2:
    115         return "ra2";
    116     case VNC_AUTH_RA2NE:
    117         return "ra2ne";
    118     case VNC_AUTH_TIGHT:
    119         return "tight";
    120     case VNC_AUTH_ULTRA:
    121         return "ultra";
    122     case VNC_AUTH_TLS:
    123         return "tls";
    124     case VNC_AUTH_VENCRYPT:
    125 #ifdef CONFIG_VNC_TLS
    126         switch (vd->subauth) {
    127         case VNC_AUTH_VENCRYPT_PLAIN:
    128             return "vencrypt+plain";
    129         case VNC_AUTH_VENCRYPT_TLSNONE:
    130             return "vencrypt+tls+none";
    131         case VNC_AUTH_VENCRYPT_TLSVNC:
    132             return "vencrypt+tls+vnc";
    133         case VNC_AUTH_VENCRYPT_TLSPLAIN:
    134             return "vencrypt+tls+plain";
    135         case VNC_AUTH_VENCRYPT_X509NONE:
    136             return "vencrypt+x509+none";
    137         case VNC_AUTH_VENCRYPT_X509VNC:
    138             return "vencrypt+x509+vnc";
    139         case VNC_AUTH_VENCRYPT_X509PLAIN:
    140             return "vencrypt+x509+plain";
    141         case VNC_AUTH_VENCRYPT_TLSSASL:
    142             return "vencrypt+tls+sasl";
    143         case VNC_AUTH_VENCRYPT_X509SASL:
    144             return "vencrypt+x509+sasl";
    145         default:
    146             return "vencrypt";
    147         }
    148 #else
    149         return "vencrypt";
    150 #endif
    151     case VNC_AUTH_SASL:
    152         return "sasl";
    153     }
    154     return "unknown";
    155 }
    156 
    157 static void do_info_vnc_client(Monitor *mon, VncState *client)
    158 {
    159     char *clientAddr =
    160         vnc_socket_remote_addr("     address: %s:%s\n",
    161                                client->csock);
    162     if (!clientAddr)
    163         return;
    164 
    165     monitor_printf(mon, "Client:\n");
    166     monitor_printf(mon, "%s", clientAddr);
    167     free(clientAddr);
    168 
    169 #ifdef CONFIG_VNC_TLS
    170     if (client->tls.session &&
    171         client->tls.dname)
    172         monitor_printf(mon, "  x509 dname: %s\n", client->tls.dname);
    173     else
    174         monitor_printf(mon, "  x509 dname: none\n");
    175 #endif
    176 #ifdef CONFIG_VNC_SASL
    177     if (client->sasl.conn &&
    178         client->sasl.username)
    179         monitor_printf(mon, "    username: %s\n", client->sasl.username);
    180     else
    181         monitor_printf(mon, "    username: none\n");
    182 #endif
    183 }
    184 
    185 void do_info_vnc(Monitor *mon)
    186 {
    187     if (vnc_display == NULL || vnc_display->display == NULL) {
    188         monitor_printf(mon, "Server: disabled\n");
    189     } else {
    190         char *serverAddr = vnc_socket_local_addr("     address: %s:%s\n",
    191                                                  vnc_display->lsock);
    192 
    193         if (!serverAddr)
    194             return;
    195 
    196         monitor_printf(mon, "Server:\n");
    197         monitor_printf(mon, "%s", serverAddr);
    198         free(serverAddr);
    199         monitor_printf(mon, "        auth: %s\n", vnc_auth_name(vnc_display));
    200 
    201         if (vnc_display->clients) {
    202             VncState *client = vnc_display->clients;
    203             while (client) {
    204                 do_info_vnc_client(mon, client);
    205                 client = client->next;
    206             }
    207         } else {
    208             monitor_printf(mon, "Client: none\n");
    209         }
    210     }
    211 }
    212 
    213 static inline uint32_t vnc_has_feature(VncState *vs, int feature) {
    214     return (vs->features & (1 << feature));
    215 }
    216 
    217 /* TODO
    218    1) Get the queue working for IO.
    219    2) there is some weirdness when using the -S option (the screen is grey
    220       and not totally invalidated
    221    3) resolutions > 1024
    222 */
    223 
    224 static void vnc_update_client(void *opaque);
    225 static void vnc_disconnect_start(VncState *vs);
    226 static void vnc_disconnect_finish(VncState *vs);
    227 
    228 static void vnc_colordepth(VncState *vs);
    229 
    230 static inline void vnc_set_bit(uint32_t *d, int k)
    231 {
    232     d[k >> 5] |= 1 << (k & 0x1f);
    233 }
    234 
    235 static inline void vnc_clear_bit(uint32_t *d, int k)
    236 {
    237     d[k >> 5] &= ~(1 << (k & 0x1f));
    238 }
    239 
    240 static inline void vnc_set_bits(uint32_t *d, int n, int nb_words)
    241 {
    242     int j;
    243 
    244     j = 0;
    245     while (n >= 32) {
    246         d[j++] = -1;
    247         n -= 32;
    248     }
    249     if (n > 0)
    250         d[j++] = (1 << n) - 1;
    251     while (j < nb_words)
    252         d[j++] = 0;
    253 }
    254 
    255 static inline int vnc_get_bit(const uint32_t *d, int k)
    256 {
    257     return (d[k >> 5] >> (k & 0x1f)) & 1;
    258 }
    259 
    260 static inline int vnc_and_bits(const uint32_t *d1, const uint32_t *d2,
    261                                int nb_words)
    262 {
    263     int i;
    264     for(i = 0; i < nb_words; i++) {
    265         if ((d1[i] & d2[i]) != 0)
    266             return 1;
    267     }
    268     return 0;
    269 }
    270 
    271 static void vnc_update(VncState *vs, int x, int y, int w, int h)
    272 {
    273     struct VncSurface *s = &vs->guest;
    274     int i;
    275 
    276     h += y;
    277 
    278     /* round x down to ensure the loop only spans one 16-pixel block per,
    279        iteration.  otherwise, if (x % 16) != 0, the last iteration may span
    280        two 16-pixel blocks but we only mark the first as dirty
    281     */
    282     w += (x % 16);
    283     x -= (x % 16);
    284 
    285     x = MIN(x, s->ds->width);
    286     y = MIN(y, s->ds->height);
    287     w = MIN(x + w, s->ds->width) - x;
    288     h = MIN(h, s->ds->height);
    289 
    290     for (; y < h; y++)
    291         for (i = 0; i < w; i += 16)
    292             vnc_set_bit(s->dirty[y], (x + i) / 16);
    293 }
    294 
    295 static void vnc_dpy_update(DisplayState *ds, int x, int y, int w, int h)
    296 {
    297     VncDisplay *vd = ds->opaque;
    298     VncState *vs = vd->clients;
    299     while (vs != NULL) {
    300         vnc_update(vs, x, y, w, h);
    301         vs = vs->next;
    302     }
    303 }
    304 
    305 static void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
    306                                    int32_t encoding)
    307 {
    308     vnc_write_u16(vs, x);
    309     vnc_write_u16(vs, y);
    310     vnc_write_u16(vs, w);
    311     vnc_write_u16(vs, h);
    312 
    313     vnc_write_s32(vs, encoding);
    314 }
    315 
    316 void buffer_reserve(Buffer *buffer, size_t len)
    317 {
    318     if ((buffer->capacity - buffer->offset) < len) {
    319         buffer->capacity += (len + 1024);
    320         buffer->buffer = qemu_realloc(buffer->buffer, buffer->capacity);
    321         if (buffer->buffer == NULL) {
    322             fprintf(stderr, "vnc: out of memory\n");
    323             exit(1);
    324         }
    325     }
    326 }
    327 
    328 int buffer_empty(Buffer *buffer)
    329 {
    330     return buffer->offset == 0;
    331 }
    332 
    333 uint8_t *buffer_end(Buffer *buffer)
    334 {
    335     return buffer->buffer + buffer->offset;
    336 }
    337 
    338 void buffer_reset(Buffer *buffer)
    339 {
    340         buffer->offset = 0;
    341 }
    342 
    343 void buffer_append(Buffer *buffer, const void *data, size_t len)
    344 {
    345     memcpy(buffer->buffer + buffer->offset, data, len);
    346     buffer->offset += len;
    347 }
    348 
    349 static void vnc_resize(VncState *vs)
    350 {
    351     DisplayState *ds = vs->ds;
    352     int size_changed;
    353 
    354     /* guest surface */
    355     if (!vs->guest.ds)
    356         vs->guest.ds = qemu_mallocz(sizeof(*vs->guest.ds));
    357     if (ds_get_bytes_per_pixel(ds) != vs->guest.ds->pf.bytes_per_pixel)
    358         console_color_init(ds);
    359     vnc_colordepth(vs);
    360     size_changed = ds_get_width(ds) != vs->guest.ds->width ||
    361                    ds_get_height(ds) != vs->guest.ds->height;
    362     *(vs->guest.ds) = *(ds->surface);
    363     if (size_changed) {
    364         if (vs->csock != -1 && vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
    365             vnc_write_u8(vs, 0);  /* msg id */
    366             vnc_write_u8(vs, 0);
    367             vnc_write_u16(vs, 1); /* number of rects */
    368             vnc_framebuffer_update(vs, 0, 0, ds_get_width(ds), ds_get_height(ds),
    369                                    VNC_ENCODING_DESKTOPRESIZE);
    370             vnc_flush(vs);
    371         }
    372     }
    373     memset(vs->guest.dirty, 0xFF, sizeof(vs->guest.dirty));
    374 
    375     /* server surface */
    376     if (!vs->server.ds)
    377         vs->server.ds = qemu_mallocz(sizeof(*vs->server.ds));
    378     if (vs->server.ds->data)
    379         qemu_free(vs->server.ds->data);
    380     *(vs->server.ds) = *(ds->surface);
    381     vs->server.ds->data = qemu_mallocz(vs->server.ds->linesize *
    382                                        vs->server.ds->height);
    383     memset(vs->server.dirty, 0xFF, sizeof(vs->guest.dirty));
    384 }
    385 
    386 static void vnc_dpy_resize(DisplayState *ds)
    387 {
    388     VncDisplay *vd = ds->opaque;
    389     VncState *vs = vd->clients;
    390     while (vs != NULL) {
    391         vnc_resize(vs);
    392         vs = vs->next;
    393     }
    394 }
    395 
    396 /* fastest code */
    397 static void vnc_write_pixels_copy(VncState *vs, void *pixels, int size)
    398 {
    399     vnc_write(vs, pixels, size);
    400 }
    401 
    402 /* slowest but generic code. */
    403 static void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
    404 {
    405     uint8_t r, g, b;
    406 
    407     r = ((((v & vs->server.ds->pf.rmask) >> vs->server.ds->pf.rshift) << vs->clientds.pf.rbits) >>
    408         vs->server.ds->pf.rbits);
    409     g = ((((v & vs->server.ds->pf.gmask) >> vs->server.ds->pf.gshift) << vs->clientds.pf.gbits) >>
    410         vs->server.ds->pf.gbits);
    411     b = ((((v & vs->server.ds->pf.bmask) >> vs->server.ds->pf.bshift) << vs->clientds.pf.bbits) >>
    412         vs->server.ds->pf.bbits);
    413     v = (r << vs->clientds.pf.rshift) |
    414         (g << vs->clientds.pf.gshift) |
    415         (b << vs->clientds.pf.bshift);
    416     switch(vs->clientds.pf.bytes_per_pixel) {
    417     case 1:
    418         buf[0] = v;
    419         break;
    420     case 2:
    421         if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) {
    422             buf[0] = v >> 8;
    423             buf[1] = v;
    424         } else {
    425             buf[1] = v >> 8;
    426             buf[0] = v;
    427         }
    428         break;
    429     default:
    430     case 4:
    431         if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) {
    432             buf[0] = v >> 24;
    433             buf[1] = v >> 16;
    434             buf[2] = v >> 8;
    435             buf[3] = v;
    436         } else {
    437             buf[3] = v >> 24;
    438             buf[2] = v >> 16;
    439             buf[1] = v >> 8;
    440             buf[0] = v;
    441         }
    442         break;
    443     }
    444 }
    445 
    446 static void vnc_write_pixels_generic(VncState *vs, void *pixels1, int size)
    447 {
    448     uint8_t buf[4];
    449 
    450     if (vs->server.ds->pf.bytes_per_pixel == 4) {
    451         uint32_t *pixels = pixels1;
    452         int n, i;
    453         n = size >> 2;
    454         for(i = 0; i < n; i++) {
    455             vnc_convert_pixel(vs, buf, pixels[i]);
    456             vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
    457         }
    458     } else if (vs->server.ds->pf.bytes_per_pixel == 2) {
    459         uint16_t *pixels = pixels1;
    460         int n, i;
    461         n = size >> 1;
    462         for(i = 0; i < n; i++) {
    463             vnc_convert_pixel(vs, buf, pixels[i]);
    464             vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
    465         }
    466     } else if (vs->server.ds->pf.bytes_per_pixel == 1) {
    467         uint8_t *pixels = pixels1;
    468         int n, i;
    469         n = size;
    470         for(i = 0; i < n; i++) {
    471             vnc_convert_pixel(vs, buf, pixels[i]);
    472             vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
    473         }
    474     } else {
    475         fprintf(stderr, "vnc_write_pixels_generic: VncState color depth not supported\n");
    476     }
    477 }
    478 
    479 static void send_framebuffer_update_raw(VncState *vs, int x, int y, int w, int h)
    480 {
    481     int i;
    482     uint8_t *row;
    483 
    484     row = vs->server.ds->data + y * ds_get_linesize(vs->ds) + x * ds_get_bytes_per_pixel(vs->ds);
    485     for (i = 0; i < h; i++) {
    486         vs->write_pixels(vs, row, w * ds_get_bytes_per_pixel(vs->ds));
    487         row += ds_get_linesize(vs->ds);
    488     }
    489 }
    490 
    491 static void hextile_enc_cord(uint8_t *ptr, int x, int y, int w, int h)
    492 {
    493     ptr[0] = ((x & 0x0F) << 4) | (y & 0x0F);
    494     ptr[1] = (((w - 1) & 0x0F) << 4) | ((h - 1) & 0x0F);
    495 }
    496 
    497 #define BPP 8
    498 #include "vnchextile.h"
    499 #undef BPP
    500 
    501 #define BPP 16
    502 #include "vnchextile.h"
    503 #undef BPP
    504 
    505 #define BPP 32
    506 #include "vnchextile.h"
    507 #undef BPP
    508 
    509 #define GENERIC
    510 #define BPP 8
    511 #include "vnchextile.h"
    512 #undef BPP
    513 #undef GENERIC
    514 
    515 #define GENERIC
    516 #define BPP 16
    517 #include "vnchextile.h"
    518 #undef BPP
    519 #undef GENERIC
    520 
    521 #define GENERIC
    522 #define BPP 32
    523 #include "vnchextile.h"
    524 #undef BPP
    525 #undef GENERIC
    526 
    527 static void send_framebuffer_update_hextile(VncState *vs, int x, int y, int w, int h)
    528 {
    529     int i, j;
    530     int has_fg, has_bg;
    531     uint8_t *last_fg, *last_bg;
    532 
    533     last_fg = (uint8_t *) qemu_malloc(vs->server.ds->pf.bytes_per_pixel);
    534     last_bg = (uint8_t *) qemu_malloc(vs->server.ds->pf.bytes_per_pixel);
    535     has_fg = has_bg = 0;
    536     for (j = y; j < (y + h); j += 16) {
    537         for (i = x; i < (x + w); i += 16) {
    538             vs->send_hextile_tile(vs, i, j,
    539                                   MIN(16, x + w - i), MIN(16, y + h - j),
    540                                   last_bg, last_fg, &has_bg, &has_fg);
    541         }
    542     }
    543     free(last_fg);
    544     free(last_bg);
    545 
    546 }
    547 
    548 static void vnc_zlib_init(VncState *vs)
    549 {
    550     int i;
    551     for (i=0; i<(sizeof(vs->zlib_stream) / sizeof(z_stream)); i++)
    552         vs->zlib_stream[i].opaque = NULL;
    553 }
    554 
    555 static void vnc_zlib_start(VncState *vs)
    556 {
    557     buffer_reset(&vs->zlib);
    558 
    559     // make the output buffer be the zlib buffer, so we can compress it later
    560     vs->zlib_tmp = vs->output;
    561     vs->output = vs->zlib;
    562 }
    563 
    564 static int vnc_zlib_stop(VncState *vs, int stream_id)
    565 {
    566     z_streamp zstream = &vs->zlib_stream[stream_id];
    567     int previous_out;
    568 
    569     // switch back to normal output/zlib buffers
    570     vs->zlib = vs->output;
    571     vs->output = vs->zlib_tmp;
    572 
    573     // compress the zlib buffer
    574 
    575     // initialize the stream
    576     // XXX need one stream per session
    577     if (zstream->opaque != vs) {
    578         int err;
    579 
    580         VNC_DEBUG("VNC: initializing zlib stream %d\n", stream_id);
    581         VNC_DEBUG("VNC: opaque = %p | vs = %p\n", zstream->opaque, vs);
    582         zstream->zalloc = Z_NULL;
    583         zstream->zfree = Z_NULL;
    584 
    585         err = deflateInit2(zstream, vs->tight_compression, Z_DEFLATED, MAX_WBITS,
    586                            MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY);
    587 
    588         if (err != Z_OK) {
    589             fprintf(stderr, "VNC: error initializing zlib\n");
    590             return -1;
    591         }
    592 
    593         zstream->opaque = vs;
    594     }
    595 
    596     // XXX what to do if tight_compression changed in between?
    597 
    598     // reserve memory in output buffer
    599     buffer_reserve(&vs->output, vs->zlib.offset + 64);
    600 
    601     // set pointers
    602     zstream->next_in = vs->zlib.buffer;
    603     zstream->avail_in = vs->zlib.offset;
    604     zstream->next_out = vs->output.buffer + vs->output.offset;
    605     zstream->avail_out = vs->output.capacity - vs->output.offset;
    606     zstream->data_type = Z_BINARY;
    607     previous_out = zstream->total_out;
    608 
    609     // start encoding
    610     if (deflate(zstream, Z_SYNC_FLUSH) != Z_OK) {
    611         fprintf(stderr, "VNC: error during zlib compression\n");
    612         return -1;
    613     }
    614 
    615     vs->output.offset = vs->output.capacity - zstream->avail_out;
    616     return zstream->total_out - previous_out;
    617 }
    618 
    619 static void send_framebuffer_update_zlib(VncState *vs, int x, int y, int w, int h)
    620 {
    621     int old_offset, new_offset, bytes_written;
    622 
    623     vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_ZLIB);
    624 
    625     // remember where we put in the follow-up size
    626     old_offset = vs->output.offset;
    627     vnc_write_s32(vs, 0);
    628 
    629     // compress the stream
    630     vnc_zlib_start(vs);
    631     send_framebuffer_update_raw(vs, x, y, w, h);
    632     bytes_written = vnc_zlib_stop(vs, 0);
    633 
    634     if (bytes_written == -1)
    635         return;
    636 
    637     // hack in the size
    638     new_offset = vs->output.offset;
    639     vs->output.offset = old_offset;
    640     vnc_write_u32(vs, bytes_written);
    641     vs->output.offset = new_offset;
    642 }
    643 
    644 static void send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
    645 {
    646     switch(vs->vnc_encoding) {
    647         case VNC_ENCODING_ZLIB:
    648             send_framebuffer_update_zlib(vs, x, y, w, h);
    649             break;
    650         case VNC_ENCODING_HEXTILE:
    651             vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
    652             send_framebuffer_update_hextile(vs, x, y, w, h);
    653             break;
    654         default:
    655             vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
    656             send_framebuffer_update_raw(vs, x, y, w, h);
    657             break;
    658     }
    659 }
    660 
    661 static void vnc_copy(VncState *vs, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
    662 {
    663     vnc_write_u8(vs, 0);  /* msg id */
    664     vnc_write_u8(vs, 0);
    665     vnc_write_u16(vs, 1); /* number of rects */
    666     vnc_framebuffer_update(vs, dst_x, dst_y, w, h, VNC_ENCODING_COPYRECT);
    667     vnc_write_u16(vs, src_x);
    668     vnc_write_u16(vs, src_y);
    669     vnc_flush(vs);
    670 }
    671 
    672 static void vnc_dpy_copy(DisplayState *ds, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
    673 {
    674     VncDisplay *vd = ds->opaque;
    675     VncState *vs, *vn;
    676 
    677     for (vs = vd->clients; vs != NULL; vs = vn) {
    678         vn = vs->next;
    679         if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
    680             vs->force_update = 1;
    681             vnc_update_client(vs);
    682             /* vs might be free()ed here */
    683         }
    684     }
    685 
    686     for (vs = vd->clients; vs != NULL; vs = vs->next) {
    687         if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT))
    688             vnc_copy(vs, src_x, src_y, dst_x, dst_y, w, h);
    689         else /* TODO */
    690             vnc_update(vs, dst_x, dst_y, w, h);
    691     }
    692 }
    693 
    694 static int find_and_clear_dirty_height(struct VncSurface *s,
    695                                        int y, int last_x, int x)
    696 {
    697     int h;
    698 
    699     for (h = 1; h < (s->ds->height - y); h++) {
    700         int tmp_x;
    701         if (!vnc_get_bit(s->dirty[y + h], last_x))
    702             break;
    703         for (tmp_x = last_x; tmp_x < x; tmp_x++)
    704             vnc_clear_bit(s->dirty[y + h], tmp_x);
    705     }
    706 
    707     return h;
    708 }
    709 
    710 static void vnc_update_client(void *opaque)
    711 {
    712     VncState *vs = opaque;
    713     if (vs->need_update && vs->csock != -1) {
    714         int y;
    715         uint8_t *guest_row;
    716         uint8_t *server_row;
    717         int cmp_bytes;
    718         uint32_t width_mask[VNC_DIRTY_WORDS];
    719         int n_rectangles;
    720         int saved_offset;
    721         int has_dirty = 0;
    722 
    723         if (vs->output.offset && !vs->audio_cap && !vs->force_update) {
    724             /* kernel send buffers are full -> drop frames to throttle */
    725             qemu_mod_timer(vs->timer, qemu_get_clock_ms(rt_clock) + VNC_REFRESH_INTERVAL);
    726             return;
    727         }
    728 
    729         vga_hw_update();
    730 
    731         /*
    732          * Walk through the guest dirty map.
    733          * Check and copy modified bits from guest to server surface.
    734          * Update server dirty map.
    735          */
    736         vnc_set_bits(width_mask, (ds_get_width(vs->ds) / 16), VNC_DIRTY_WORDS);
    737         cmp_bytes = 16 * ds_get_bytes_per_pixel(vs->ds);
    738         guest_row  = vs->guest.ds->data;
    739         server_row = vs->server.ds->data;
    740         for (y = 0; y < vs->guest.ds->height; y++) {
    741             if (vnc_and_bits(vs->guest.dirty[y], width_mask, VNC_DIRTY_WORDS)) {
    742                 int x;
    743                 uint8_t *guest_ptr;
    744                 uint8_t *server_ptr;
    745 
    746                 guest_ptr  = guest_row;
    747                 server_ptr = server_row;
    748 
    749                 for (x = 0; x < vs->guest.ds->width;
    750                      x += 16, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
    751                     if (!vnc_get_bit(vs->guest.dirty[y], (x / 16)))
    752                         continue;
    753                     vnc_clear_bit(vs->guest.dirty[y], (x / 16));
    754                     if (memcmp(server_ptr, guest_ptr, cmp_bytes) == 0)
    755                         continue;
    756                     memcpy(server_ptr, guest_ptr, cmp_bytes);
    757                     vnc_set_bit(vs->server.dirty[y], (x / 16));
    758                     has_dirty++;
    759                 }
    760             }
    761             guest_row  += ds_get_linesize(vs->ds);
    762             server_row += ds_get_linesize(vs->ds);
    763         }
    764 
    765         if (!has_dirty && !vs->audio_cap && !vs->force_update) {
    766             qemu_mod_timer(vs->timer, qemu_get_clock_ms(rt_clock) + VNC_REFRESH_INTERVAL);
    767             return;
    768         }
    769 
    770         /*
    771          * Send screen updates to the vnc client using the server
    772          * surface and server dirty map.  guest surface updates
    773          * happening in parallel don't disturb us, the next pass will
    774          * send them to the client.
    775          */
    776         n_rectangles = 0;
    777         vnc_write_u8(vs, 0);  /* msg id */
    778         vnc_write_u8(vs, 0);
    779         saved_offset = vs->output.offset;
    780         vnc_write_u16(vs, 0);
    781 
    782         for (y = 0; y < vs->server.ds->height; y++) {
    783             int x;
    784             int last_x = -1;
    785             for (x = 0; x < vs->server.ds->width / 16; x++) {
    786                 if (vnc_get_bit(vs->server.dirty[y], x)) {
    787                     if (last_x == -1) {
    788                         last_x = x;
    789                     }
    790                     vnc_clear_bit(vs->server.dirty[y], x);
    791                 } else {
    792                     if (last_x != -1) {
    793                         int h = find_and_clear_dirty_height(&vs->server, y, last_x, x);
    794                         send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
    795                         n_rectangles++;
    796                     }
    797                     last_x = -1;
    798                 }
    799             }
    800             if (last_x != -1) {
    801                 int h = find_and_clear_dirty_height(&vs->server, y, last_x, x);
    802                 send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
    803                 n_rectangles++;
    804             }
    805         }
    806         vs->output.buffer[saved_offset] = (n_rectangles >> 8) & 0xFF;
    807         vs->output.buffer[saved_offset + 1] = n_rectangles & 0xFF;
    808         vnc_flush(vs);
    809         vs->force_update = 0;
    810 
    811     }
    812 
    813     if (vs->csock != -1) {
    814         qemu_mod_timer(vs->timer, qemu_get_clock_ms(rt_clock) + VNC_REFRESH_INTERVAL);
    815     } else {
    816         vnc_disconnect_finish(vs);
    817     }
    818 
    819 }
    820 
    821 /* audio */
    822 static void audio_capture_notify(void *opaque, audcnotification_e cmd)
    823 {
    824     VncState *vs = opaque;
    825 
    826     switch (cmd) {
    827     case AUD_CNOTIFY_DISABLE:
    828         vnc_write_u8(vs, 255);
    829         vnc_write_u8(vs, 1);
    830         vnc_write_u16(vs, 0);
    831         vnc_flush(vs);
    832         break;
    833 
    834     case AUD_CNOTIFY_ENABLE:
    835         vnc_write_u8(vs, 255);
    836         vnc_write_u8(vs, 1);
    837         vnc_write_u16(vs, 1);
    838         vnc_flush(vs);
    839         break;
    840     }
    841 }
    842 
    843 static void audio_capture_destroy(void *opaque)
    844 {
    845 }
    846 
    847 static void audio_capture(void *opaque, void *buf, int size)
    848 {
    849     VncState *vs = opaque;
    850 
    851     vnc_write_u8(vs, 255);
    852     vnc_write_u8(vs, 1);
    853     vnc_write_u16(vs, 2);
    854     vnc_write_u32(vs, size);
    855     vnc_write(vs, buf, size);
    856     vnc_flush(vs);
    857 }
    858 
    859 static void audio_add(VncState *vs)
    860 {
    861     Monitor *mon = cur_mon;
    862     struct audio_capture_ops ops;
    863 
    864     if (vs->audio_cap) {
    865         monitor_printf(mon, "audio already running\n");
    866         return;
    867     }
    868 
    869     ops.notify = audio_capture_notify;
    870     ops.destroy = audio_capture_destroy;
    871     ops.capture = audio_capture;
    872 
    873     vs->audio_cap = AUD_add_capture(&vs->as, &ops, vs);
    874     if (!vs->audio_cap) {
    875         monitor_printf(mon, "Failed to add audio capture\n");
    876     }
    877 }
    878 
    879 static void audio_del(VncState *vs)
    880 {
    881     if (vs->audio_cap) {
    882         AUD_del_capture(vs->audio_cap, vs);
    883         vs->audio_cap = NULL;
    884     }
    885 }
    886 
    887 static void vnc_disconnect_start(VncState *vs)
    888 {
    889     if (vs->csock == -1)
    890         return;
    891     qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
    892     closesocket(vs->csock);
    893     vs->csock = -1;
    894 }
    895 
    896 static void vnc_disconnect_finish(VncState *vs)
    897 {
    898     qemu_del_timer(vs->timer);
    899     qemu_free_timer(vs->timer);
    900     if (vs->input.buffer) qemu_free(vs->input.buffer);
    901     if (vs->output.buffer) qemu_free(vs->output.buffer);
    902 #ifdef CONFIG_VNC_TLS
    903     vnc_tls_client_cleanup(vs);
    904 #endif /* CONFIG_VNC_TLS */
    905 #ifdef CONFIG_VNC_SASL
    906     vnc_sasl_client_cleanup(vs);
    907 #endif /* CONFIG_VNC_SASL */
    908     audio_del(vs);
    909 
    910     VncState *p, *parent = NULL;
    911     for (p = vs->vd->clients; p != NULL; p = p->next) {
    912         if (p == vs) {
    913             if (parent)
    914                 parent->next = p->next;
    915             else
    916                 vs->vd->clients = p->next;
    917             break;
    918         }
    919         parent = p;
    920     }
    921     if (!vs->vd->clients)
    922         dcl->idle = 1;
    923 
    924     qemu_free(vs->server.ds->data);
    925     qemu_free(vs->server.ds);
    926     qemu_free(vs->guest.ds);
    927     qemu_free(vs);
    928 }
    929 
    930 int vnc_client_io_error(VncState *vs, int ret, int last_errno)
    931 {
    932     if (ret == 0 || ret == -1) {
    933         if (ret == -1) {
    934             switch (last_errno) {
    935                 case EINTR:
    936                 case EAGAIN:
    937 #ifdef _WIN32
    938                 case WSAEWOULDBLOCK:
    939 #endif
    940                     return 0;
    941                 default:
    942                     break;
    943             }
    944         }
    945 
    946         VNC_DEBUG("Closing down client sock: ret %d, errno %d\n",
    947                   ret, ret < 0 ? last_errno : 0);
    948         vnc_disconnect_start(vs);
    949 
    950         return 0;
    951     }
    952     return ret;
    953 }
    954 
    955 
    956 void vnc_client_error(VncState *vs)
    957 {
    958     VNC_DEBUG("Closing down client sock: protocol error\n");
    959     vnc_disconnect_start(vs);
    960 }
    961 
    962 
    963 /*
    964  * Called to write a chunk of data to the client socket. The data may
    965  * be the raw data, or may have already been encoded by SASL.
    966  * The data will be written either straight onto the socket, or
    967  * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
    968  *
    969  * NB, it is theoretically possible to have 2 layers of encryption,
    970  * both SASL, and this TLS layer. It is highly unlikely in practice
    971  * though, since SASL encryption will typically be a no-op if TLS
    972  * is active
    973  *
    974  * Returns the number of bytes written, which may be less than
    975  * the requested 'datalen' if the socket would block. Returns
    976  * -1 on error, and disconnects the client socket.
    977  */
    978 long vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
    979 {
    980     long ret;
    981 #ifdef CONFIG_VNC_TLS
    982     if (vs->tls.session) {
    983         ret = gnutls_write(vs->tls.session, data, datalen);
    984         if (ret < 0) {
    985             if (ret == GNUTLS_E_AGAIN)
    986                 errno = EAGAIN;
    987             else
    988                 errno = EIO;
    989             ret = -1;
    990         }
    991     } else
    992 #endif /* CONFIG_VNC_TLS */
    993         ret = socket_send(vs->csock, data, datalen);
    994     VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
    995     return vnc_client_io_error(vs, ret, socket_error());
    996 }
    997 
    998 
    999 /*
   1000  * Called to write buffered data to the client socket, when not
   1001  * using any SASL SSF encryption layers. Will write as much data
   1002  * as possible without blocking. If all buffered data is written,
   1003  * will switch the FD poll() handler back to read monitoring.
   1004  *
   1005  * Returns the number of bytes written, which may be less than
   1006  * the buffered output data if the socket would block. Returns
   1007  * -1 on error, and disconnects the client socket.
   1008  */
   1009 static long vnc_client_write_plain(VncState *vs)
   1010 {
   1011     long ret;
   1012 
   1013 #ifdef CONFIG_VNC_SASL
   1014     VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
   1015               vs->output.buffer, vs->output.capacity, vs->output.offset,
   1016               vs->sasl.waitWriteSSF);
   1017 
   1018     if (vs->sasl.conn &&
   1019         vs->sasl.runSSF &&
   1020         vs->sasl.waitWriteSSF) {
   1021         ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
   1022         if (ret)
   1023             vs->sasl.waitWriteSSF -= ret;
   1024     } else
   1025 #endif /* CONFIG_VNC_SASL */
   1026         ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
   1027     if (!ret)
   1028         return 0;
   1029 
   1030     memmove(vs->output.buffer, vs->output.buffer + ret, (vs->output.offset - ret));
   1031     vs->output.offset -= ret;
   1032 
   1033     if (vs->output.offset == 0) {
   1034         qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
   1035     }
   1036 
   1037     return ret;
   1038 }
   1039 
   1040 
   1041 /*
   1042  * First function called whenever there is data to be written to
   1043  * the client socket. Will delegate actual work according to whether
   1044  * SASL SSF layers are enabled (thus requiring encryption calls)
   1045  */
   1046 void vnc_client_write(void *opaque)
   1047 {
   1048     long ret;
   1049     VncState *vs = opaque;
   1050 
   1051 #ifdef CONFIG_VNC_SASL
   1052     if (vs->sasl.conn &&
   1053         vs->sasl.runSSF &&
   1054         !vs->sasl.waitWriteSSF)
   1055         ret = vnc_client_write_sasl(vs);
   1056     else
   1057 #endif /* CONFIG_VNC_SASL */
   1058         ret = vnc_client_write_plain(vs);
   1059 }
   1060 
   1061 void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
   1062 {
   1063     vs->read_handler = func;
   1064     vs->read_handler_expect = expecting;
   1065 }
   1066 
   1067 
   1068 /*
   1069  * Called to read a chunk of data from the client socket. The data may
   1070  * be the raw data, or may need to be further decoded by SASL.
   1071  * The data will be read either straight from to the socket, or
   1072  * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
   1073  *
   1074  * NB, it is theoretically possible to have 2 layers of encryption,
   1075  * both SASL, and this TLS layer. It is highly unlikely in practice
   1076  * though, since SASL encryption will typically be a no-op if TLS
   1077  * is active
   1078  *
   1079  * Returns the number of bytes read, which may be less than
   1080  * the requested 'datalen' if the socket would block. Returns
   1081  * -1 on error, and disconnects the client socket.
   1082  */
   1083 long vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
   1084 {
   1085     long ret;
   1086 #ifdef CONFIG_VNC_TLS
   1087     if (vs->tls.session) {
   1088         ret = gnutls_read(vs->tls.session, data, datalen);
   1089         if (ret < 0) {
   1090             if (ret == GNUTLS_E_AGAIN)
   1091                 errno = EAGAIN;
   1092             else
   1093                 errno = EIO;
   1094             ret = -1;
   1095         }
   1096     } else
   1097 #endif /* CONFIG_VNC_TLS */
   1098         ret = socket_recv(vs->csock, data, datalen);
   1099     VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
   1100     return vnc_client_io_error(vs, ret, socket_error());
   1101 }
   1102 
   1103 
   1104 /*
   1105  * Called to read data from the client socket to the input buffer,
   1106  * when not using any SASL SSF encryption layers. Will read as much
   1107  * data as possible without blocking.
   1108  *
   1109  * Returns the number of bytes read. Returns -1 on error, and
   1110  * disconnects the client socket.
   1111  */
   1112 static long vnc_client_read_plain(VncState *vs)
   1113 {
   1114     int ret;
   1115     VNC_DEBUG("Read plain %p size %zd offset %zd\n",
   1116               vs->input.buffer, vs->input.capacity, vs->input.offset);
   1117     buffer_reserve(&vs->input, 4096);
   1118     ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
   1119     if (!ret)
   1120         return 0;
   1121     vs->input.offset += ret;
   1122     return ret;
   1123 }
   1124 
   1125 
   1126 /*
   1127  * First function called whenever there is more data to be read from
   1128  * the client socket. Will delegate actual work according to whether
   1129  * SASL SSF layers are enabled (thus requiring decryption calls)
   1130  */
   1131 void vnc_client_read(void *opaque)
   1132 {
   1133     VncState *vs = opaque;
   1134     long ret;
   1135 
   1136 #ifdef CONFIG_VNC_SASL
   1137     if (vs->sasl.conn && vs->sasl.runSSF)
   1138         ret = vnc_client_read_sasl(vs);
   1139     else
   1140 #endif /* CONFIG_VNC_SASL */
   1141         ret = vnc_client_read_plain(vs);
   1142     if (!ret) {
   1143         if (vs->csock == -1)
   1144             vnc_disconnect_finish(vs);
   1145         return;
   1146     }
   1147 
   1148     while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
   1149         size_t len = vs->read_handler_expect;
   1150         int ret;
   1151 
   1152         ret = vs->read_handler(vs, vs->input.buffer, len);
   1153         if (vs->csock == -1) {
   1154             vnc_disconnect_finish(vs);
   1155             return;
   1156         }
   1157 
   1158         if (!ret) {
   1159             memmove(vs->input.buffer, vs->input.buffer + len, (vs->input.offset - len));
   1160             vs->input.offset -= len;
   1161         } else {
   1162             vs->read_handler_expect = ret;
   1163         }
   1164     }
   1165 }
   1166 
   1167 void vnc_write(VncState *vs, const void *data, size_t len)
   1168 {
   1169     buffer_reserve(&vs->output, len);
   1170 
   1171     if (vs->csock != -1 && buffer_empty(&vs->output)) {
   1172         qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
   1173     }
   1174 
   1175     buffer_append(&vs->output, data, len);
   1176 }
   1177 
   1178 void vnc_write_s32(VncState *vs, int32_t value)
   1179 {
   1180     vnc_write_u32(vs, *(uint32_t *)&value);
   1181 }
   1182 
   1183 void vnc_write_u32(VncState *vs, uint32_t value)
   1184 {
   1185     uint8_t buf[4];
   1186 
   1187     buf[0] = (value >> 24) & 0xFF;
   1188     buf[1] = (value >> 16) & 0xFF;
   1189     buf[2] = (value >>  8) & 0xFF;
   1190     buf[3] = value & 0xFF;
   1191 
   1192     vnc_write(vs, buf, 4);
   1193 }
   1194 
   1195 void vnc_write_u16(VncState *vs, uint16_t value)
   1196 {
   1197     uint8_t buf[2];
   1198 
   1199     buf[0] = (value >> 8) & 0xFF;
   1200     buf[1] = value & 0xFF;
   1201 
   1202     vnc_write(vs, buf, 2);
   1203 }
   1204 
   1205 void vnc_write_u8(VncState *vs, uint8_t value)
   1206 {
   1207     vnc_write(vs, (char *)&value, 1);
   1208 }
   1209 
   1210 void vnc_flush(VncState *vs)
   1211 {
   1212     if (vs->csock != -1 && vs->output.offset)
   1213         vnc_client_write(vs);
   1214 }
   1215 
   1216 uint8_t read_u8(uint8_t *data, size_t offset)
   1217 {
   1218     return data[offset];
   1219 }
   1220 
   1221 uint16_t read_u16(uint8_t *data, size_t offset)
   1222 {
   1223     return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
   1224 }
   1225 
   1226 int32_t read_s32(uint8_t *data, size_t offset)
   1227 {
   1228     return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
   1229                      (data[offset + 2] << 8) | data[offset + 3]);
   1230 }
   1231 
   1232 uint32_t read_u32(uint8_t *data, size_t offset)
   1233 {
   1234     return ((data[offset] << 24) | (data[offset + 1] << 16) |
   1235             (data[offset + 2] << 8) | data[offset + 3]);
   1236 }
   1237 
   1238 static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
   1239 {
   1240 }
   1241 
   1242 static void check_pointer_type_change(VncState *vs, int absolute)
   1243 {
   1244     if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
   1245         vnc_write_u8(vs, 0);
   1246         vnc_write_u8(vs, 0);
   1247         vnc_write_u16(vs, 1);
   1248         vnc_framebuffer_update(vs, absolute, 0,
   1249                                ds_get_width(vs->ds), ds_get_height(vs->ds),
   1250                                VNC_ENCODING_POINTER_TYPE_CHANGE);
   1251         vnc_flush(vs);
   1252     }
   1253     vs->absolute = absolute;
   1254 }
   1255 
   1256 static void pointer_event(VncState *vs, int button_mask, int x, int y)
   1257 {
   1258     int buttons = 0;
   1259     int dz = 0;
   1260 
   1261     if (button_mask & 0x01)
   1262         buttons |= MOUSE_EVENT_LBUTTON;
   1263     if (button_mask & 0x02)
   1264         buttons |= MOUSE_EVENT_MBUTTON;
   1265     if (button_mask & 0x04)
   1266         buttons |= MOUSE_EVENT_RBUTTON;
   1267     if (button_mask & 0x08)
   1268         dz = -1;
   1269     if (button_mask & 0x10)
   1270         dz = 1;
   1271 
   1272     if (vs->absolute) {
   1273         kbd_mouse_event(x * 0x7FFF / (ds_get_width(vs->ds) - 1),
   1274                         y * 0x7FFF / (ds_get_height(vs->ds) - 1),
   1275                         dz, buttons);
   1276     } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
   1277         x -= 0x7FFF;
   1278         y -= 0x7FFF;
   1279 
   1280         kbd_mouse_event(x, y, dz, buttons);
   1281     } else {
   1282         if (vs->last_x != -1)
   1283             kbd_mouse_event(x - vs->last_x,
   1284                             y - vs->last_y,
   1285                             dz, buttons);
   1286         vs->last_x = x;
   1287         vs->last_y = y;
   1288     }
   1289 
   1290     check_pointer_type_change(vs, kbd_mouse_is_absolute());
   1291 }
   1292 
   1293 static void reset_keys(VncState *vs)
   1294 {
   1295     int i;
   1296     for(i = 0; i < 256; i++) {
   1297         if (vs->modifiers_state[i]) {
   1298             if (i & 0x80)
   1299                 kbd_put_keycode(0xe0);
   1300             kbd_put_keycode(i | 0x80);
   1301             vs->modifiers_state[i] = 0;
   1302         }
   1303     }
   1304 }
   1305 
   1306 static void press_key(VncState *vs, int keysym)
   1307 {
   1308     kbd_put_keycode(keysym2scancode(vs->vd->kbd_layout, keysym) & 0x7f);
   1309     kbd_put_keycode(keysym2scancode(vs->vd->kbd_layout, keysym) | 0x80);
   1310 }
   1311 
   1312 static void do_key_event(VncState *vs, int down, int keycode, int sym)
   1313 {
   1314     /* QEMU console switch */
   1315     switch(keycode) {
   1316     case 0x2a:                          /* Left Shift */
   1317     case 0x36:                          /* Right Shift */
   1318     case 0x1d:                          /* Left CTRL */
   1319     case 0x9d:                          /* Right CTRL */
   1320     case 0x38:                          /* Left ALT */
   1321     case 0xb8:                          /* Right ALT */
   1322         if (down)
   1323             vs->modifiers_state[keycode] = 1;
   1324         else
   1325             vs->modifiers_state[keycode] = 0;
   1326         break;
   1327     case 0x02 ... 0x0a: /* '1' to '9' keys */
   1328         if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
   1329             /* Reset the modifiers sent to the current console */
   1330             reset_keys(vs);
   1331             console_select(keycode - 0x02);
   1332             return;
   1333         }
   1334         break;
   1335     case 0x3a:                        /* CapsLock */
   1336     case 0x45:                        /* NumLock */
   1337         if (!down)
   1338             vs->modifiers_state[keycode] ^= 1;
   1339         break;
   1340     }
   1341 
   1342     if (keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
   1343         /* If the numlock state needs to change then simulate an additional
   1344            keypress before sending this one.  This will happen if the user
   1345            toggles numlock away from the VNC window.
   1346         */
   1347         if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
   1348             if (!vs->modifiers_state[0x45]) {
   1349                 vs->modifiers_state[0x45] = 1;
   1350                 press_key(vs, 0xff7f);
   1351             }
   1352         } else {
   1353             if (vs->modifiers_state[0x45]) {
   1354                 vs->modifiers_state[0x45] = 0;
   1355                 press_key(vs, 0xff7f);
   1356             }
   1357         }
   1358     }
   1359 
   1360     if (is_graphic_console()) {
   1361         if (keycode & 0x80)
   1362             kbd_put_keycode(0xe0);
   1363         if (down)
   1364             kbd_put_keycode(keycode & 0x7f);
   1365         else
   1366             kbd_put_keycode(keycode | 0x80);
   1367     } else {
   1368         /* QEMU console emulation */
   1369         if (down) {
   1370             int numlock = vs->modifiers_state[0x45];
   1371             switch (keycode) {
   1372             case 0x2a:                          /* Left Shift */
   1373             case 0x36:                          /* Right Shift */
   1374             case 0x1d:                          /* Left CTRL */
   1375             case 0x9d:                          /* Right CTRL */
   1376             case 0x38:                          /* Left ALT */
   1377             case 0xb8:                          /* Right ALT */
   1378                 break;
   1379             case 0xc8:
   1380                 kbd_put_keysym(QEMU_KEY_UP);
   1381                 break;
   1382             case 0xd0:
   1383                 kbd_put_keysym(QEMU_KEY_DOWN);
   1384                 break;
   1385             case 0xcb:
   1386                 kbd_put_keysym(QEMU_KEY_LEFT);
   1387                 break;
   1388             case 0xcd:
   1389                 kbd_put_keysym(QEMU_KEY_RIGHT);
   1390                 break;
   1391             case 0xd3:
   1392                 kbd_put_keysym(QEMU_KEY_DELETE);
   1393                 break;
   1394             case 0xc7:
   1395                 kbd_put_keysym(QEMU_KEY_HOME);
   1396                 break;
   1397             case 0xcf:
   1398                 kbd_put_keysym(QEMU_KEY_END);
   1399                 break;
   1400             case 0xc9:
   1401                 kbd_put_keysym(QEMU_KEY_PAGEUP);
   1402                 break;
   1403             case 0xd1:
   1404                 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
   1405                 break;
   1406 
   1407             case 0x47:
   1408                 kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
   1409                 break;
   1410             case 0x48:
   1411                 kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
   1412                 break;
   1413             case 0x49:
   1414                 kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
   1415                 break;
   1416             case 0x4b:
   1417                 kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
   1418                 break;
   1419             case 0x4c:
   1420                 kbd_put_keysym('5');
   1421                 break;
   1422             case 0x4d:
   1423                 kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
   1424                 break;
   1425             case 0x4f:
   1426                 kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
   1427                 break;
   1428             case 0x50:
   1429                 kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
   1430                 break;
   1431             case 0x51:
   1432                 kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
   1433                 break;
   1434             case 0x52:
   1435                 kbd_put_keysym('0');
   1436                 break;
   1437             case 0x53:
   1438                 kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
   1439                 break;
   1440 
   1441             case 0xb5:
   1442                 kbd_put_keysym('/');
   1443                 break;
   1444             case 0x37:
   1445                 kbd_put_keysym('*');
   1446                 break;
   1447             case 0x4a:
   1448                 kbd_put_keysym('-');
   1449                 break;
   1450             case 0x4e:
   1451                 kbd_put_keysym('+');
   1452                 break;
   1453             case 0x9c:
   1454                 kbd_put_keysym('\n');
   1455                 break;
   1456 
   1457             default:
   1458                 kbd_put_keysym(sym);
   1459                 break;
   1460             }
   1461         }
   1462     }
   1463 }
   1464 
   1465 static void key_event(VncState *vs, int down, uint32_t sym)
   1466 {
   1467     int keycode;
   1468 
   1469     if (sym >= 'A' && sym <= 'Z' && is_graphic_console())
   1470         sym = sym - 'A' + 'a';
   1471 
   1472     keycode = keysym2scancode(vs->vd->kbd_layout, sym & 0xFFFF);
   1473     do_key_event(vs, down, keycode, sym);
   1474 }
   1475 
   1476 static void ext_key_event(VncState *vs, int down,
   1477                           uint32_t sym, uint16_t keycode)
   1478 {
   1479     /* if the user specifies a keyboard layout, always use it */
   1480     if (keyboard_layout)
   1481         key_event(vs, down, sym);
   1482     else
   1483         do_key_event(vs, down, keycode, sym);
   1484 }
   1485 
   1486 static void framebuffer_update_request(VncState *vs, int incremental,
   1487                                        int x_position, int y_position,
   1488                                        int w, int h)
   1489 {
   1490     if (x_position > ds_get_width(vs->ds))
   1491         x_position = ds_get_width(vs->ds);
   1492     if (y_position > ds_get_height(vs->ds))
   1493         y_position = ds_get_height(vs->ds);
   1494     if (x_position + w >= ds_get_width(vs->ds))
   1495         w = ds_get_width(vs->ds)  - x_position;
   1496     if (y_position + h >= ds_get_height(vs->ds))
   1497         h = ds_get_height(vs->ds) - y_position;
   1498 
   1499     int i;
   1500     vs->need_update = 1;
   1501     if (!incremental) {
   1502         vs->force_update = 1;
   1503         for (i = 0; i < h; i++) {
   1504             vnc_set_bits(vs->guest.dirty[y_position + i],
   1505                          (ds_get_width(vs->ds) / 16), VNC_DIRTY_WORDS);
   1506             vnc_set_bits(vs->server.dirty[y_position + i],
   1507                          (ds_get_width(vs->ds) / 16), VNC_DIRTY_WORDS);
   1508         }
   1509     }
   1510 }
   1511 
   1512 static void send_ext_key_event_ack(VncState *vs)
   1513 {
   1514     vnc_write_u8(vs, 0);
   1515     vnc_write_u8(vs, 0);
   1516     vnc_write_u16(vs, 1);
   1517     vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
   1518                            VNC_ENCODING_EXT_KEY_EVENT);
   1519     vnc_flush(vs);
   1520 }
   1521 
   1522 static void send_ext_audio_ack(VncState *vs)
   1523 {
   1524     vnc_write_u8(vs, 0);
   1525     vnc_write_u8(vs, 0);
   1526     vnc_write_u16(vs, 1);
   1527     vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
   1528                            VNC_ENCODING_AUDIO);
   1529     vnc_flush(vs);
   1530 }
   1531 
   1532 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
   1533 {
   1534     int i;
   1535     unsigned int enc = 0;
   1536 
   1537     vnc_zlib_init(vs);
   1538     vs->features = 0;
   1539     vs->vnc_encoding = 0;
   1540     vs->tight_compression = 9;
   1541     vs->tight_quality = 9;
   1542     vs->absolute = -1;
   1543 
   1544     for (i = n_encodings - 1; i >= 0; i--) {
   1545         enc = encodings[i];
   1546         switch (enc) {
   1547         case VNC_ENCODING_RAW:
   1548             vs->vnc_encoding = enc;
   1549             break;
   1550         case VNC_ENCODING_COPYRECT:
   1551             vs->features |= VNC_FEATURE_COPYRECT_MASK;
   1552             break;
   1553         case VNC_ENCODING_HEXTILE:
   1554             vs->features |= VNC_FEATURE_HEXTILE_MASK;
   1555             vs->vnc_encoding = enc;
   1556             break;
   1557         case VNC_ENCODING_ZLIB:
   1558             vs->features |= VNC_FEATURE_ZLIB_MASK;
   1559             vs->vnc_encoding = enc;
   1560             break;
   1561         case VNC_ENCODING_DESKTOPRESIZE:
   1562             vs->features |= VNC_FEATURE_RESIZE_MASK;
   1563             break;
   1564         case VNC_ENCODING_POINTER_TYPE_CHANGE:
   1565             vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
   1566             break;
   1567         case VNC_ENCODING_EXT_KEY_EVENT:
   1568             send_ext_key_event_ack(vs);
   1569             break;
   1570         case VNC_ENCODING_AUDIO:
   1571             send_ext_audio_ack(vs);
   1572             break;
   1573         case VNC_ENCODING_WMVi:
   1574             vs->features |= VNC_FEATURE_WMVI_MASK;
   1575             break;
   1576         case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
   1577             vs->tight_compression = (enc & 0x0F);
   1578             break;
   1579         case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
   1580             vs->tight_quality = (enc & 0x0F);
   1581             break;
   1582         default:
   1583             VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
   1584             break;
   1585         }
   1586     }
   1587 
   1588     check_pointer_type_change(vs, kbd_mouse_is_absolute());
   1589 }
   1590 
   1591 static void set_pixel_conversion(VncState *vs)
   1592 {
   1593     if ((vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) ==
   1594         (vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG) &&
   1595         !memcmp(&(vs->clientds.pf), &(vs->ds->surface->pf), sizeof(PixelFormat))) {
   1596         vs->write_pixels = vnc_write_pixels_copy;
   1597         switch (vs->ds->surface->pf.bits_per_pixel) {
   1598             case 8:
   1599                 vs->send_hextile_tile = send_hextile_tile_8;
   1600                 break;
   1601             case 16:
   1602                 vs->send_hextile_tile = send_hextile_tile_16;
   1603                 break;
   1604             case 32:
   1605                 vs->send_hextile_tile = send_hextile_tile_32;
   1606                 break;
   1607         }
   1608     } else {
   1609         vs->write_pixels = vnc_write_pixels_generic;
   1610         switch (vs->ds->surface->pf.bits_per_pixel) {
   1611             case 8:
   1612                 vs->send_hextile_tile = send_hextile_tile_generic_8;
   1613                 break;
   1614             case 16:
   1615                 vs->send_hextile_tile = send_hextile_tile_generic_16;
   1616                 break;
   1617             case 32:
   1618                 vs->send_hextile_tile = send_hextile_tile_generic_32;
   1619                 break;
   1620         }
   1621     }
   1622 }
   1623 
   1624 static void set_pixel_format(VncState *vs,
   1625                              int bits_per_pixel, int depth,
   1626                              int big_endian_flag, int true_color_flag,
   1627                              int red_max, int green_max, int blue_max,
   1628                              int red_shift, int green_shift, int blue_shift)
   1629 {
   1630     if (!true_color_flag) {
   1631         vnc_client_error(vs);
   1632         return;
   1633     }
   1634 
   1635     vs->clientds = *(vs->guest.ds);
   1636     vs->clientds.pf.rmax = red_max;
   1637     count_bits(vs->clientds.pf.rbits, red_max);
   1638     vs->clientds.pf.rshift = red_shift;
   1639     vs->clientds.pf.rmask = red_max << red_shift;
   1640     vs->clientds.pf.gmax = green_max;
   1641     count_bits(vs->clientds.pf.gbits, green_max);
   1642     vs->clientds.pf.gshift = green_shift;
   1643     vs->clientds.pf.gmask = green_max << green_shift;
   1644     vs->clientds.pf.bmax = blue_max;
   1645     count_bits(vs->clientds.pf.bbits, blue_max);
   1646     vs->clientds.pf.bshift = blue_shift;
   1647     vs->clientds.pf.bmask = blue_max << blue_shift;
   1648     vs->clientds.pf.bits_per_pixel = bits_per_pixel;
   1649     vs->clientds.pf.bytes_per_pixel = bits_per_pixel / 8;
   1650     vs->clientds.pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
   1651     vs->clientds.flags = big_endian_flag ? QEMU_BIG_ENDIAN_FLAG : 0x00;
   1652 
   1653     set_pixel_conversion(vs);
   1654 
   1655     vga_hw_invalidate();
   1656     vga_hw_update();
   1657 }
   1658 
   1659 static void pixel_format_message (VncState *vs) {
   1660     char pad[3] = { 0, 0, 0 };
   1661 
   1662     vnc_write_u8(vs, vs->ds->surface->pf.bits_per_pixel); /* bits-per-pixel */
   1663     vnc_write_u8(vs, vs->ds->surface->pf.depth); /* depth */
   1664 
   1665 #ifdef HOST_WORDS_BIGENDIAN
   1666     vnc_write_u8(vs, 1);             /* big-endian-flag */
   1667 #else
   1668     vnc_write_u8(vs, 0);             /* big-endian-flag */
   1669 #endif
   1670     vnc_write_u8(vs, 1);             /* true-color-flag */
   1671     vnc_write_u16(vs, vs->ds->surface->pf.rmax);     /* red-max */
   1672     vnc_write_u16(vs, vs->ds->surface->pf.gmax);     /* green-max */
   1673     vnc_write_u16(vs, vs->ds->surface->pf.bmax);     /* blue-max */
   1674     vnc_write_u8(vs, vs->ds->surface->pf.rshift);    /* red-shift */
   1675     vnc_write_u8(vs, vs->ds->surface->pf.gshift);    /* green-shift */
   1676     vnc_write_u8(vs, vs->ds->surface->pf.bshift);    /* blue-shift */
   1677     if (vs->ds->surface->pf.bits_per_pixel == 32)
   1678         vs->send_hextile_tile = send_hextile_tile_32;
   1679     else if (vs->ds->surface->pf.bits_per_pixel == 16)
   1680         vs->send_hextile_tile = send_hextile_tile_16;
   1681     else if (vs->ds->surface->pf.bits_per_pixel == 8)
   1682         vs->send_hextile_tile = send_hextile_tile_8;
   1683     vs->clientds = *(vs->ds->surface);
   1684     vs->clientds.flags &= ~QEMU_ALLOCATED_FLAG;
   1685     vs->write_pixels = vnc_write_pixels_copy;
   1686 
   1687     vnc_write(vs, pad, 3);           /* padding */
   1688 }
   1689 
   1690 static void vnc_dpy_setdata(DisplayState *ds)
   1691 {
   1692     /* We don't have to do anything */
   1693 }
   1694 
   1695 static void vnc_colordepth(VncState *vs)
   1696 {
   1697     if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
   1698         /* Sending a WMVi message to notify the client*/
   1699         vnc_write_u8(vs, 0);  /* msg id */
   1700         vnc_write_u8(vs, 0);
   1701         vnc_write_u16(vs, 1); /* number of rects */
   1702         vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds),
   1703                                ds_get_height(vs->ds), VNC_ENCODING_WMVi);
   1704         pixel_format_message(vs);
   1705         vnc_flush(vs);
   1706     } else {
   1707         set_pixel_conversion(vs);
   1708     }
   1709 }
   1710 
   1711 static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
   1712 {
   1713     int i;
   1714     uint16_t limit;
   1715 
   1716     switch (data[0]) {
   1717     case 0:
   1718         if (len == 1)
   1719             return 20;
   1720 
   1721         set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
   1722                          read_u8(data, 6), read_u8(data, 7),
   1723                          read_u16(data, 8), read_u16(data, 10),
   1724                          read_u16(data, 12), read_u8(data, 14),
   1725                          read_u8(data, 15), read_u8(data, 16));
   1726         break;
   1727     case 2:
   1728         if (len == 1)
   1729             return 4;
   1730 
   1731         if (len == 4) {
   1732             limit = read_u16(data, 2);
   1733             if (limit > 0)
   1734                 return 4 + (limit * 4);
   1735         } else
   1736             limit = read_u16(data, 2);
   1737 
   1738         for (i = 0; i < limit; i++) {
   1739             int32_t val = read_s32(data, 4 + (i * 4));
   1740             memcpy(data + 4 + (i * 4), &val, sizeof(val));
   1741         }
   1742 
   1743         set_encodings(vs, (int32_t *)(data + 4), limit);
   1744         break;
   1745     case 3:
   1746         if (len == 1)
   1747             return 10;
   1748 
   1749         framebuffer_update_request(vs,
   1750                                    read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
   1751                                    read_u16(data, 6), read_u16(data, 8));
   1752         break;
   1753     case 4:
   1754         if (len == 1)
   1755             return 8;
   1756 
   1757         key_event(vs, read_u8(data, 1), read_u32(data, 4));
   1758         break;
   1759     case 5:
   1760         if (len == 1)
   1761             return 6;
   1762 
   1763         pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
   1764         break;
   1765     case 6:
   1766         if (len == 1)
   1767             return 8;
   1768 
   1769         if (len == 8) {
   1770             uint32_t dlen = read_u32(data, 4);
   1771             if (dlen > 0)
   1772                 return 8 + dlen;
   1773         }
   1774 
   1775         client_cut_text(vs, read_u32(data, 4), data + 8);
   1776         break;
   1777     case 255:
   1778         if (len == 1)
   1779             return 2;
   1780 
   1781         switch (read_u8(data, 1)) {
   1782         case 0:
   1783             if (len == 2)
   1784                 return 12;
   1785 
   1786             ext_key_event(vs, read_u16(data, 2),
   1787                           read_u32(data, 4), read_u32(data, 8));
   1788             break;
   1789         case 1:
   1790             if (len == 2)
   1791                 return 4;
   1792 
   1793             switch (read_u16 (data, 2)) {
   1794             case 0:
   1795                 audio_add(vs);
   1796                 break;
   1797             case 1:
   1798                 audio_del(vs);
   1799                 break;
   1800             case 2:
   1801                 if (len == 4)
   1802                     return 10;
   1803                 switch (read_u8(data, 4)) {
   1804                 case 0: vs->as.fmt = AUD_FMT_U8; break;
   1805                 case 1: vs->as.fmt = AUD_FMT_S8; break;
   1806                 case 2: vs->as.fmt = AUD_FMT_U16; break;
   1807                 case 3: vs->as.fmt = AUD_FMT_S16; break;
   1808                 case 4: vs->as.fmt = AUD_FMT_U32; break;
   1809                 case 5: vs->as.fmt = AUD_FMT_S32; break;
   1810                 default:
   1811                     printf("Invalid audio format %d\n", read_u8(data, 4));
   1812                     vnc_client_error(vs);
   1813                     break;
   1814                 }
   1815                 vs->as.nchannels = read_u8(data, 5);
   1816                 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
   1817                     printf("Invalid audio channel coount %d\n",
   1818                            read_u8(data, 5));
   1819                     vnc_client_error(vs);
   1820                     break;
   1821                 }
   1822                 vs->as.freq = read_u32(data, 6);
   1823                 break;
   1824             default:
   1825                 printf ("Invalid audio message %d\n", read_u8(data, 4));
   1826                 vnc_client_error(vs);
   1827                 break;
   1828             }
   1829             break;
   1830 
   1831         default:
   1832             printf("Msg: %d\n", read_u16(data, 0));
   1833             vnc_client_error(vs);
   1834             break;
   1835         }
   1836         break;
   1837     default:
   1838         printf("Msg: %d\n", data[0]);
   1839         vnc_client_error(vs);
   1840         break;
   1841     }
   1842 
   1843     vnc_read_when(vs, protocol_client_msg, 1);
   1844     return 0;
   1845 }
   1846 
   1847 static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
   1848 {
   1849     char buf[1024];
   1850     int size;
   1851 
   1852     vnc_write_u16(vs, ds_get_width(vs->ds));
   1853     vnc_write_u16(vs, ds_get_height(vs->ds));
   1854 
   1855     pixel_format_message(vs);
   1856 
   1857     if (qemu_name)
   1858         size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
   1859     else
   1860         size = snprintf(buf, sizeof(buf), "QEMU");
   1861 
   1862     vnc_write_u32(vs, size);
   1863     vnc_write(vs, buf, size);
   1864     vnc_flush(vs);
   1865 
   1866     vnc_read_when(vs, protocol_client_msg, 1);
   1867 
   1868     return 0;
   1869 }
   1870 
   1871 void start_client_init(VncState *vs)
   1872 {
   1873     vnc_read_when(vs, protocol_client_init, 1);
   1874 }
   1875 
   1876 static void make_challenge(VncState *vs)
   1877 {
   1878     int i;
   1879 
   1880     srand(time(NULL)+getpid()+getpid()*987654+rand());
   1881 
   1882     for (i = 0 ; i < sizeof(vs->challenge) ; i++)
   1883         vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
   1884 }
   1885 
   1886 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
   1887 {
   1888     unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
   1889     int i, j, pwlen;
   1890     unsigned char key[8];
   1891 
   1892     if (!vs->vd->password || !vs->vd->password[0]) {
   1893         VNC_DEBUG("No password configured on server");
   1894         vnc_write_u32(vs, 1); /* Reject auth */
   1895         if (vs->minor >= 8) {
   1896             static const char err[] = "Authentication failed";
   1897             vnc_write_u32(vs, sizeof(err));
   1898             vnc_write(vs, err, sizeof(err));
   1899         }
   1900         vnc_flush(vs);
   1901         vnc_client_error(vs);
   1902         return 0;
   1903     }
   1904 
   1905     memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
   1906 
   1907     /* Calculate the expected challenge response */
   1908     pwlen = strlen(vs->vd->password);
   1909     for (i=0; i<sizeof(key); i++)
   1910         key[i] = i<pwlen ? vs->vd->password[i] : 0;
   1911     deskey(key, EN0);
   1912     for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
   1913         des(response+j, response+j);
   1914 
   1915     /* Compare expected vs actual challenge response */
   1916     if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
   1917         VNC_DEBUG("Client challenge reponse did not match\n");
   1918         vnc_write_u32(vs, 1); /* Reject auth */
   1919         if (vs->minor >= 8) {
   1920             static const char err[] = "Authentication failed";
   1921             vnc_write_u32(vs, sizeof(err));
   1922             vnc_write(vs, err, sizeof(err));
   1923         }
   1924         vnc_flush(vs);
   1925         vnc_client_error(vs);
   1926     } else {
   1927         VNC_DEBUG("Accepting VNC challenge response\n");
   1928         vnc_write_u32(vs, 0); /* Accept auth */
   1929         vnc_flush(vs);
   1930 
   1931         start_client_init(vs);
   1932     }
   1933     return 0;
   1934 }
   1935 
   1936 void start_auth_vnc(VncState *vs)
   1937 {
   1938     make_challenge(vs);
   1939     /* Send client a 'random' challenge */
   1940     vnc_write(vs, vs->challenge, sizeof(vs->challenge));
   1941     vnc_flush(vs);
   1942 
   1943     vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
   1944 }
   1945 
   1946 
   1947 static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
   1948 {
   1949     /* We only advertise 1 auth scheme at a time, so client
   1950      * must pick the one we sent. Verify this */
   1951     if (data[0] != vs->vd->auth) { /* Reject auth */
   1952        VNC_DEBUG("Reject auth %d because it didn't match advertized\n", (int)data[0]);
   1953        vnc_write_u32(vs, 1);
   1954        if (vs->minor >= 8) {
   1955            static const char err[] = "Authentication failed";
   1956            vnc_write_u32(vs, sizeof(err));
   1957            vnc_write(vs, err, sizeof(err));
   1958        }
   1959        vnc_client_error(vs);
   1960     } else { /* Accept requested auth */
   1961        VNC_DEBUG("Client requested auth %d\n", (int)data[0]);
   1962        switch (vs->vd->auth) {
   1963        case VNC_AUTH_NONE:
   1964            VNC_DEBUG("Accept auth none\n");
   1965            if (vs->minor >= 8) {
   1966                vnc_write_u32(vs, 0); /* Accept auth completion */
   1967                vnc_flush(vs);
   1968            }
   1969            start_client_init(vs);
   1970            break;
   1971 
   1972        case VNC_AUTH_VNC:
   1973            VNC_DEBUG("Start VNC auth\n");
   1974            start_auth_vnc(vs);
   1975            break;
   1976 
   1977 #ifdef CONFIG_VNC_TLS
   1978        case VNC_AUTH_VENCRYPT:
   1979            VNC_DEBUG("Accept VeNCrypt auth\n");;
   1980            start_auth_vencrypt(vs);
   1981            break;
   1982 #endif /* CONFIG_VNC_TLS */
   1983 
   1984 #ifdef CONFIG_VNC_SASL
   1985        case VNC_AUTH_SASL:
   1986            VNC_DEBUG("Accept SASL auth\n");
   1987            start_auth_sasl(vs);
   1988            break;
   1989 #endif /* CONFIG_VNC_SASL */
   1990 
   1991        default: /* Should not be possible, but just in case */
   1992            VNC_DEBUG("Reject auth %d server code bug\n", vs->vd->auth);
   1993            vnc_write_u8(vs, 1);
   1994            if (vs->minor >= 8) {
   1995                static const char err[] = "Authentication failed";
   1996                vnc_write_u32(vs, sizeof(err));
   1997                vnc_write(vs, err, sizeof(err));
   1998            }
   1999            vnc_client_error(vs);
   2000        }
   2001     }
   2002     return 0;
   2003 }
   2004 
   2005 static int protocol_version(VncState *vs, uint8_t *version, size_t len)
   2006 {
   2007     char local[13];
   2008 
   2009     memcpy(local, version, 12);
   2010     local[12] = 0;
   2011 
   2012     if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
   2013         VNC_DEBUG("Malformed protocol version %s\n", local);
   2014         vnc_client_error(vs);
   2015         return 0;
   2016     }
   2017     VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
   2018     if (vs->major != 3 ||
   2019         (vs->minor != 3 &&
   2020          vs->minor != 4 &&
   2021          vs->minor != 5 &&
   2022          vs->minor != 7 &&
   2023          vs->minor != 8)) {
   2024         VNC_DEBUG("Unsupported client version\n");
   2025         vnc_write_u32(vs, VNC_AUTH_INVALID);
   2026         vnc_flush(vs);
   2027         vnc_client_error(vs);
   2028         return 0;
   2029     }
   2030     /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
   2031      * as equivalent to v3.3 by servers
   2032      */
   2033     if (vs->minor == 4 || vs->minor == 5)
   2034         vs->minor = 3;
   2035 
   2036     if (vs->minor == 3) {
   2037         if (vs->vd->auth == VNC_AUTH_NONE) {
   2038             VNC_DEBUG("Tell client auth none\n");
   2039             vnc_write_u32(vs, vs->vd->auth);
   2040             vnc_flush(vs);
   2041             start_client_init(vs);
   2042        } else if (vs->vd->auth == VNC_AUTH_VNC) {
   2043             VNC_DEBUG("Tell client VNC auth\n");
   2044             vnc_write_u32(vs, vs->vd->auth);
   2045             vnc_flush(vs);
   2046             start_auth_vnc(vs);
   2047        } else {
   2048             VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->vd->auth);
   2049             vnc_write_u32(vs, VNC_AUTH_INVALID);
   2050             vnc_flush(vs);
   2051             vnc_client_error(vs);
   2052        }
   2053     } else {
   2054         VNC_DEBUG("Telling client we support auth %d\n", vs->vd->auth);
   2055         vnc_write_u8(vs, 1); /* num auth */
   2056         vnc_write_u8(vs, vs->vd->auth);
   2057         vnc_read_when(vs, protocol_client_auth, 1);
   2058         vnc_flush(vs);
   2059     }
   2060 
   2061     return 0;
   2062 }
   2063 
   2064 static void vnc_connect(VncDisplay *vd, int csock)
   2065 {
   2066     VncState *vs = qemu_mallocz(sizeof(VncState));
   2067     vs->csock = csock;
   2068 
   2069     VNC_DEBUG("New client on socket %d\n", csock);
   2070     dcl->idle = 0;
   2071     socket_set_nonblock(vs->csock);
   2072     qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
   2073 
   2074     vs->vd = vd;
   2075     vs->ds = vd->ds;
   2076     vs->timer = qemu_new_timer_ms(rt_clock, vnc_update_client, vs);
   2077     vs->last_x = -1;
   2078     vs->last_y = -1;
   2079 
   2080     vs->as.freq = 44100;
   2081     vs->as.nchannels = 2;
   2082     vs->as.fmt = AUD_FMT_S16;
   2083     vs->as.endianness = 0;
   2084 
   2085     vnc_resize(vs);
   2086     vnc_write(vs, "RFB 003.008\n", 12);
   2087     vnc_flush(vs);
   2088     vnc_read_when(vs, protocol_version, 12);
   2089     reset_keys(vs);
   2090 
   2091     vs->next = vd->clients;
   2092     vd->clients = vs;
   2093 
   2094     vnc_update_client(vs);
   2095     /* vs might be free()ed here */
   2096 }
   2097 
   2098 static void vnc_listen_read(void *opaque)
   2099 {
   2100     VncDisplay *vs = opaque;
   2101 
   2102     /* Catch-up */
   2103     vga_hw_update();
   2104 
   2105     int csock = socket_accept(vs->lsock, NULL);
   2106     if (csock != -1) {
   2107         vnc_connect(vs, csock);
   2108     }
   2109 }
   2110 
   2111 void vnc_display_init(DisplayState *ds)
   2112 {
   2113     VncDisplay *vs = qemu_mallocz(sizeof(*vs));
   2114 
   2115     dcl = qemu_mallocz(sizeof(DisplayChangeListener));
   2116 
   2117     ds->opaque = vs;
   2118     dcl->idle = 1;
   2119     vnc_display = vs;
   2120 
   2121     vs->lsock = -1;
   2122 
   2123     vs->ds = ds;
   2124 
   2125     if (keyboard_layout)
   2126         vs->kbd_layout = init_keyboard_layout(name2keysym, keyboard_layout);
   2127     else
   2128         vs->kbd_layout = init_keyboard_layout(name2keysym, "en-us");
   2129 
   2130     if (!vs->kbd_layout)
   2131         exit(1);
   2132 
   2133     dcl->dpy_copy = vnc_dpy_copy;
   2134     dcl->dpy_update = vnc_dpy_update;
   2135     dcl->dpy_resize = vnc_dpy_resize;
   2136     dcl->dpy_setdata = vnc_dpy_setdata;
   2137     register_displaychangelistener(ds, dcl);
   2138 }
   2139 
   2140 
   2141 void vnc_display_close(DisplayState *ds)
   2142 {
   2143     VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
   2144 
   2145     if (!vs)
   2146         return;
   2147     if (vs->display) {
   2148         qemu_free(vs->display);
   2149         vs->display = NULL;
   2150     }
   2151     if (vs->lsock != -1) {
   2152         qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);
   2153         close(vs->lsock);
   2154         vs->lsock = -1;
   2155     }
   2156     vs->auth = VNC_AUTH_INVALID;
   2157 #ifdef CONFIG_VNC_TLS
   2158     vs->subauth = VNC_AUTH_INVALID;
   2159     vs->tls.x509verify = 0;
   2160 #endif
   2161 }
   2162 
   2163 int vnc_display_password(DisplayState *ds, const char *password)
   2164 {
   2165     VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
   2166 
   2167     if (vs->password) {
   2168         qemu_free(vs->password);
   2169         vs->password = NULL;
   2170     }
   2171     if (password && password[0]) {
   2172         if (!(vs->password = qemu_strdup(password)))
   2173             return -1;
   2174     }
   2175 
   2176     return 0;
   2177 }
   2178 
   2179 char *vnc_display_local_addr(DisplayState *ds)
   2180 {
   2181     VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
   2182 
   2183     return vnc_socket_local_addr("%s:%s", vs->lsock);
   2184 }
   2185 
   2186 int vnc_display_open(DisplayState *ds, const char *display)
   2187 {
   2188     VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
   2189     const char *options;
   2190     int password = 0;
   2191     int reverse = 0;
   2192     int to_port = 0;
   2193 #ifdef CONFIG_VNC_TLS
   2194     int tls = 0, x509 = 0;
   2195 #endif
   2196 #ifdef CONFIG_VNC_SASL
   2197     int sasl = 0;
   2198     int saslErr;
   2199 #endif
   2200     int acl = 0;
   2201 
   2202     if (!vnc_display)
   2203         return -1;
   2204     vnc_display_close(ds);
   2205     if (strcmp(display, "none") == 0)
   2206         return 0;
   2207 
   2208     if (!(vs->display = strdup(display)))
   2209         return -1;
   2210 
   2211     options = display;
   2212     while ((options = strchr(options, ','))) {
   2213         options++;
   2214         if (strncmp(options, "password", 8) == 0) {
   2215             password = 1; /* Require password auth */
   2216         } else if (strncmp(options, "reverse", 7) == 0) {
   2217             reverse = 1;
   2218         } else if (strncmp(options, "to=", 3) == 0) {
   2219             to_port = atoi(options+3) + 5900;
   2220 #ifdef CONFIG_VNC_SASL
   2221         } else if (strncmp(options, "sasl", 4) == 0) {
   2222             sasl = 1; /* Require SASL auth */
   2223 #endif
   2224 #ifdef CONFIG_VNC_TLS
   2225         } else if (strncmp(options, "tls", 3) == 0) {
   2226             tls = 1; /* Require TLS */
   2227         } else if (strncmp(options, "x509", 4) == 0) {
   2228             char *start, *end;
   2229             x509 = 1; /* Require x509 certificates */
   2230             if (strncmp(options, "x509verify", 10) == 0)
   2231                 vs->tls.x509verify = 1; /* ...and verify client certs */
   2232 
   2233             /* Now check for 'x509=/some/path' postfix
   2234              * and use that to setup x509 certificate/key paths */
   2235             start = strchr(options, '=');
   2236             end = strchr(options, ',');
   2237             if (start && (!end || (start < end))) {
   2238                 int len = end ? end-(start+1) : strlen(start+1);
   2239                 char *path = qemu_strndup(start + 1, len);
   2240 
   2241                 VNC_DEBUG("Trying certificate path '%s'\n", path);
   2242                 if (vnc_tls_set_x509_creds_dir(vs, path) < 0) {
   2243                     fprintf(stderr, "Failed to find x509 certificates/keys in %s\n", path);
   2244                     qemu_free(path);
   2245                     qemu_free(vs->display);
   2246                     vs->display = NULL;
   2247                     return -1;
   2248                 }
   2249                 qemu_free(path);
   2250             } else {
   2251                 fprintf(stderr, "No certificate path provided\n");
   2252                 qemu_free(vs->display);
   2253                 vs->display = NULL;
   2254                 return -1;
   2255             }
   2256 #endif
   2257         } else if (strncmp(options, "acl", 3) == 0) {
   2258             acl = 1;
   2259         }
   2260     }
   2261 
   2262 #ifdef CONFIG_VNC_TLS
   2263     if (acl && x509 && vs->tls.x509verify) {
   2264         if (!(vs->tls.acl = qemu_acl_init("vnc.x509dname"))) {
   2265             fprintf(stderr, "Failed to create x509 dname ACL\n");
   2266             exit(1);
   2267         }
   2268     }
   2269 #endif
   2270 #ifdef CONFIG_VNC_SASL
   2271     if (acl && sasl) {
   2272         if (!(vs->sasl.acl = qemu_acl_init("vnc.username"))) {
   2273             fprintf(stderr, "Failed to create username ACL\n");
   2274             exit(1);
   2275         }
   2276     }
   2277 #endif
   2278 
   2279     /*
   2280      * Combinations we support here:
   2281      *
   2282      *  - no-auth                (clear text, no auth)
   2283      *  - password               (clear text, weak auth)
   2284      *  - sasl                   (encrypt, good auth *IF* using Kerberos via GSSAPI)
   2285      *  - tls                    (encrypt, weak anonymous creds, no auth)
   2286      *  - tls + password         (encrypt, weak anonymous creds, weak auth)
   2287      *  - tls + sasl             (encrypt, weak anonymous creds, good auth)
   2288      *  - tls + x509             (encrypt, good x509 creds, no auth)
   2289      *  - tls + x509 + password  (encrypt, good x509 creds, weak auth)
   2290      *  - tls + x509 + sasl      (encrypt, good x509 creds, good auth)
   2291      *
   2292      * NB1. TLS is a stackable auth scheme.
   2293      * NB2. the x509 schemes have option to validate a client cert dname
   2294      */
   2295     if (password) {
   2296 #ifdef CONFIG_VNC_TLS
   2297         if (tls) {
   2298             vs->auth = VNC_AUTH_VENCRYPT;
   2299             if (x509) {
   2300                 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
   2301                 vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;
   2302             } else {
   2303                 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
   2304                 vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
   2305             }
   2306         } else {
   2307 #endif /* CONFIG_VNC_TLS */
   2308             VNC_DEBUG("Initializing VNC server with password auth\n");
   2309             vs->auth = VNC_AUTH_VNC;
   2310 #ifdef CONFIG_VNC_TLS
   2311             vs->subauth = VNC_AUTH_INVALID;
   2312         }
   2313 #endif /* CONFIG_VNC_TLS */
   2314 #ifdef CONFIG_VNC_SASL
   2315     } else if (sasl) {
   2316 #ifdef CONFIG_VNC_TLS
   2317         if (tls) {
   2318             vs->auth = VNC_AUTH_VENCRYPT;
   2319             if (x509) {
   2320                 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
   2321                 vs->subauth = VNC_AUTH_VENCRYPT_X509SASL;
   2322             } else {
   2323                 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
   2324                 vs->subauth = VNC_AUTH_VENCRYPT_TLSSASL;
   2325             }
   2326         } else {
   2327 #endif /* CONFIG_VNC_TLS */
   2328             VNC_DEBUG("Initializing VNC server with SASL auth\n");
   2329             vs->auth = VNC_AUTH_SASL;
   2330 #ifdef CONFIG_VNC_TLS
   2331             vs->subauth = VNC_AUTH_INVALID;
   2332         }
   2333 #endif /* CONFIG_VNC_TLS */
   2334 #endif /* CONFIG_VNC_SASL */
   2335     } else {
   2336 #ifdef CONFIG_VNC_TLS
   2337         if (tls) {
   2338             vs->auth = VNC_AUTH_VENCRYPT;
   2339             if (x509) {
   2340                 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
   2341                 vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;
   2342             } else {
   2343                 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
   2344                 vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
   2345             }
   2346         } else {
   2347 #endif
   2348             VNC_DEBUG("Initializing VNC server with no auth\n");
   2349             vs->auth = VNC_AUTH_NONE;
   2350 #ifdef CONFIG_VNC_TLS
   2351             vs->subauth = VNC_AUTH_INVALID;
   2352         }
   2353 #endif
   2354     }
   2355 
   2356 #ifdef CONFIG_VNC_SASL
   2357     if ((saslErr = sasl_server_init(NULL, "qemu")) != SASL_OK) {
   2358         fprintf(stderr, "Failed to initialize SASL auth %s",
   2359                 sasl_errstring(saslErr, NULL, NULL));
   2360         free(vs->display);
   2361         vs->display = NULL;
   2362         return -1;
   2363     }
   2364 #endif
   2365 
   2366     if (reverse) {
   2367         /* connect to viewer */
   2368         if (strncmp(display, "unix:", 5) == 0)
   2369             vs->lsock = unix_connect(display+5);
   2370         else
   2371             vs->lsock = inet_connect(display, SOCKET_STREAM);
   2372         if (-1 == vs->lsock) {
   2373             free(vs->display);
   2374             vs->display = NULL;
   2375             return -1;
   2376         } else {
   2377             int csock = vs->lsock;
   2378             vs->lsock = -1;
   2379             vnc_connect(vs, csock);
   2380         }
   2381         return 0;
   2382 
   2383     } else {
   2384         /* listen for connects */
   2385         char *dpy;
   2386         dpy = qemu_malloc(256);
   2387         if (strncmp(display, "unix:", 5) == 0) {
   2388             pstrcpy(dpy, 256, "unix:");
   2389             vs->lsock = unix_listen(display+5, dpy+5, 256-5);
   2390         } else {
   2391             vs->lsock = inet_listen(display, dpy, 256, SOCKET_STREAM, 5900);
   2392         }
   2393         if (-1 == vs->lsock) {
   2394             free(dpy);
   2395             return -1;
   2396         } else {
   2397             free(vs->display);
   2398             vs->display = dpy;
   2399         }
   2400     }
   2401     return qemu_set_fd_handler2(vs->lsock, NULL, vnc_listen_read, NULL, vs);
   2402 }
   2403