xref: /openbmc/qemu/ui/vnc.c (revision d901eff3)
1 /*
2  * QEMU VNC display driver
3  *
4  * Copyright (C) 2006 Anthony Liguori <anthony@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 "vnc-jobs.h"
29 #include "sysemu.h"
30 #include "qemu_socket.h"
31 #include "qemu-timer.h"
32 #include "acl.h"
33 #include "qemu-objects.h"
34 #include "qmp-commands.h"
35 
36 #define VNC_REFRESH_INTERVAL_BASE 30
37 #define VNC_REFRESH_INTERVAL_INC  50
38 #define VNC_REFRESH_INTERVAL_MAX  2000
39 static const struct timeval VNC_REFRESH_STATS = { 0, 500000 };
40 static const struct timeval VNC_REFRESH_LOSSY = { 2, 0 };
41 
42 #include "vnc_keysym.h"
43 #include "d3des.h"
44 
45 static VncDisplay *vnc_display; /* needed for info vnc */
46 static DisplayChangeListener *dcl;
47 
48 static int vnc_cursor_define(VncState *vs);
49 static void vnc_release_modifiers(VncState *vs);
50 
51 static void vnc_set_share_mode(VncState *vs, VncShareMode mode)
52 {
53 #ifdef _VNC_DEBUG
54     static const char *mn[] = {
55         [0]                           = "undefined",
56         [VNC_SHARE_MODE_CONNECTING]   = "connecting",
57         [VNC_SHARE_MODE_SHARED]       = "shared",
58         [VNC_SHARE_MODE_EXCLUSIVE]    = "exclusive",
59         [VNC_SHARE_MODE_DISCONNECTED] = "disconnected",
60     };
61     fprintf(stderr, "%s/%d: %s -> %s\n", __func__,
62             vs->csock, mn[vs->share_mode], mn[mode]);
63 #endif
64 
65     if (vs->share_mode == VNC_SHARE_MODE_EXCLUSIVE) {
66         vs->vd->num_exclusive--;
67     }
68     vs->share_mode = mode;
69     if (vs->share_mode == VNC_SHARE_MODE_EXCLUSIVE) {
70         vs->vd->num_exclusive++;
71     }
72 }
73 
74 static char *addr_to_string(const char *format,
75                             struct sockaddr_storage *sa,
76                             socklen_t salen) {
77     char *addr;
78     char host[NI_MAXHOST];
79     char serv[NI_MAXSERV];
80     int err;
81     size_t addrlen;
82 
83     if ((err = getnameinfo((struct sockaddr *)sa, salen,
84                            host, sizeof(host),
85                            serv, sizeof(serv),
86                            NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
87         VNC_DEBUG("Cannot resolve address %d: %s\n",
88                   err, gai_strerror(err));
89         return NULL;
90     }
91 
92     /* Enough for the existing format + the 2 vars we're
93      * substituting in. */
94     addrlen = strlen(format) + strlen(host) + strlen(serv);
95     addr = g_malloc(addrlen + 1);
96     snprintf(addr, addrlen, format, host, serv);
97     addr[addrlen] = '\0';
98 
99     return addr;
100 }
101 
102 
103 char *vnc_socket_local_addr(const char *format, int fd) {
104     struct sockaddr_storage sa;
105     socklen_t salen;
106 
107     salen = sizeof(sa);
108     if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0)
109         return NULL;
110 
111     return addr_to_string(format, &sa, salen);
112 }
113 
114 char *vnc_socket_remote_addr(const char *format, int fd) {
115     struct sockaddr_storage sa;
116     socklen_t salen;
117 
118     salen = sizeof(sa);
119     if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0)
120         return NULL;
121 
122     return addr_to_string(format, &sa, salen);
123 }
124 
125 static int put_addr_qdict(QDict *qdict, struct sockaddr_storage *sa,
126                           socklen_t salen)
127 {
128     char host[NI_MAXHOST];
129     char serv[NI_MAXSERV];
130     int err;
131 
132     if ((err = getnameinfo((struct sockaddr *)sa, salen,
133                            host, sizeof(host),
134                            serv, sizeof(serv),
135                            NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
136         VNC_DEBUG("Cannot resolve address %d: %s\n",
137                   err, gai_strerror(err));
138         return -1;
139     }
140 
141     qdict_put(qdict, "host", qstring_from_str(host));
142     qdict_put(qdict, "service", qstring_from_str(serv));
143     qdict_put(qdict, "family",qstring_from_str(inet_strfamily(sa->ss_family)));
144 
145     return 0;
146 }
147 
148 static int vnc_server_addr_put(QDict *qdict, int fd)
149 {
150     struct sockaddr_storage sa;
151     socklen_t salen;
152 
153     salen = sizeof(sa);
154     if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0) {
155         return -1;
156     }
157 
158     return put_addr_qdict(qdict, &sa, salen);
159 }
160 
161 static int vnc_qdict_remote_addr(QDict *qdict, int fd)
162 {
163     struct sockaddr_storage sa;
164     socklen_t salen;
165 
166     salen = sizeof(sa);
167     if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0) {
168         return -1;
169     }
170 
171     return put_addr_qdict(qdict, &sa, salen);
172 }
173 
174 static const char *vnc_auth_name(VncDisplay *vd) {
175     switch (vd->auth) {
176     case VNC_AUTH_INVALID:
177         return "invalid";
178     case VNC_AUTH_NONE:
179         return "none";
180     case VNC_AUTH_VNC:
181         return "vnc";
182     case VNC_AUTH_RA2:
183         return "ra2";
184     case VNC_AUTH_RA2NE:
185         return "ra2ne";
186     case VNC_AUTH_TIGHT:
187         return "tight";
188     case VNC_AUTH_ULTRA:
189         return "ultra";
190     case VNC_AUTH_TLS:
191         return "tls";
192     case VNC_AUTH_VENCRYPT:
193 #ifdef CONFIG_VNC_TLS
194         switch (vd->subauth) {
195         case VNC_AUTH_VENCRYPT_PLAIN:
196             return "vencrypt+plain";
197         case VNC_AUTH_VENCRYPT_TLSNONE:
198             return "vencrypt+tls+none";
199         case VNC_AUTH_VENCRYPT_TLSVNC:
200             return "vencrypt+tls+vnc";
201         case VNC_AUTH_VENCRYPT_TLSPLAIN:
202             return "vencrypt+tls+plain";
203         case VNC_AUTH_VENCRYPT_X509NONE:
204             return "vencrypt+x509+none";
205         case VNC_AUTH_VENCRYPT_X509VNC:
206             return "vencrypt+x509+vnc";
207         case VNC_AUTH_VENCRYPT_X509PLAIN:
208             return "vencrypt+x509+plain";
209         case VNC_AUTH_VENCRYPT_TLSSASL:
210             return "vencrypt+tls+sasl";
211         case VNC_AUTH_VENCRYPT_X509SASL:
212             return "vencrypt+x509+sasl";
213         default:
214             return "vencrypt";
215         }
216 #else
217         return "vencrypt";
218 #endif
219     case VNC_AUTH_SASL:
220         return "sasl";
221     }
222     return "unknown";
223 }
224 
225 static int vnc_server_info_put(QDict *qdict)
226 {
227     if (vnc_server_addr_put(qdict, vnc_display->lsock) < 0) {
228         return -1;
229     }
230 
231     qdict_put(qdict, "auth", qstring_from_str(vnc_auth_name(vnc_display)));
232     return 0;
233 }
234 
235 static void vnc_client_cache_auth(VncState *client)
236 {
237 #if defined(CONFIG_VNC_TLS) || defined(CONFIG_VNC_SASL)
238     QDict *qdict;
239 #endif
240 
241     if (!client->info) {
242         return;
243     }
244 
245 #if defined(CONFIG_VNC_TLS) || defined(CONFIG_VNC_SASL)
246     qdict = qobject_to_qdict(client->info);
247 #endif
248 
249 #ifdef CONFIG_VNC_TLS
250     if (client->tls.session &&
251         client->tls.dname) {
252         qdict_put(qdict, "x509_dname", qstring_from_str(client->tls.dname));
253     }
254 #endif
255 #ifdef CONFIG_VNC_SASL
256     if (client->sasl.conn &&
257         client->sasl.username) {
258         qdict_put(qdict, "sasl_username",
259                   qstring_from_str(client->sasl.username));
260     }
261 #endif
262 }
263 
264 static void vnc_client_cache_addr(VncState *client)
265 {
266     QDict *qdict;
267 
268     qdict = qdict_new();
269     if (vnc_qdict_remote_addr(qdict, client->csock) < 0) {
270         QDECREF(qdict);
271         /* XXX: how to report the error? */
272         return;
273     }
274 
275     client->info = QOBJECT(qdict);
276 }
277 
278 static void vnc_qmp_event(VncState *vs, MonitorEvent event)
279 {
280     QDict *server;
281     QObject *data;
282 
283     if (!vs->info) {
284         return;
285     }
286 
287     server = qdict_new();
288     if (vnc_server_info_put(server) < 0) {
289         QDECREF(server);
290         return;
291     }
292 
293     data = qobject_from_jsonf("{ 'client': %p, 'server': %p }",
294                               vs->info, QOBJECT(server));
295 
296     monitor_protocol_event(event, data);
297 
298     qobject_incref(vs->info);
299     qobject_decref(data);
300 }
301 
302 static VncClientInfo *qmp_query_vnc_client(const VncState *client)
303 {
304     struct sockaddr_storage sa;
305     socklen_t salen = sizeof(sa);
306     char host[NI_MAXHOST];
307     char serv[NI_MAXSERV];
308     VncClientInfo *info;
309 
310     if (getpeername(client->csock, (struct sockaddr *)&sa, &salen) < 0) {
311         return NULL;
312     }
313 
314     if (getnameinfo((struct sockaddr *)&sa, salen,
315                     host, sizeof(host),
316                     serv, sizeof(serv),
317                     NI_NUMERICHOST | NI_NUMERICSERV) < 0) {
318         return NULL;
319     }
320 
321     info = g_malloc0(sizeof(*info));
322     info->host = g_strdup(host);
323     info->service = g_strdup(serv);
324     info->family = g_strdup(inet_strfamily(sa.ss_family));
325 
326 #ifdef CONFIG_VNC_TLS
327     if (client->tls.session && client->tls.dname) {
328         info->has_x509_dname = true;
329         info->x509_dname = g_strdup(client->tls.dname);
330     }
331 #endif
332 #ifdef CONFIG_VNC_SASL
333     if (client->sasl.conn && client->sasl.username) {
334         info->has_sasl_username = true;
335         info->sasl_username = g_strdup(client->sasl.username);
336     }
337 #endif
338 
339     return info;
340 }
341 
342 VncInfo *qmp_query_vnc(Error **errp)
343 {
344     VncInfo *info = g_malloc0(sizeof(*info));
345 
346     if (vnc_display == NULL || vnc_display->display == NULL) {
347         info->enabled = false;
348     } else {
349         VncClientInfoList *cur_item = NULL;
350         struct sockaddr_storage sa;
351         socklen_t salen = sizeof(sa);
352         char host[NI_MAXHOST];
353         char serv[NI_MAXSERV];
354         VncState *client;
355 
356         info->enabled = true;
357 
358         /* for compatibility with the original command */
359         info->has_clients = true;
360 
361         QTAILQ_FOREACH(client, &vnc_display->clients, next) {
362             VncClientInfoList *cinfo = g_malloc0(sizeof(*info));
363             cinfo->value = qmp_query_vnc_client(client);
364 
365             /* XXX: waiting for the qapi to support GSList */
366             if (!cur_item) {
367                 info->clients = cur_item = cinfo;
368             } else {
369                 cur_item->next = cinfo;
370                 cur_item = cinfo;
371             }
372         }
373 
374         if (getsockname(vnc_display->lsock, (struct sockaddr *)&sa,
375                         &salen) == -1) {
376             error_set(errp, QERR_UNDEFINED_ERROR);
377             goto out_error;
378         }
379 
380         if (getnameinfo((struct sockaddr *)&sa, salen,
381                         host, sizeof(host),
382                         serv, sizeof(serv),
383                         NI_NUMERICHOST | NI_NUMERICSERV) < 0) {
384             error_set(errp, QERR_UNDEFINED_ERROR);
385             goto out_error;
386         }
387 
388         info->has_host = true;
389         info->host = g_strdup(host);
390 
391         info->has_service = true;
392         info->service = g_strdup(serv);
393 
394         info->has_family = true;
395         info->family = g_strdup(inet_strfamily(sa.ss_family));
396 
397         info->has_auth = true;
398         info->auth = g_strdup(vnc_auth_name(vnc_display));
399     }
400 
401     return info;
402 
403 out_error:
404     qapi_free_VncInfo(info);
405     return NULL;
406 }
407 
408 /* TODO
409    1) Get the queue working for IO.
410    2) there is some weirdness when using the -S option (the screen is grey
411       and not totally invalidated
412    3) resolutions > 1024
413 */
414 
415 static int vnc_update_client(VncState *vs, int has_dirty);
416 static int vnc_update_client_sync(VncState *vs, int has_dirty);
417 static void vnc_disconnect_start(VncState *vs);
418 static void vnc_disconnect_finish(VncState *vs);
419 static void vnc_init_timer(VncDisplay *vd);
420 static void vnc_remove_timer(VncDisplay *vd);
421 
422 static void vnc_colordepth(VncState *vs);
423 static void framebuffer_update_request(VncState *vs, int incremental,
424                                        int x_position, int y_position,
425                                        int w, int h);
426 static void vnc_refresh(void *opaque);
427 static int vnc_refresh_server_surface(VncDisplay *vd);
428 
429 static void vnc_dpy_update(DisplayState *ds, int x, int y, int w, int h)
430 {
431     int i;
432     VncDisplay *vd = ds->opaque;
433     struct VncSurface *s = &vd->guest;
434 
435     h += y;
436 
437     /* round x down to ensure the loop only spans one 16-pixel block per,
438        iteration.  otherwise, if (x % 16) != 0, the last iteration may span
439        two 16-pixel blocks but we only mark the first as dirty
440     */
441     w += (x % 16);
442     x -= (x % 16);
443 
444     x = MIN(x, s->ds->width);
445     y = MIN(y, s->ds->height);
446     w = MIN(x + w, s->ds->width) - x;
447     h = MIN(h, s->ds->height);
448 
449     for (; y < h; y++)
450         for (i = 0; i < w; i += 16)
451             set_bit((x + i) / 16, s->dirty[y]);
452 }
453 
454 void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
455                             int32_t encoding)
456 {
457     vnc_write_u16(vs, x);
458     vnc_write_u16(vs, y);
459     vnc_write_u16(vs, w);
460     vnc_write_u16(vs, h);
461 
462     vnc_write_s32(vs, encoding);
463 }
464 
465 void buffer_reserve(Buffer *buffer, size_t len)
466 {
467     if ((buffer->capacity - buffer->offset) < len) {
468         buffer->capacity += (len + 1024);
469         buffer->buffer = g_realloc(buffer->buffer, buffer->capacity);
470         if (buffer->buffer == NULL) {
471             fprintf(stderr, "vnc: out of memory\n");
472             exit(1);
473         }
474     }
475 }
476 
477 int buffer_empty(Buffer *buffer)
478 {
479     return buffer->offset == 0;
480 }
481 
482 uint8_t *buffer_end(Buffer *buffer)
483 {
484     return buffer->buffer + buffer->offset;
485 }
486 
487 void buffer_reset(Buffer *buffer)
488 {
489         buffer->offset = 0;
490 }
491 
492 void buffer_free(Buffer *buffer)
493 {
494     g_free(buffer->buffer);
495     buffer->offset = 0;
496     buffer->capacity = 0;
497     buffer->buffer = NULL;
498 }
499 
500 void buffer_append(Buffer *buffer, const void *data, size_t len)
501 {
502     memcpy(buffer->buffer + buffer->offset, data, len);
503     buffer->offset += len;
504 }
505 
506 static void vnc_desktop_resize(VncState *vs)
507 {
508     DisplayState *ds = vs->ds;
509 
510     if (vs->csock == -1 || !vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
511         return;
512     }
513     if (vs->client_width == ds_get_width(ds) &&
514         vs->client_height == ds_get_height(ds)) {
515         return;
516     }
517     vs->client_width = ds_get_width(ds);
518     vs->client_height = ds_get_height(ds);
519     vnc_lock_output(vs);
520     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
521     vnc_write_u8(vs, 0);
522     vnc_write_u16(vs, 1); /* number of rects */
523     vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
524                            VNC_ENCODING_DESKTOPRESIZE);
525     vnc_unlock_output(vs);
526     vnc_flush(vs);
527 }
528 
529 static void vnc_abort_display_jobs(VncDisplay *vd)
530 {
531     VncState *vs;
532 
533     QTAILQ_FOREACH(vs, &vd->clients, next) {
534         vnc_lock_output(vs);
535         vs->abort = true;
536         vnc_unlock_output(vs);
537     }
538     QTAILQ_FOREACH(vs, &vd->clients, next) {
539         vnc_jobs_join(vs);
540     }
541     QTAILQ_FOREACH(vs, &vd->clients, next) {
542         vnc_lock_output(vs);
543         vs->abort = false;
544         vnc_unlock_output(vs);
545     }
546 }
547 
548 static void vnc_dpy_resize(DisplayState *ds)
549 {
550     VncDisplay *vd = ds->opaque;
551     VncState *vs;
552 
553     vnc_abort_display_jobs(vd);
554 
555     /* server surface */
556     if (!vd->server)
557         vd->server = g_malloc0(sizeof(*vd->server));
558     if (vd->server->data)
559         g_free(vd->server->data);
560     *(vd->server) = *(ds->surface);
561     vd->server->data = g_malloc0(vd->server->linesize *
562                                     vd->server->height);
563 
564     /* guest surface */
565     if (!vd->guest.ds)
566         vd->guest.ds = g_malloc0(sizeof(*vd->guest.ds));
567     if (ds_get_bytes_per_pixel(ds) != vd->guest.ds->pf.bytes_per_pixel)
568         console_color_init(ds);
569     *(vd->guest.ds) = *(ds->surface);
570     memset(vd->guest.dirty, 0xFF, sizeof(vd->guest.dirty));
571 
572     QTAILQ_FOREACH(vs, &vd->clients, next) {
573         vnc_colordepth(vs);
574         vnc_desktop_resize(vs);
575         if (vs->vd->cursor) {
576             vnc_cursor_define(vs);
577         }
578         memset(vs->dirty, 0xFF, sizeof(vs->dirty));
579     }
580 }
581 
582 /* fastest code */
583 static void vnc_write_pixels_copy(VncState *vs, struct PixelFormat *pf,
584                                   void *pixels, int size)
585 {
586     vnc_write(vs, pixels, size);
587 }
588 
589 /* slowest but generic code. */
590 void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
591 {
592     uint8_t r, g, b;
593     VncDisplay *vd = vs->vd;
594 
595     r = ((((v & vd->server->pf.rmask) >> vd->server->pf.rshift) << vs->clientds.pf.rbits) >>
596         vd->server->pf.rbits);
597     g = ((((v & vd->server->pf.gmask) >> vd->server->pf.gshift) << vs->clientds.pf.gbits) >>
598         vd->server->pf.gbits);
599     b = ((((v & vd->server->pf.bmask) >> vd->server->pf.bshift) << vs->clientds.pf.bbits) >>
600         vd->server->pf.bbits);
601     v = (r << vs->clientds.pf.rshift) |
602         (g << vs->clientds.pf.gshift) |
603         (b << vs->clientds.pf.bshift);
604     switch(vs->clientds.pf.bytes_per_pixel) {
605     case 1:
606         buf[0] = v;
607         break;
608     case 2:
609         if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) {
610             buf[0] = v >> 8;
611             buf[1] = v;
612         } else {
613             buf[1] = v >> 8;
614             buf[0] = v;
615         }
616         break;
617     default:
618     case 4:
619         if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) {
620             buf[0] = v >> 24;
621             buf[1] = v >> 16;
622             buf[2] = v >> 8;
623             buf[3] = v;
624         } else {
625             buf[3] = v >> 24;
626             buf[2] = v >> 16;
627             buf[1] = v >> 8;
628             buf[0] = v;
629         }
630         break;
631     }
632 }
633 
634 static void vnc_write_pixels_generic(VncState *vs, struct PixelFormat *pf,
635                                      void *pixels1, int size)
636 {
637     uint8_t buf[4];
638 
639     if (pf->bytes_per_pixel == 4) {
640         uint32_t *pixels = pixels1;
641         int n, i;
642         n = size >> 2;
643         for(i = 0; i < n; i++) {
644             vnc_convert_pixel(vs, buf, pixels[i]);
645             vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
646         }
647     } else if (pf->bytes_per_pixel == 2) {
648         uint16_t *pixels = pixels1;
649         int n, i;
650         n = size >> 1;
651         for(i = 0; i < n; i++) {
652             vnc_convert_pixel(vs, buf, pixels[i]);
653             vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
654         }
655     } else if (pf->bytes_per_pixel == 1) {
656         uint8_t *pixels = pixels1;
657         int n, i;
658         n = size;
659         for(i = 0; i < n; i++) {
660             vnc_convert_pixel(vs, buf, pixels[i]);
661             vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
662         }
663     } else {
664         fprintf(stderr, "vnc_write_pixels_generic: VncState color depth not supported\n");
665     }
666 }
667 
668 int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
669 {
670     int i;
671     uint8_t *row;
672     VncDisplay *vd = vs->vd;
673 
674     row = vd->server->data + y * ds_get_linesize(vs->ds) + x * ds_get_bytes_per_pixel(vs->ds);
675     for (i = 0; i < h; i++) {
676         vs->write_pixels(vs, &vd->server->pf, row, w * ds_get_bytes_per_pixel(vs->ds));
677         row += ds_get_linesize(vs->ds);
678     }
679     return 1;
680 }
681 
682 int vnc_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
683 {
684     int n = 0;
685 
686     switch(vs->vnc_encoding) {
687         case VNC_ENCODING_ZLIB:
688             n = vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
689             break;
690         case VNC_ENCODING_HEXTILE:
691             vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
692             n = vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
693             break;
694         case VNC_ENCODING_TIGHT:
695             n = vnc_tight_send_framebuffer_update(vs, x, y, w, h);
696             break;
697         case VNC_ENCODING_TIGHT_PNG:
698             n = vnc_tight_png_send_framebuffer_update(vs, x, y, w, h);
699             break;
700         case VNC_ENCODING_ZRLE:
701             n = vnc_zrle_send_framebuffer_update(vs, x, y, w, h);
702             break;
703         case VNC_ENCODING_ZYWRLE:
704             n = vnc_zywrle_send_framebuffer_update(vs, x, y, w, h);
705             break;
706         default:
707             vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
708             n = vnc_raw_send_framebuffer_update(vs, x, y, w, h);
709             break;
710     }
711     return n;
712 }
713 
714 static void vnc_copy(VncState *vs, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
715 {
716     /* send bitblit op to the vnc client */
717     vnc_lock_output(vs);
718     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
719     vnc_write_u8(vs, 0);
720     vnc_write_u16(vs, 1); /* number of rects */
721     vnc_framebuffer_update(vs, dst_x, dst_y, w, h, VNC_ENCODING_COPYRECT);
722     vnc_write_u16(vs, src_x);
723     vnc_write_u16(vs, src_y);
724     vnc_unlock_output(vs);
725     vnc_flush(vs);
726 }
727 
728 static void vnc_dpy_copy(DisplayState *ds, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
729 {
730     VncDisplay *vd = ds->opaque;
731     VncState *vs, *vn;
732     uint8_t *src_row;
733     uint8_t *dst_row;
734     int i,x,y,pitch,depth,inc,w_lim,s;
735     int cmp_bytes;
736 
737     vnc_refresh_server_surface(vd);
738     QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
739         if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
740             vs->force_update = 1;
741             vnc_update_client_sync(vs, 1);
742             /* vs might be free()ed here */
743         }
744     }
745 
746     /* do bitblit op on the local surface too */
747     pitch = ds_get_linesize(vd->ds);
748     depth = ds_get_bytes_per_pixel(vd->ds);
749     src_row = vd->server->data + pitch * src_y + depth * src_x;
750     dst_row = vd->server->data + pitch * dst_y + depth * dst_x;
751     y = dst_y;
752     inc = 1;
753     if (dst_y > src_y) {
754         /* copy backwards */
755         src_row += pitch * (h-1);
756         dst_row += pitch * (h-1);
757         pitch = -pitch;
758         y = dst_y + h - 1;
759         inc = -1;
760     }
761     w_lim = w - (16 - (dst_x % 16));
762     if (w_lim < 0)
763         w_lim = w;
764     else
765         w_lim = w - (w_lim % 16);
766     for (i = 0; i < h; i++) {
767         for (x = 0; x <= w_lim;
768                 x += s, src_row += cmp_bytes, dst_row += cmp_bytes) {
769             if (x == w_lim) {
770                 if ((s = w - w_lim) == 0)
771                     break;
772             } else if (!x) {
773                 s = (16 - (dst_x % 16));
774                 s = MIN(s, w_lim);
775             } else {
776                 s = 16;
777             }
778             cmp_bytes = s * depth;
779             if (memcmp(src_row, dst_row, cmp_bytes) == 0)
780                 continue;
781             memmove(dst_row, src_row, cmp_bytes);
782             QTAILQ_FOREACH(vs, &vd->clients, next) {
783                 if (!vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
784                     set_bit(((x + dst_x) / 16), vs->dirty[y]);
785                 }
786             }
787         }
788         src_row += pitch - w * depth;
789         dst_row += pitch - w * depth;
790         y += inc;
791     }
792 
793     QTAILQ_FOREACH(vs, &vd->clients, next) {
794         if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
795             vnc_copy(vs, src_x, src_y, dst_x, dst_y, w, h);
796         }
797     }
798 }
799 
800 static void vnc_mouse_set(int x, int y, int visible)
801 {
802     /* can we ask the client(s) to move the pointer ??? */
803 }
804 
805 static int vnc_cursor_define(VncState *vs)
806 {
807     QEMUCursor *c = vs->vd->cursor;
808     PixelFormat pf = qemu_default_pixelformat(32);
809     int isize;
810 
811     if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
812         vnc_lock_output(vs);
813         vnc_write_u8(vs,  VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
814         vnc_write_u8(vs,  0);  /*  padding     */
815         vnc_write_u16(vs, 1);  /*  # of rects  */
816         vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
817                                VNC_ENCODING_RICH_CURSOR);
818         isize = c->width * c->height * vs->clientds.pf.bytes_per_pixel;
819         vnc_write_pixels_generic(vs, &pf, c->data, isize);
820         vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
821         vnc_unlock_output(vs);
822         return 0;
823     }
824     return -1;
825 }
826 
827 static void vnc_dpy_cursor_define(QEMUCursor *c)
828 {
829     VncDisplay *vd = vnc_display;
830     VncState *vs;
831 
832     cursor_put(vd->cursor);
833     g_free(vd->cursor_mask);
834 
835     vd->cursor = c;
836     cursor_get(vd->cursor);
837     vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
838     vd->cursor_mask = g_malloc0(vd->cursor_msize);
839     cursor_get_mono_mask(c, 0, vd->cursor_mask);
840 
841     QTAILQ_FOREACH(vs, &vd->clients, next) {
842         vnc_cursor_define(vs);
843     }
844 }
845 
846 static int find_and_clear_dirty_height(struct VncState *vs,
847                                        int y, int last_x, int x, int height)
848 {
849     int h;
850 
851     for (h = 1; h < (height - y); h++) {
852         int tmp_x;
853         if (!test_bit(last_x, vs->dirty[y + h])) {
854             break;
855         }
856         for (tmp_x = last_x; tmp_x < x; tmp_x++) {
857             clear_bit(tmp_x, vs->dirty[y + h]);
858         }
859     }
860 
861     return h;
862 }
863 
864 static int vnc_update_client_sync(VncState *vs, int has_dirty)
865 {
866     int ret = vnc_update_client(vs, has_dirty);
867     vnc_jobs_join(vs);
868     return ret;
869 }
870 
871 static int vnc_update_client(VncState *vs, int has_dirty)
872 {
873     if (vs->need_update && vs->csock != -1) {
874         VncDisplay *vd = vs->vd;
875         VncJob *job;
876         int y;
877         int width, height;
878         int n = 0;
879 
880 
881         if (vs->output.offset && !vs->audio_cap && !vs->force_update)
882             /* kernel send buffers are full -> drop frames to throttle */
883             return 0;
884 
885         if (!has_dirty && !vs->audio_cap && !vs->force_update)
886             return 0;
887 
888         /*
889          * Send screen updates to the vnc client using the server
890          * surface and server dirty map.  guest surface updates
891          * happening in parallel don't disturb us, the next pass will
892          * send them to the client.
893          */
894         job = vnc_job_new(vs);
895 
896         width = MIN(vd->server->width, vs->client_width);
897         height = MIN(vd->server->height, vs->client_height);
898 
899         for (y = 0; y < height; y++) {
900             int x;
901             int last_x = -1;
902             for (x = 0; x < width / 16; x++) {
903                 if (test_and_clear_bit(x, vs->dirty[y])) {
904                     if (last_x == -1) {
905                         last_x = x;
906                     }
907                 } else {
908                     if (last_x != -1) {
909                         int h = find_and_clear_dirty_height(vs, y, last_x, x,
910                                                             height);
911 
912                         n += vnc_job_add_rect(job, last_x * 16, y,
913                                               (x - last_x) * 16, h);
914                     }
915                     last_x = -1;
916                 }
917             }
918             if (last_x != -1) {
919                 int h = find_and_clear_dirty_height(vs, y, last_x, x, height);
920                 n += vnc_job_add_rect(job, last_x * 16, y,
921                                       (x - last_x) * 16, h);
922             }
923         }
924 
925         vnc_job_push(job);
926         vs->force_update = 0;
927         return n;
928     }
929 
930     if (vs->csock == -1)
931         vnc_disconnect_finish(vs);
932 
933     return 0;
934 }
935 
936 /* audio */
937 static void audio_capture_notify(void *opaque, audcnotification_e cmd)
938 {
939     VncState *vs = opaque;
940 
941     switch (cmd) {
942     case AUD_CNOTIFY_DISABLE:
943         vnc_lock_output(vs);
944         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
945         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
946         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
947         vnc_unlock_output(vs);
948         vnc_flush(vs);
949         break;
950 
951     case AUD_CNOTIFY_ENABLE:
952         vnc_lock_output(vs);
953         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
954         vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
955         vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
956         vnc_unlock_output(vs);
957         vnc_flush(vs);
958         break;
959     }
960 }
961 
962 static void audio_capture_destroy(void *opaque)
963 {
964 }
965 
966 static void audio_capture(void *opaque, void *buf, int size)
967 {
968     VncState *vs = opaque;
969 
970     vnc_lock_output(vs);
971     vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
972     vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
973     vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
974     vnc_write_u32(vs, size);
975     vnc_write(vs, buf, size);
976     vnc_unlock_output(vs);
977     vnc_flush(vs);
978 }
979 
980 static void audio_add(VncState *vs)
981 {
982     struct audio_capture_ops ops;
983 
984     if (vs->audio_cap) {
985         monitor_printf(default_mon, "audio already running\n");
986         return;
987     }
988 
989     ops.notify = audio_capture_notify;
990     ops.destroy = audio_capture_destroy;
991     ops.capture = audio_capture;
992 
993     vs->audio_cap = AUD_add_capture(&vs->as, &ops, vs);
994     if (!vs->audio_cap) {
995         monitor_printf(default_mon, "Failed to add audio capture\n");
996     }
997 }
998 
999 static void audio_del(VncState *vs)
1000 {
1001     if (vs->audio_cap) {
1002         AUD_del_capture(vs->audio_cap, vs);
1003         vs->audio_cap = NULL;
1004     }
1005 }
1006 
1007 static void vnc_disconnect_start(VncState *vs)
1008 {
1009     if (vs->csock == -1)
1010         return;
1011     vnc_set_share_mode(vs, VNC_SHARE_MODE_DISCONNECTED);
1012     qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
1013     closesocket(vs->csock);
1014     vs->csock = -1;
1015 }
1016 
1017 static void vnc_disconnect_finish(VncState *vs)
1018 {
1019     int i;
1020 
1021     vnc_jobs_join(vs); /* Wait encoding jobs */
1022 
1023     vnc_lock_output(vs);
1024     vnc_qmp_event(vs, QEVENT_VNC_DISCONNECTED);
1025 
1026     buffer_free(&vs->input);
1027     buffer_free(&vs->output);
1028 
1029     qobject_decref(vs->info);
1030 
1031     vnc_zlib_clear(vs);
1032     vnc_tight_clear(vs);
1033     vnc_zrle_clear(vs);
1034 
1035 #ifdef CONFIG_VNC_TLS
1036     vnc_tls_client_cleanup(vs);
1037 #endif /* CONFIG_VNC_TLS */
1038 #ifdef CONFIG_VNC_SASL
1039     vnc_sasl_client_cleanup(vs);
1040 #endif /* CONFIG_VNC_SASL */
1041     audio_del(vs);
1042     vnc_release_modifiers(vs);
1043 
1044     QTAILQ_REMOVE(&vs->vd->clients, vs, next);
1045 
1046     if (QTAILQ_EMPTY(&vs->vd->clients)) {
1047         dcl->idle = 1;
1048     }
1049 
1050     qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
1051     vnc_remove_timer(vs->vd);
1052     if (vs->vd->lock_key_sync)
1053         qemu_remove_led_event_handler(vs->led);
1054     vnc_unlock_output(vs);
1055 
1056     qemu_mutex_destroy(&vs->output_mutex);
1057     qemu_bh_delete(vs->bh);
1058     buffer_free(&vs->jobs_buffer);
1059 
1060     for (i = 0; i < VNC_STAT_ROWS; ++i) {
1061         g_free(vs->lossy_rect[i]);
1062     }
1063     g_free(vs->lossy_rect);
1064     g_free(vs);
1065 }
1066 
1067 int vnc_client_io_error(VncState *vs, int ret, int last_errno)
1068 {
1069     if (ret == 0 || ret == -1) {
1070         if (ret == -1) {
1071             switch (last_errno) {
1072                 case EINTR:
1073                 case EAGAIN:
1074 #ifdef _WIN32
1075                 case WSAEWOULDBLOCK:
1076 #endif
1077                     return 0;
1078                 default:
1079                     break;
1080             }
1081         }
1082 
1083         VNC_DEBUG("Closing down client sock: ret %d, errno %d\n",
1084                   ret, ret < 0 ? last_errno : 0);
1085         vnc_disconnect_start(vs);
1086 
1087         return 0;
1088     }
1089     return ret;
1090 }
1091 
1092 
1093 void vnc_client_error(VncState *vs)
1094 {
1095     VNC_DEBUG("Closing down client sock: protocol error\n");
1096     vnc_disconnect_start(vs);
1097 }
1098 
1099 
1100 /*
1101  * Called to write a chunk of data to the client socket. The data may
1102  * be the raw data, or may have already been encoded by SASL.
1103  * The data will be written either straight onto the socket, or
1104  * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1105  *
1106  * NB, it is theoretically possible to have 2 layers of encryption,
1107  * both SASL, and this TLS layer. It is highly unlikely in practice
1108  * though, since SASL encryption will typically be a no-op if TLS
1109  * is active
1110  *
1111  * Returns the number of bytes written, which may be less than
1112  * the requested 'datalen' if the socket would block. Returns
1113  * -1 on error, and disconnects the client socket.
1114  */
1115 long vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
1116 {
1117     long ret;
1118 #ifdef CONFIG_VNC_TLS
1119     if (vs->tls.session) {
1120         ret = gnutls_write(vs->tls.session, data, datalen);
1121         if (ret < 0) {
1122             if (ret == GNUTLS_E_AGAIN)
1123                 errno = EAGAIN;
1124             else
1125                 errno = EIO;
1126             ret = -1;
1127         }
1128     } else
1129 #endif /* CONFIG_VNC_TLS */
1130         ret = send(vs->csock, (const void *)data, datalen, 0);
1131     VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
1132     return vnc_client_io_error(vs, ret, socket_error());
1133 }
1134 
1135 
1136 /*
1137  * Called to write buffered data to the client socket, when not
1138  * using any SASL SSF encryption layers. Will write as much data
1139  * as possible without blocking. If all buffered data is written,
1140  * will switch the FD poll() handler back to read monitoring.
1141  *
1142  * Returns the number of bytes written, which may be less than
1143  * the buffered output data if the socket would block. Returns
1144  * -1 on error, and disconnects the client socket.
1145  */
1146 static long vnc_client_write_plain(VncState *vs)
1147 {
1148     long ret;
1149 
1150 #ifdef CONFIG_VNC_SASL
1151     VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
1152               vs->output.buffer, vs->output.capacity, vs->output.offset,
1153               vs->sasl.waitWriteSSF);
1154 
1155     if (vs->sasl.conn &&
1156         vs->sasl.runSSF &&
1157         vs->sasl.waitWriteSSF) {
1158         ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
1159         if (ret)
1160             vs->sasl.waitWriteSSF -= ret;
1161     } else
1162 #endif /* CONFIG_VNC_SASL */
1163         ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
1164     if (!ret)
1165         return 0;
1166 
1167     memmove(vs->output.buffer, vs->output.buffer + ret, (vs->output.offset - ret));
1168     vs->output.offset -= ret;
1169 
1170     if (vs->output.offset == 0) {
1171         qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
1172     }
1173 
1174     return ret;
1175 }
1176 
1177 
1178 /*
1179  * First function called whenever there is data to be written to
1180  * the client socket. Will delegate actual work according to whether
1181  * SASL SSF layers are enabled (thus requiring encryption calls)
1182  */
1183 static void vnc_client_write_locked(void *opaque)
1184 {
1185     VncState *vs = opaque;
1186 
1187 #ifdef CONFIG_VNC_SASL
1188     if (vs->sasl.conn &&
1189         vs->sasl.runSSF &&
1190         !vs->sasl.waitWriteSSF) {
1191         vnc_client_write_sasl(vs);
1192     } else
1193 #endif /* CONFIG_VNC_SASL */
1194         vnc_client_write_plain(vs);
1195 }
1196 
1197 void vnc_client_write(void *opaque)
1198 {
1199     VncState *vs = opaque;
1200 
1201     vnc_lock_output(vs);
1202     if (vs->output.offset) {
1203         vnc_client_write_locked(opaque);
1204     } else if (vs->csock != -1) {
1205         qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
1206     }
1207     vnc_unlock_output(vs);
1208 }
1209 
1210 void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
1211 {
1212     vs->read_handler = func;
1213     vs->read_handler_expect = expecting;
1214 }
1215 
1216 
1217 /*
1218  * Called to read a chunk of data from the client socket. The data may
1219  * be the raw data, or may need to be further decoded by SASL.
1220  * The data will be read either straight from to the socket, or
1221  * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1222  *
1223  * NB, it is theoretically possible to have 2 layers of encryption,
1224  * both SASL, and this TLS layer. It is highly unlikely in practice
1225  * though, since SASL encryption will typically be a no-op if TLS
1226  * is active
1227  *
1228  * Returns the number of bytes read, which may be less than
1229  * the requested 'datalen' if the socket would block. Returns
1230  * -1 on error, and disconnects the client socket.
1231  */
1232 long vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
1233 {
1234     long ret;
1235 #ifdef CONFIG_VNC_TLS
1236     if (vs->tls.session) {
1237         ret = gnutls_read(vs->tls.session, data, datalen);
1238         if (ret < 0) {
1239             if (ret == GNUTLS_E_AGAIN)
1240                 errno = EAGAIN;
1241             else
1242                 errno = EIO;
1243             ret = -1;
1244         }
1245     } else
1246 #endif /* CONFIG_VNC_TLS */
1247         ret = qemu_recv(vs->csock, data, datalen, 0);
1248     VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
1249     return vnc_client_io_error(vs, ret, socket_error());
1250 }
1251 
1252 
1253 /*
1254  * Called to read data from the client socket to the input buffer,
1255  * when not using any SASL SSF encryption layers. Will read as much
1256  * data as possible without blocking.
1257  *
1258  * Returns the number of bytes read. Returns -1 on error, and
1259  * disconnects the client socket.
1260  */
1261 static long vnc_client_read_plain(VncState *vs)
1262 {
1263     int ret;
1264     VNC_DEBUG("Read plain %p size %zd offset %zd\n",
1265               vs->input.buffer, vs->input.capacity, vs->input.offset);
1266     buffer_reserve(&vs->input, 4096);
1267     ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
1268     if (!ret)
1269         return 0;
1270     vs->input.offset += ret;
1271     return ret;
1272 }
1273 
1274 static void vnc_jobs_bh(void *opaque)
1275 {
1276     VncState *vs = opaque;
1277 
1278     vnc_jobs_consume_buffer(vs);
1279 }
1280 
1281 /*
1282  * First function called whenever there is more data to be read from
1283  * the client socket. Will delegate actual work according to whether
1284  * SASL SSF layers are enabled (thus requiring decryption calls)
1285  */
1286 void vnc_client_read(void *opaque)
1287 {
1288     VncState *vs = opaque;
1289     long ret;
1290 
1291 #ifdef CONFIG_VNC_SASL
1292     if (vs->sasl.conn && vs->sasl.runSSF)
1293         ret = vnc_client_read_sasl(vs);
1294     else
1295 #endif /* CONFIG_VNC_SASL */
1296         ret = vnc_client_read_plain(vs);
1297     if (!ret) {
1298         if (vs->csock == -1)
1299             vnc_disconnect_finish(vs);
1300         return;
1301     }
1302 
1303     while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
1304         size_t len = vs->read_handler_expect;
1305         int ret;
1306 
1307         ret = vs->read_handler(vs, vs->input.buffer, len);
1308         if (vs->csock == -1) {
1309             vnc_disconnect_finish(vs);
1310             return;
1311         }
1312 
1313         if (!ret) {
1314             memmove(vs->input.buffer, vs->input.buffer + len, (vs->input.offset - len));
1315             vs->input.offset -= len;
1316         } else {
1317             vs->read_handler_expect = ret;
1318         }
1319     }
1320 }
1321 
1322 void vnc_write(VncState *vs, const void *data, size_t len)
1323 {
1324     buffer_reserve(&vs->output, len);
1325 
1326     if (vs->csock != -1 && buffer_empty(&vs->output)) {
1327         qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
1328     }
1329 
1330     buffer_append(&vs->output, data, len);
1331 }
1332 
1333 void vnc_write_s32(VncState *vs, int32_t value)
1334 {
1335     vnc_write_u32(vs, *(uint32_t *)&value);
1336 }
1337 
1338 void vnc_write_u32(VncState *vs, uint32_t value)
1339 {
1340     uint8_t buf[4];
1341 
1342     buf[0] = (value >> 24) & 0xFF;
1343     buf[1] = (value >> 16) & 0xFF;
1344     buf[2] = (value >>  8) & 0xFF;
1345     buf[3] = value & 0xFF;
1346 
1347     vnc_write(vs, buf, 4);
1348 }
1349 
1350 void vnc_write_u16(VncState *vs, uint16_t value)
1351 {
1352     uint8_t buf[2];
1353 
1354     buf[0] = (value >> 8) & 0xFF;
1355     buf[1] = value & 0xFF;
1356 
1357     vnc_write(vs, buf, 2);
1358 }
1359 
1360 void vnc_write_u8(VncState *vs, uint8_t value)
1361 {
1362     vnc_write(vs, (char *)&value, 1);
1363 }
1364 
1365 void vnc_flush(VncState *vs)
1366 {
1367     vnc_lock_output(vs);
1368     if (vs->csock != -1 && vs->output.offset) {
1369         vnc_client_write_locked(vs);
1370     }
1371     vnc_unlock_output(vs);
1372 }
1373 
1374 uint8_t read_u8(uint8_t *data, size_t offset)
1375 {
1376     return data[offset];
1377 }
1378 
1379 uint16_t read_u16(uint8_t *data, size_t offset)
1380 {
1381     return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1382 }
1383 
1384 int32_t read_s32(uint8_t *data, size_t offset)
1385 {
1386     return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
1387                      (data[offset + 2] << 8) | data[offset + 3]);
1388 }
1389 
1390 uint32_t read_u32(uint8_t *data, size_t offset)
1391 {
1392     return ((data[offset] << 24) | (data[offset + 1] << 16) |
1393             (data[offset + 2] << 8) | data[offset + 3]);
1394 }
1395 
1396 static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
1397 {
1398 }
1399 
1400 static void check_pointer_type_change(Notifier *notifier, void *data)
1401 {
1402     VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
1403     int absolute = kbd_mouse_is_absolute();
1404 
1405     if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1406         vnc_lock_output(vs);
1407         vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1408         vnc_write_u8(vs, 0);
1409         vnc_write_u16(vs, 1);
1410         vnc_framebuffer_update(vs, absolute, 0,
1411                                ds_get_width(vs->ds), ds_get_height(vs->ds),
1412                                VNC_ENCODING_POINTER_TYPE_CHANGE);
1413         vnc_unlock_output(vs);
1414         vnc_flush(vs);
1415     }
1416     vs->absolute = absolute;
1417 }
1418 
1419 static void pointer_event(VncState *vs, int button_mask, int x, int y)
1420 {
1421     int buttons = 0;
1422     int dz = 0;
1423 
1424     if (button_mask & 0x01)
1425         buttons |= MOUSE_EVENT_LBUTTON;
1426     if (button_mask & 0x02)
1427         buttons |= MOUSE_EVENT_MBUTTON;
1428     if (button_mask & 0x04)
1429         buttons |= MOUSE_EVENT_RBUTTON;
1430     if (button_mask & 0x08)
1431         dz = -1;
1432     if (button_mask & 0x10)
1433         dz = 1;
1434 
1435     if (vs->absolute) {
1436         kbd_mouse_event(ds_get_width(vs->ds) > 1 ?
1437                           x * 0x7FFF / (ds_get_width(vs->ds) - 1) : 0x4000,
1438                         ds_get_height(vs->ds) > 1 ?
1439                           y * 0x7FFF / (ds_get_height(vs->ds) - 1) : 0x4000,
1440                         dz, buttons);
1441     } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
1442         x -= 0x7FFF;
1443         y -= 0x7FFF;
1444 
1445         kbd_mouse_event(x, y, dz, buttons);
1446     } else {
1447         if (vs->last_x != -1)
1448             kbd_mouse_event(x - vs->last_x,
1449                             y - vs->last_y,
1450                             dz, buttons);
1451         vs->last_x = x;
1452         vs->last_y = y;
1453     }
1454 }
1455 
1456 static void reset_keys(VncState *vs)
1457 {
1458     int i;
1459     for(i = 0; i < 256; i++) {
1460         if (vs->modifiers_state[i]) {
1461             if (i & SCANCODE_GREY)
1462                 kbd_put_keycode(SCANCODE_EMUL0);
1463             kbd_put_keycode(i | SCANCODE_UP);
1464             vs->modifiers_state[i] = 0;
1465         }
1466     }
1467 }
1468 
1469 static void press_key(VncState *vs, int keysym)
1470 {
1471     int keycode = keysym2scancode(vs->vd->kbd_layout, keysym) & SCANCODE_KEYMASK;
1472     if (keycode & SCANCODE_GREY)
1473         kbd_put_keycode(SCANCODE_EMUL0);
1474     kbd_put_keycode(keycode & SCANCODE_KEYCODEMASK);
1475     if (keycode & SCANCODE_GREY)
1476         kbd_put_keycode(SCANCODE_EMUL0);
1477     kbd_put_keycode(keycode | SCANCODE_UP);
1478 }
1479 
1480 static void kbd_leds(void *opaque, int ledstate)
1481 {
1482     VncState *vs = opaque;
1483     int caps, num;
1484 
1485     caps = ledstate & QEMU_CAPS_LOCK_LED ? 1 : 0;
1486     num  = ledstate & QEMU_NUM_LOCK_LED  ? 1 : 0;
1487 
1488     if (vs->modifiers_state[0x3a] != caps) {
1489         vs->modifiers_state[0x3a] = caps;
1490     }
1491     if (vs->modifiers_state[0x45] != num) {
1492         vs->modifiers_state[0x45] = num;
1493     }
1494 }
1495 
1496 static void do_key_event(VncState *vs, int down, int keycode, int sym)
1497 {
1498     /* QEMU console switch */
1499     switch(keycode) {
1500     case 0x2a:                          /* Left Shift */
1501     case 0x36:                          /* Right Shift */
1502     case 0x1d:                          /* Left CTRL */
1503     case 0x9d:                          /* Right CTRL */
1504     case 0x38:                          /* Left ALT */
1505     case 0xb8:                          /* Right ALT */
1506         if (down)
1507             vs->modifiers_state[keycode] = 1;
1508         else
1509             vs->modifiers_state[keycode] = 0;
1510         break;
1511     case 0x02 ... 0x0a: /* '1' to '9' keys */
1512         if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
1513             /* Reset the modifiers sent to the current console */
1514             reset_keys(vs);
1515             console_select(keycode - 0x02);
1516             return;
1517         }
1518         break;
1519     case 0x3a:                        /* CapsLock */
1520     case 0x45:                        /* NumLock */
1521         if (down)
1522             vs->modifiers_state[keycode] ^= 1;
1523         break;
1524     }
1525 
1526     if (down && vs->vd->lock_key_sync &&
1527         keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
1528         /* If the numlock state needs to change then simulate an additional
1529            keypress before sending this one.  This will happen if the user
1530            toggles numlock away from the VNC window.
1531         */
1532         if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1533             if (!vs->modifiers_state[0x45]) {
1534                 vs->modifiers_state[0x45] = 1;
1535                 press_key(vs, 0xff7f);
1536             }
1537         } else {
1538             if (vs->modifiers_state[0x45]) {
1539                 vs->modifiers_state[0x45] = 0;
1540                 press_key(vs, 0xff7f);
1541             }
1542         }
1543     }
1544 
1545     if (down && vs->vd->lock_key_sync &&
1546         ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
1547         /* If the capslock state needs to change then simulate an additional
1548            keypress before sending this one.  This will happen if the user
1549            toggles capslock away from the VNC window.
1550         */
1551         int uppercase = !!(sym >= 'A' && sym <= 'Z');
1552         int shift = !!(vs->modifiers_state[0x2a] | vs->modifiers_state[0x36]);
1553         int capslock = !!(vs->modifiers_state[0x3a]);
1554         if (capslock) {
1555             if (uppercase == shift) {
1556                 vs->modifiers_state[0x3a] = 0;
1557                 press_key(vs, 0xffe5);
1558             }
1559         } else {
1560             if (uppercase != shift) {
1561                 vs->modifiers_state[0x3a] = 1;
1562                 press_key(vs, 0xffe5);
1563             }
1564         }
1565     }
1566 
1567     if (is_graphic_console()) {
1568         if (keycode & SCANCODE_GREY)
1569             kbd_put_keycode(SCANCODE_EMUL0);
1570         if (down)
1571             kbd_put_keycode(keycode & SCANCODE_KEYCODEMASK);
1572         else
1573             kbd_put_keycode(keycode | SCANCODE_UP);
1574     } else {
1575         bool numlock = vs->modifiers_state[0x45];
1576         bool control = (vs->modifiers_state[0x1d] ||
1577                         vs->modifiers_state[0x9d]);
1578         /* QEMU console emulation */
1579         if (down) {
1580             switch (keycode) {
1581             case 0x2a:                          /* Left Shift */
1582             case 0x36:                          /* Right Shift */
1583             case 0x1d:                          /* Left CTRL */
1584             case 0x9d:                          /* Right CTRL */
1585             case 0x38:                          /* Left ALT */
1586             case 0xb8:                          /* Right ALT */
1587                 break;
1588             case 0xc8:
1589                 kbd_put_keysym(QEMU_KEY_UP);
1590                 break;
1591             case 0xd0:
1592                 kbd_put_keysym(QEMU_KEY_DOWN);
1593                 break;
1594             case 0xcb:
1595                 kbd_put_keysym(QEMU_KEY_LEFT);
1596                 break;
1597             case 0xcd:
1598                 kbd_put_keysym(QEMU_KEY_RIGHT);
1599                 break;
1600             case 0xd3:
1601                 kbd_put_keysym(QEMU_KEY_DELETE);
1602                 break;
1603             case 0xc7:
1604                 kbd_put_keysym(QEMU_KEY_HOME);
1605                 break;
1606             case 0xcf:
1607                 kbd_put_keysym(QEMU_KEY_END);
1608                 break;
1609             case 0xc9:
1610                 kbd_put_keysym(QEMU_KEY_PAGEUP);
1611                 break;
1612             case 0xd1:
1613                 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1614                 break;
1615 
1616             case 0x47:
1617                 kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
1618                 break;
1619             case 0x48:
1620                 kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
1621                 break;
1622             case 0x49:
1623                 kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
1624                 break;
1625             case 0x4b:
1626                 kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
1627                 break;
1628             case 0x4c:
1629                 kbd_put_keysym('5');
1630                 break;
1631             case 0x4d:
1632                 kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
1633                 break;
1634             case 0x4f:
1635                 kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
1636                 break;
1637             case 0x50:
1638                 kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
1639                 break;
1640             case 0x51:
1641                 kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
1642                 break;
1643             case 0x52:
1644                 kbd_put_keysym('0');
1645                 break;
1646             case 0x53:
1647                 kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
1648                 break;
1649 
1650             case 0xb5:
1651                 kbd_put_keysym('/');
1652                 break;
1653             case 0x37:
1654                 kbd_put_keysym('*');
1655                 break;
1656             case 0x4a:
1657                 kbd_put_keysym('-');
1658                 break;
1659             case 0x4e:
1660                 kbd_put_keysym('+');
1661                 break;
1662             case 0x9c:
1663                 kbd_put_keysym('\n');
1664                 break;
1665 
1666             default:
1667                 if (control) {
1668                     kbd_put_keysym(sym & 0x1f);
1669                 } else {
1670                     kbd_put_keysym(sym);
1671                 }
1672                 break;
1673             }
1674         }
1675     }
1676 }
1677 
1678 static void vnc_release_modifiers(VncState *vs)
1679 {
1680     static const int keycodes[] = {
1681         /* shift, control, alt keys, both left & right */
1682         0x2a, 0x36, 0x1d, 0x9d, 0x38, 0xb8,
1683     };
1684     int i, keycode;
1685 
1686     if (!is_graphic_console()) {
1687         return;
1688     }
1689     for (i = 0; i < ARRAY_SIZE(keycodes); i++) {
1690         keycode = keycodes[i];
1691         if (!vs->modifiers_state[keycode]) {
1692             continue;
1693         }
1694         if (keycode & SCANCODE_GREY) {
1695             kbd_put_keycode(SCANCODE_EMUL0);
1696         }
1697         kbd_put_keycode(keycode | SCANCODE_UP);
1698     }
1699 }
1700 
1701 static void key_event(VncState *vs, int down, uint32_t sym)
1702 {
1703     int keycode;
1704     int lsym = sym;
1705 
1706     if (lsym >= 'A' && lsym <= 'Z' && is_graphic_console()) {
1707         lsym = lsym - 'A' + 'a';
1708     }
1709 
1710     keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF) & SCANCODE_KEYMASK;
1711     do_key_event(vs, down, keycode, sym);
1712 }
1713 
1714 static void ext_key_event(VncState *vs, int down,
1715                           uint32_t sym, uint16_t keycode)
1716 {
1717     /* if the user specifies a keyboard layout, always use it */
1718     if (keyboard_layout)
1719         key_event(vs, down, sym);
1720     else
1721         do_key_event(vs, down, keycode, sym);
1722 }
1723 
1724 static void framebuffer_update_request(VncState *vs, int incremental,
1725                                        int x_position, int y_position,
1726                                        int w, int h)
1727 {
1728     int i;
1729     const size_t width = ds_get_width(vs->ds) / 16;
1730 
1731     if (y_position > ds_get_height(vs->ds))
1732         y_position = ds_get_height(vs->ds);
1733     if (y_position + h >= ds_get_height(vs->ds))
1734         h = ds_get_height(vs->ds) - y_position;
1735 
1736     vs->need_update = 1;
1737     if (!incremental) {
1738         vs->force_update = 1;
1739         for (i = 0; i < h; i++) {
1740             bitmap_set(vs->dirty[y_position + i], 0, width);
1741             bitmap_clear(vs->dirty[y_position + i], width,
1742                          VNC_DIRTY_BITS - width);
1743         }
1744     }
1745 }
1746 
1747 static void send_ext_key_event_ack(VncState *vs)
1748 {
1749     vnc_lock_output(vs);
1750     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1751     vnc_write_u8(vs, 0);
1752     vnc_write_u16(vs, 1);
1753     vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1754                            VNC_ENCODING_EXT_KEY_EVENT);
1755     vnc_unlock_output(vs);
1756     vnc_flush(vs);
1757 }
1758 
1759 static void send_ext_audio_ack(VncState *vs)
1760 {
1761     vnc_lock_output(vs);
1762     vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1763     vnc_write_u8(vs, 0);
1764     vnc_write_u16(vs, 1);
1765     vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1766                            VNC_ENCODING_AUDIO);
1767     vnc_unlock_output(vs);
1768     vnc_flush(vs);
1769 }
1770 
1771 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
1772 {
1773     int i;
1774     unsigned int enc = 0;
1775 
1776     vs->features = 0;
1777     vs->vnc_encoding = 0;
1778     vs->tight.compression = 9;
1779     vs->tight.quality = -1; /* Lossless by default */
1780     vs->absolute = -1;
1781 
1782     /*
1783      * Start from the end because the encodings are sent in order of preference.
1784      * This way the preferred encoding (first encoding defined in the array)
1785      * will be set at the end of the loop.
1786      */
1787     for (i = n_encodings - 1; i >= 0; i--) {
1788         enc = encodings[i];
1789         switch (enc) {
1790         case VNC_ENCODING_RAW:
1791             vs->vnc_encoding = enc;
1792             break;
1793         case VNC_ENCODING_COPYRECT:
1794             vs->features |= VNC_FEATURE_COPYRECT_MASK;
1795             break;
1796         case VNC_ENCODING_HEXTILE:
1797             vs->features |= VNC_FEATURE_HEXTILE_MASK;
1798             vs->vnc_encoding = enc;
1799             break;
1800         case VNC_ENCODING_TIGHT:
1801             vs->features |= VNC_FEATURE_TIGHT_MASK;
1802             vs->vnc_encoding = enc;
1803             break;
1804         case VNC_ENCODING_TIGHT_PNG:
1805             vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;
1806             vs->vnc_encoding = enc;
1807             break;
1808         case VNC_ENCODING_ZLIB:
1809             vs->features |= VNC_FEATURE_ZLIB_MASK;
1810             vs->vnc_encoding = enc;
1811             break;
1812         case VNC_ENCODING_ZRLE:
1813             vs->features |= VNC_FEATURE_ZRLE_MASK;
1814             vs->vnc_encoding = enc;
1815             break;
1816         case VNC_ENCODING_ZYWRLE:
1817             vs->features |= VNC_FEATURE_ZYWRLE_MASK;
1818             vs->vnc_encoding = enc;
1819             break;
1820         case VNC_ENCODING_DESKTOPRESIZE:
1821             vs->features |= VNC_FEATURE_RESIZE_MASK;
1822             break;
1823         case VNC_ENCODING_POINTER_TYPE_CHANGE:
1824             vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
1825             break;
1826         case VNC_ENCODING_RICH_CURSOR:
1827             vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
1828             break;
1829         case VNC_ENCODING_EXT_KEY_EVENT:
1830             send_ext_key_event_ack(vs);
1831             break;
1832         case VNC_ENCODING_AUDIO:
1833             send_ext_audio_ack(vs);
1834             break;
1835         case VNC_ENCODING_WMVi:
1836             vs->features |= VNC_FEATURE_WMVI_MASK;
1837             break;
1838         case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
1839             vs->tight.compression = (enc & 0x0F);
1840             break;
1841         case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
1842             if (vs->vd->lossy) {
1843                 vs->tight.quality = (enc & 0x0F);
1844             }
1845             break;
1846         default:
1847             VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
1848             break;
1849         }
1850     }
1851     vnc_desktop_resize(vs);
1852     check_pointer_type_change(&vs->mouse_mode_notifier, NULL);
1853 }
1854 
1855 static void set_pixel_conversion(VncState *vs)
1856 {
1857     if ((vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) ==
1858         (vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG) &&
1859         !memcmp(&(vs->clientds.pf), &(vs->ds->surface->pf), sizeof(PixelFormat))) {
1860         vs->write_pixels = vnc_write_pixels_copy;
1861         vnc_hextile_set_pixel_conversion(vs, 0);
1862     } else {
1863         vs->write_pixels = vnc_write_pixels_generic;
1864         vnc_hextile_set_pixel_conversion(vs, 1);
1865     }
1866 }
1867 
1868 static void set_pixel_format(VncState *vs,
1869                              int bits_per_pixel, int depth,
1870                              int big_endian_flag, int true_color_flag,
1871                              int red_max, int green_max, int blue_max,
1872                              int red_shift, int green_shift, int blue_shift)
1873 {
1874     if (!true_color_flag) {
1875         vnc_client_error(vs);
1876         return;
1877     }
1878 
1879     vs->clientds = *(vs->vd->guest.ds);
1880     vs->clientds.pf.rmax = red_max;
1881     vs->clientds.pf.rbits = hweight_long(red_max);
1882     vs->clientds.pf.rshift = red_shift;
1883     vs->clientds.pf.rmask = red_max << red_shift;
1884     vs->clientds.pf.gmax = green_max;
1885     vs->clientds.pf.gbits = hweight_long(green_max);
1886     vs->clientds.pf.gshift = green_shift;
1887     vs->clientds.pf.gmask = green_max << green_shift;
1888     vs->clientds.pf.bmax = blue_max;
1889     vs->clientds.pf.bbits = hweight_long(blue_max);
1890     vs->clientds.pf.bshift = blue_shift;
1891     vs->clientds.pf.bmask = blue_max << blue_shift;
1892     vs->clientds.pf.bits_per_pixel = bits_per_pixel;
1893     vs->clientds.pf.bytes_per_pixel = bits_per_pixel / 8;
1894     vs->clientds.pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
1895     vs->clientds.flags = big_endian_flag ? QEMU_BIG_ENDIAN_FLAG : 0x00;
1896 
1897     set_pixel_conversion(vs);
1898 
1899     vga_hw_invalidate();
1900     vga_hw_update();
1901 }
1902 
1903 static void pixel_format_message (VncState *vs) {
1904     char pad[3] = { 0, 0, 0 };
1905 
1906     vnc_write_u8(vs, vs->ds->surface->pf.bits_per_pixel); /* bits-per-pixel */
1907     vnc_write_u8(vs, vs->ds->surface->pf.depth); /* depth */
1908 
1909 #ifdef HOST_WORDS_BIGENDIAN
1910     vnc_write_u8(vs, 1);             /* big-endian-flag */
1911 #else
1912     vnc_write_u8(vs, 0);             /* big-endian-flag */
1913 #endif
1914     vnc_write_u8(vs, 1);             /* true-color-flag */
1915     vnc_write_u16(vs, vs->ds->surface->pf.rmax);     /* red-max */
1916     vnc_write_u16(vs, vs->ds->surface->pf.gmax);     /* green-max */
1917     vnc_write_u16(vs, vs->ds->surface->pf.bmax);     /* blue-max */
1918     vnc_write_u8(vs, vs->ds->surface->pf.rshift);    /* red-shift */
1919     vnc_write_u8(vs, vs->ds->surface->pf.gshift);    /* green-shift */
1920     vnc_write_u8(vs, vs->ds->surface->pf.bshift);    /* blue-shift */
1921 
1922     vnc_hextile_set_pixel_conversion(vs, 0);
1923 
1924     vs->clientds = *(vs->ds->surface);
1925     vs->clientds.flags &= ~QEMU_ALLOCATED_FLAG;
1926     vs->write_pixels = vnc_write_pixels_copy;
1927 
1928     vnc_write(vs, pad, 3);           /* padding */
1929 }
1930 
1931 static void vnc_dpy_setdata(DisplayState *ds)
1932 {
1933     VncDisplay *vd = ds->opaque;
1934 
1935     *(vd->guest.ds) = *(ds->surface);
1936     vnc_dpy_update(ds, 0, 0, ds_get_width(ds), ds_get_height(ds));
1937 }
1938 
1939 static void vnc_colordepth(VncState *vs)
1940 {
1941     if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
1942         /* Sending a WMVi message to notify the client*/
1943         vnc_lock_output(vs);
1944         vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1945         vnc_write_u8(vs, 0);
1946         vnc_write_u16(vs, 1); /* number of rects */
1947         vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds),
1948                                ds_get_height(vs->ds), VNC_ENCODING_WMVi);
1949         pixel_format_message(vs);
1950         vnc_unlock_output(vs);
1951         vnc_flush(vs);
1952     } else {
1953         set_pixel_conversion(vs);
1954     }
1955 }
1956 
1957 static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
1958 {
1959     int i;
1960     uint16_t limit;
1961     VncDisplay *vd = vs->vd;
1962 
1963     if (data[0] > 3) {
1964         vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
1965         if (!qemu_timer_expired(vd->timer, qemu_get_clock_ms(rt_clock) + vd->timer_interval))
1966             qemu_mod_timer(vd->timer, qemu_get_clock_ms(rt_clock) + vd->timer_interval);
1967     }
1968 
1969     switch (data[0]) {
1970     case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
1971         if (len == 1)
1972             return 20;
1973 
1974         set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
1975                          read_u8(data, 6), read_u8(data, 7),
1976                          read_u16(data, 8), read_u16(data, 10),
1977                          read_u16(data, 12), read_u8(data, 14),
1978                          read_u8(data, 15), read_u8(data, 16));
1979         break;
1980     case VNC_MSG_CLIENT_SET_ENCODINGS:
1981         if (len == 1)
1982             return 4;
1983 
1984         if (len == 4) {
1985             limit = read_u16(data, 2);
1986             if (limit > 0)
1987                 return 4 + (limit * 4);
1988         } else
1989             limit = read_u16(data, 2);
1990 
1991         for (i = 0; i < limit; i++) {
1992             int32_t val = read_s32(data, 4 + (i * 4));
1993             memcpy(data + 4 + (i * 4), &val, sizeof(val));
1994         }
1995 
1996         set_encodings(vs, (int32_t *)(data + 4), limit);
1997         break;
1998     case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
1999         if (len == 1)
2000             return 10;
2001 
2002         framebuffer_update_request(vs,
2003                                    read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
2004                                    read_u16(data, 6), read_u16(data, 8));
2005         break;
2006     case VNC_MSG_CLIENT_KEY_EVENT:
2007         if (len == 1)
2008             return 8;
2009 
2010         key_event(vs, read_u8(data, 1), read_u32(data, 4));
2011         break;
2012     case VNC_MSG_CLIENT_POINTER_EVENT:
2013         if (len == 1)
2014             return 6;
2015 
2016         pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
2017         break;
2018     case VNC_MSG_CLIENT_CUT_TEXT:
2019         if (len == 1)
2020             return 8;
2021 
2022         if (len == 8) {
2023             uint32_t dlen = read_u32(data, 4);
2024             if (dlen > 0)
2025                 return 8 + dlen;
2026         }
2027 
2028         client_cut_text(vs, read_u32(data, 4), data + 8);
2029         break;
2030     case VNC_MSG_CLIENT_QEMU:
2031         if (len == 1)
2032             return 2;
2033 
2034         switch (read_u8(data, 1)) {
2035         case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
2036             if (len == 2)
2037                 return 12;
2038 
2039             ext_key_event(vs, read_u16(data, 2),
2040                           read_u32(data, 4), read_u32(data, 8));
2041             break;
2042         case VNC_MSG_CLIENT_QEMU_AUDIO:
2043             if (len == 2)
2044                 return 4;
2045 
2046             switch (read_u16 (data, 2)) {
2047             case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
2048                 audio_add(vs);
2049                 break;
2050             case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
2051                 audio_del(vs);
2052                 break;
2053             case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
2054                 if (len == 4)
2055                     return 10;
2056                 switch (read_u8(data, 4)) {
2057                 case 0: vs->as.fmt = AUD_FMT_U8; break;
2058                 case 1: vs->as.fmt = AUD_FMT_S8; break;
2059                 case 2: vs->as.fmt = AUD_FMT_U16; break;
2060                 case 3: vs->as.fmt = AUD_FMT_S16; break;
2061                 case 4: vs->as.fmt = AUD_FMT_U32; break;
2062                 case 5: vs->as.fmt = AUD_FMT_S32; break;
2063                 default:
2064                     printf("Invalid audio format %d\n", read_u8(data, 4));
2065                     vnc_client_error(vs);
2066                     break;
2067                 }
2068                 vs->as.nchannels = read_u8(data, 5);
2069                 if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2070                     printf("Invalid audio channel coount %d\n",
2071                            read_u8(data, 5));
2072                     vnc_client_error(vs);
2073                     break;
2074                 }
2075                 vs->as.freq = read_u32(data, 6);
2076                 break;
2077             default:
2078                 printf ("Invalid audio message %d\n", read_u8(data, 4));
2079                 vnc_client_error(vs);
2080                 break;
2081             }
2082             break;
2083 
2084         default:
2085             printf("Msg: %d\n", read_u16(data, 0));
2086             vnc_client_error(vs);
2087             break;
2088         }
2089         break;
2090     default:
2091         printf("Msg: %d\n", data[0]);
2092         vnc_client_error(vs);
2093         break;
2094     }
2095 
2096     vnc_read_when(vs, protocol_client_msg, 1);
2097     return 0;
2098 }
2099 
2100 static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
2101 {
2102     char buf[1024];
2103     VncShareMode mode;
2104     int size;
2105 
2106     mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;
2107     switch (vs->vd->share_policy) {
2108     case VNC_SHARE_POLICY_IGNORE:
2109         /*
2110          * Ignore the shared flag.  Nothing to do here.
2111          *
2112          * Doesn't conform to the rfb spec but is traditional qemu
2113          * behavior, thus left here as option for compatibility
2114          * reasons.
2115          */
2116         break;
2117     case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:
2118         /*
2119          * Policy: Allow clients ask for exclusive access.
2120          *
2121          * Implementation: When a client asks for exclusive access,
2122          * disconnect all others. Shared connects are allowed as long
2123          * as no exclusive connection exists.
2124          *
2125          * This is how the rfb spec suggests to handle the shared flag.
2126          */
2127         if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2128             VncState *client;
2129             QTAILQ_FOREACH(client, &vs->vd->clients, next) {
2130                 if (vs == client) {
2131                     continue;
2132                 }
2133                 if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&
2134                     client->share_mode != VNC_SHARE_MODE_SHARED) {
2135                     continue;
2136                 }
2137                 vnc_disconnect_start(client);
2138             }
2139         }
2140         if (mode == VNC_SHARE_MODE_SHARED) {
2141             if (vs->vd->num_exclusive > 0) {
2142                 vnc_disconnect_start(vs);
2143                 return 0;
2144             }
2145         }
2146         break;
2147     case VNC_SHARE_POLICY_FORCE_SHARED:
2148         /*
2149          * Policy: Shared connects only.
2150          * Implementation: Disallow clients asking for exclusive access.
2151          *
2152          * Useful for shared desktop sessions where you don't want
2153          * someone forgetting to say -shared when running the vnc
2154          * client disconnect everybody else.
2155          */
2156         if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
2157             vnc_disconnect_start(vs);
2158             return 0;
2159         }
2160         break;
2161     }
2162     vnc_set_share_mode(vs, mode);
2163 
2164     vs->client_width = ds_get_width(vs->ds);
2165     vs->client_height = ds_get_height(vs->ds);
2166     vnc_write_u16(vs, vs->client_width);
2167     vnc_write_u16(vs, vs->client_height);
2168 
2169     pixel_format_message(vs);
2170 
2171     if (qemu_name)
2172         size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
2173     else
2174         size = snprintf(buf, sizeof(buf), "QEMU");
2175 
2176     vnc_write_u32(vs, size);
2177     vnc_write(vs, buf, size);
2178     vnc_flush(vs);
2179 
2180     vnc_client_cache_auth(vs);
2181     vnc_qmp_event(vs, QEVENT_VNC_INITIALIZED);
2182 
2183     vnc_read_when(vs, protocol_client_msg, 1);
2184 
2185     return 0;
2186 }
2187 
2188 void start_client_init(VncState *vs)
2189 {
2190     vnc_read_when(vs, protocol_client_init, 1);
2191 }
2192 
2193 static void make_challenge(VncState *vs)
2194 {
2195     int i;
2196 
2197     srand(time(NULL)+getpid()+getpid()*987654+rand());
2198 
2199     for (i = 0 ; i < sizeof(vs->challenge) ; i++)
2200         vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
2201 }
2202 
2203 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
2204 {
2205     unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2206     int i, j, pwlen;
2207     unsigned char key[8];
2208     time_t now = time(NULL);
2209 
2210     if (!vs->vd->password) {
2211         VNC_DEBUG("No password configured on server");
2212         goto reject;
2213     }
2214     if (vs->vd->expires < now) {
2215         VNC_DEBUG("Password is expired");
2216         goto reject;
2217     }
2218 
2219     memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
2220 
2221     /* Calculate the expected challenge response */
2222     pwlen = strlen(vs->vd->password);
2223     for (i=0; i<sizeof(key); i++)
2224         key[i] = i<pwlen ? vs->vd->password[i] : 0;
2225     deskey(key, EN0);
2226     for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
2227         des(response+j, response+j);
2228 
2229     /* Compare expected vs actual challenge response */
2230     if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
2231         VNC_DEBUG("Client challenge response did not match\n");
2232         goto reject;
2233     } else {
2234         VNC_DEBUG("Accepting VNC challenge response\n");
2235         vnc_write_u32(vs, 0); /* Accept auth */
2236         vnc_flush(vs);
2237 
2238         start_client_init(vs);
2239     }
2240     return 0;
2241 
2242 reject:
2243     vnc_write_u32(vs, 1); /* Reject auth */
2244     if (vs->minor >= 8) {
2245         static const char err[] = "Authentication failed";
2246         vnc_write_u32(vs, sizeof(err));
2247         vnc_write(vs, err, sizeof(err));
2248     }
2249     vnc_flush(vs);
2250     vnc_client_error(vs);
2251     return 0;
2252 }
2253 
2254 void start_auth_vnc(VncState *vs)
2255 {
2256     make_challenge(vs);
2257     /* Send client a 'random' challenge */
2258     vnc_write(vs, vs->challenge, sizeof(vs->challenge));
2259     vnc_flush(vs);
2260 
2261     vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
2262 }
2263 
2264 
2265 static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
2266 {
2267     /* We only advertise 1 auth scheme at a time, so client
2268      * must pick the one we sent. Verify this */
2269     if (data[0] != vs->auth) { /* Reject auth */
2270        VNC_DEBUG("Reject auth %d because it didn't match advertized\n", (int)data[0]);
2271        vnc_write_u32(vs, 1);
2272        if (vs->minor >= 8) {
2273            static const char err[] = "Authentication failed";
2274            vnc_write_u32(vs, sizeof(err));
2275            vnc_write(vs, err, sizeof(err));
2276        }
2277        vnc_client_error(vs);
2278     } else { /* Accept requested auth */
2279        VNC_DEBUG("Client requested auth %d\n", (int)data[0]);
2280        switch (vs->auth) {
2281        case VNC_AUTH_NONE:
2282            VNC_DEBUG("Accept auth none\n");
2283            if (vs->minor >= 8) {
2284                vnc_write_u32(vs, 0); /* Accept auth completion */
2285                vnc_flush(vs);
2286            }
2287            start_client_init(vs);
2288            break;
2289 
2290        case VNC_AUTH_VNC:
2291            VNC_DEBUG("Start VNC auth\n");
2292            start_auth_vnc(vs);
2293            break;
2294 
2295 #ifdef CONFIG_VNC_TLS
2296        case VNC_AUTH_VENCRYPT:
2297            VNC_DEBUG("Accept VeNCrypt auth\n");
2298            start_auth_vencrypt(vs);
2299            break;
2300 #endif /* CONFIG_VNC_TLS */
2301 
2302 #ifdef CONFIG_VNC_SASL
2303        case VNC_AUTH_SASL:
2304            VNC_DEBUG("Accept SASL auth\n");
2305            start_auth_sasl(vs);
2306            break;
2307 #endif /* CONFIG_VNC_SASL */
2308 
2309        default: /* Should not be possible, but just in case */
2310            VNC_DEBUG("Reject auth %d server code bug\n", vs->auth);
2311            vnc_write_u8(vs, 1);
2312            if (vs->minor >= 8) {
2313                static const char err[] = "Authentication failed";
2314                vnc_write_u32(vs, sizeof(err));
2315                vnc_write(vs, err, sizeof(err));
2316            }
2317            vnc_client_error(vs);
2318        }
2319     }
2320     return 0;
2321 }
2322 
2323 static int protocol_version(VncState *vs, uint8_t *version, size_t len)
2324 {
2325     char local[13];
2326 
2327     memcpy(local, version, 12);
2328     local[12] = 0;
2329 
2330     if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2331         VNC_DEBUG("Malformed protocol version %s\n", local);
2332         vnc_client_error(vs);
2333         return 0;
2334     }
2335     VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2336     if (vs->major != 3 ||
2337         (vs->minor != 3 &&
2338          vs->minor != 4 &&
2339          vs->minor != 5 &&
2340          vs->minor != 7 &&
2341          vs->minor != 8)) {
2342         VNC_DEBUG("Unsupported client version\n");
2343         vnc_write_u32(vs, VNC_AUTH_INVALID);
2344         vnc_flush(vs);
2345         vnc_client_error(vs);
2346         return 0;
2347     }
2348     /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2349      * as equivalent to v3.3 by servers
2350      */
2351     if (vs->minor == 4 || vs->minor == 5)
2352         vs->minor = 3;
2353 
2354     if (vs->minor == 3) {
2355         if (vs->auth == VNC_AUTH_NONE) {
2356             VNC_DEBUG("Tell client auth none\n");
2357             vnc_write_u32(vs, vs->auth);
2358             vnc_flush(vs);
2359             start_client_init(vs);
2360        } else if (vs->auth == VNC_AUTH_VNC) {
2361             VNC_DEBUG("Tell client VNC auth\n");
2362             vnc_write_u32(vs, vs->auth);
2363             vnc_flush(vs);
2364             start_auth_vnc(vs);
2365        } else {
2366             VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->auth);
2367             vnc_write_u32(vs, VNC_AUTH_INVALID);
2368             vnc_flush(vs);
2369             vnc_client_error(vs);
2370        }
2371     } else {
2372         VNC_DEBUG("Telling client we support auth %d\n", vs->auth);
2373         vnc_write_u8(vs, 1); /* num auth */
2374         vnc_write_u8(vs, vs->auth);
2375         vnc_read_when(vs, protocol_client_auth, 1);
2376         vnc_flush(vs);
2377     }
2378 
2379     return 0;
2380 }
2381 
2382 static VncRectStat *vnc_stat_rect(VncDisplay *vd, int x, int y)
2383 {
2384     struct VncSurface *vs = &vd->guest;
2385 
2386     return &vs->stats[y / VNC_STAT_RECT][x / VNC_STAT_RECT];
2387 }
2388 
2389 void vnc_sent_lossy_rect(VncState *vs, int x, int y, int w, int h)
2390 {
2391     int i, j;
2392 
2393     w = (x + w) / VNC_STAT_RECT;
2394     h = (y + h) / VNC_STAT_RECT;
2395     x /= VNC_STAT_RECT;
2396     y /= VNC_STAT_RECT;
2397 
2398     for (j = y; j <= h; j++) {
2399         for (i = x; i <= w; i++) {
2400             vs->lossy_rect[j][i] = 1;
2401         }
2402     }
2403 }
2404 
2405 static int vnc_refresh_lossy_rect(VncDisplay *vd, int x, int y)
2406 {
2407     VncState *vs;
2408     int sty = y / VNC_STAT_RECT;
2409     int stx = x / VNC_STAT_RECT;
2410     int has_dirty = 0;
2411 
2412     y = y / VNC_STAT_RECT * VNC_STAT_RECT;
2413     x = x / VNC_STAT_RECT * VNC_STAT_RECT;
2414 
2415     QTAILQ_FOREACH(vs, &vd->clients, next) {
2416         int j;
2417 
2418         /* kernel send buffers are full -> refresh later */
2419         if (vs->output.offset) {
2420             continue;
2421         }
2422 
2423         if (!vs->lossy_rect[sty][stx]) {
2424             continue;
2425         }
2426 
2427         vs->lossy_rect[sty][stx] = 0;
2428         for (j = 0; j < VNC_STAT_RECT; ++j) {
2429             bitmap_set(vs->dirty[y + j], x / 16, VNC_STAT_RECT / 16);
2430         }
2431         has_dirty++;
2432     }
2433 
2434     return has_dirty;
2435 }
2436 
2437 static int vnc_update_stats(VncDisplay *vd,  struct timeval * tv)
2438 {
2439     int x, y;
2440     struct timeval res;
2441     int has_dirty = 0;
2442 
2443     for (y = 0; y < vd->guest.ds->height; y += VNC_STAT_RECT) {
2444         for (x = 0; x < vd->guest.ds->width; x += VNC_STAT_RECT) {
2445             VncRectStat *rect = vnc_stat_rect(vd, x, y);
2446 
2447             rect->updated = false;
2448         }
2449     }
2450 
2451     qemu_timersub(tv, &VNC_REFRESH_STATS, &res);
2452 
2453     if (timercmp(&vd->guest.last_freq_check, &res, >)) {
2454         return has_dirty;
2455     }
2456     vd->guest.last_freq_check = *tv;
2457 
2458     for (y = 0; y < vd->guest.ds->height; y += VNC_STAT_RECT) {
2459         for (x = 0; x < vd->guest.ds->width; x += VNC_STAT_RECT) {
2460             VncRectStat *rect= vnc_stat_rect(vd, x, y);
2461             int count = ARRAY_SIZE(rect->times);
2462             struct timeval min, max;
2463 
2464             if (!timerisset(&rect->times[count - 1])) {
2465                 continue ;
2466             }
2467 
2468             max = rect->times[(rect->idx + count - 1) % count];
2469             qemu_timersub(tv, &max, &res);
2470 
2471             if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {
2472                 rect->freq = 0;
2473                 has_dirty += vnc_refresh_lossy_rect(vd, x, y);
2474                 memset(rect->times, 0, sizeof (rect->times));
2475                 continue ;
2476             }
2477 
2478             min = rect->times[rect->idx];
2479             max = rect->times[(rect->idx + count - 1) % count];
2480             qemu_timersub(&max, &min, &res);
2481 
2482             rect->freq = res.tv_sec + res.tv_usec / 1000000.;
2483             rect->freq /= count;
2484             rect->freq = 1. / rect->freq;
2485         }
2486     }
2487     return has_dirty;
2488 }
2489 
2490 double vnc_update_freq(VncState *vs, int x, int y, int w, int h)
2491 {
2492     int i, j;
2493     double total = 0;
2494     int num = 0;
2495 
2496     x =  (x / VNC_STAT_RECT) * VNC_STAT_RECT;
2497     y =  (y / VNC_STAT_RECT) * VNC_STAT_RECT;
2498 
2499     for (j = y; j <= y + h; j += VNC_STAT_RECT) {
2500         for (i = x; i <= x + w; i += VNC_STAT_RECT) {
2501             total += vnc_stat_rect(vs->vd, i, j)->freq;
2502             num++;
2503         }
2504     }
2505 
2506     if (num) {
2507         return total / num;
2508     } else {
2509         return 0;
2510     }
2511 }
2512 
2513 static void vnc_rect_updated(VncDisplay *vd, int x, int y, struct timeval * tv)
2514 {
2515     VncRectStat *rect;
2516 
2517     rect = vnc_stat_rect(vd, x, y);
2518     if (rect->updated) {
2519         return ;
2520     }
2521     rect->times[rect->idx] = *tv;
2522     rect->idx = (rect->idx + 1) % ARRAY_SIZE(rect->times);
2523     rect->updated = true;
2524 }
2525 
2526 static int vnc_refresh_server_surface(VncDisplay *vd)
2527 {
2528     int y;
2529     uint8_t *guest_row;
2530     uint8_t *server_row;
2531     int cmp_bytes;
2532     VncState *vs;
2533     int has_dirty = 0;
2534 
2535     struct timeval tv = { 0, 0 };
2536 
2537     if (!vd->non_adaptive) {
2538         gettimeofday(&tv, NULL);
2539         has_dirty = vnc_update_stats(vd, &tv);
2540     }
2541 
2542     /*
2543      * Walk through the guest dirty map.
2544      * Check and copy modified bits from guest to server surface.
2545      * Update server dirty map.
2546      */
2547     cmp_bytes = 16 * ds_get_bytes_per_pixel(vd->ds);
2548     if (cmp_bytes > vd->ds->surface->linesize) {
2549         cmp_bytes = vd->ds->surface->linesize;
2550     }
2551     guest_row  = vd->guest.ds->data;
2552     server_row = vd->server->data;
2553     for (y = 0; y < vd->guest.ds->height; y++) {
2554         if (!bitmap_empty(vd->guest.dirty[y], VNC_DIRTY_BITS)) {
2555             int x;
2556             uint8_t *guest_ptr;
2557             uint8_t *server_ptr;
2558 
2559             guest_ptr  = guest_row;
2560             server_ptr = server_row;
2561 
2562             for (x = 0; x + 15 < vd->guest.ds->width;
2563                     x += 16, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
2564                 if (!test_and_clear_bit((x / 16), vd->guest.dirty[y]))
2565                     continue;
2566                 if (memcmp(server_ptr, guest_ptr, cmp_bytes) == 0)
2567                     continue;
2568                 memcpy(server_ptr, guest_ptr, cmp_bytes);
2569                 if (!vd->non_adaptive)
2570                     vnc_rect_updated(vd, x, y, &tv);
2571                 QTAILQ_FOREACH(vs, &vd->clients, next) {
2572                     set_bit((x / 16), vs->dirty[y]);
2573                 }
2574                 has_dirty++;
2575             }
2576         }
2577         guest_row  += ds_get_linesize(vd->ds);
2578         server_row += ds_get_linesize(vd->ds);
2579     }
2580     return has_dirty;
2581 }
2582 
2583 static void vnc_refresh(void *opaque)
2584 {
2585     VncDisplay *vd = opaque;
2586     VncState *vs, *vn;
2587     int has_dirty, rects = 0;
2588 
2589     vga_hw_update();
2590 
2591     if (vnc_trylock_display(vd)) {
2592         vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
2593         qemu_mod_timer(vd->timer, qemu_get_clock_ms(rt_clock) +
2594                        vd->timer_interval);
2595         return;
2596     }
2597 
2598     has_dirty = vnc_refresh_server_surface(vd);
2599     vnc_unlock_display(vd);
2600 
2601     QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
2602         rects += vnc_update_client(vs, has_dirty);
2603         /* vs might be free()ed here */
2604     }
2605 
2606     /* vd->timer could be NULL now if the last client disconnected,
2607      * in this case don't update the timer */
2608     if (vd->timer == NULL)
2609         return;
2610 
2611     if (has_dirty && rects) {
2612         vd->timer_interval /= 2;
2613         if (vd->timer_interval < VNC_REFRESH_INTERVAL_BASE)
2614             vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
2615     } else {
2616         vd->timer_interval += VNC_REFRESH_INTERVAL_INC;
2617         if (vd->timer_interval > VNC_REFRESH_INTERVAL_MAX)
2618             vd->timer_interval = VNC_REFRESH_INTERVAL_MAX;
2619     }
2620     qemu_mod_timer(vd->timer, qemu_get_clock_ms(rt_clock) + vd->timer_interval);
2621 }
2622 
2623 static void vnc_init_timer(VncDisplay *vd)
2624 {
2625     vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
2626     if (vd->timer == NULL && !QTAILQ_EMPTY(&vd->clients)) {
2627         vd->timer = qemu_new_timer_ms(rt_clock, vnc_refresh, vd);
2628         vnc_dpy_resize(vd->ds);
2629         vnc_refresh(vd);
2630     }
2631 }
2632 
2633 static void vnc_remove_timer(VncDisplay *vd)
2634 {
2635     if (vd->timer != NULL && QTAILQ_EMPTY(&vd->clients)) {
2636         qemu_del_timer(vd->timer);
2637         qemu_free_timer(vd->timer);
2638         vd->timer = NULL;
2639     }
2640 }
2641 
2642 static void vnc_connect(VncDisplay *vd, int csock, int skipauth)
2643 {
2644     VncState *vs = g_malloc0(sizeof(VncState));
2645     int i;
2646 
2647     vs->csock = csock;
2648 
2649     if (skipauth) {
2650 	vs->auth = VNC_AUTH_NONE;
2651 #ifdef CONFIG_VNC_TLS
2652 	vs->subauth = VNC_AUTH_INVALID;
2653 #endif
2654     } else {
2655 	vs->auth = vd->auth;
2656 #ifdef CONFIG_VNC_TLS
2657 	vs->subauth = vd->subauth;
2658 #endif
2659     }
2660 
2661     vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));
2662     for (i = 0; i < VNC_STAT_ROWS; ++i) {
2663         vs->lossy_rect[i] = g_malloc0(VNC_STAT_COLS * sizeof (uint8_t));
2664     }
2665 
2666     VNC_DEBUG("New client on socket %d\n", csock);
2667     dcl->idle = 0;
2668     socket_set_nonblock(vs->csock);
2669     qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
2670 
2671     vnc_client_cache_addr(vs);
2672     vnc_qmp_event(vs, QEVENT_VNC_CONNECTED);
2673     vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
2674 
2675     vs->vd = vd;
2676     vs->ds = vd->ds;
2677     vs->last_x = -1;
2678     vs->last_y = -1;
2679 
2680     vs->as.freq = 44100;
2681     vs->as.nchannels = 2;
2682     vs->as.fmt = AUD_FMT_S16;
2683     vs->as.endianness = 0;
2684 
2685     qemu_mutex_init(&vs->output_mutex);
2686     vs->bh = qemu_bh_new(vnc_jobs_bh, vs);
2687 
2688     QTAILQ_INSERT_HEAD(&vd->clients, vs, next);
2689 
2690     vga_hw_update();
2691 
2692     vnc_write(vs, "RFB 003.008\n", 12);
2693     vnc_flush(vs);
2694     vnc_read_when(vs, protocol_version, 12);
2695     reset_keys(vs);
2696     if (vs->vd->lock_key_sync)
2697         vs->led = qemu_add_led_event_handler(kbd_leds, vs);
2698 
2699     vs->mouse_mode_notifier.notify = check_pointer_type_change;
2700     qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
2701 
2702     vnc_init_timer(vd);
2703 
2704     /* vs might be free()ed here */
2705 }
2706 
2707 static void vnc_listen_read(void *opaque)
2708 {
2709     VncDisplay *vs = opaque;
2710     struct sockaddr_in addr;
2711     socklen_t addrlen = sizeof(addr);
2712 
2713     /* Catch-up */
2714     vga_hw_update();
2715 
2716     int csock = qemu_accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
2717     if (csock != -1) {
2718         vnc_connect(vs, csock, 0);
2719     }
2720 }
2721 
2722 void vnc_display_init(DisplayState *ds)
2723 {
2724     VncDisplay *vs = g_malloc0(sizeof(*vs));
2725 
2726     dcl = g_malloc0(sizeof(DisplayChangeListener));
2727 
2728     ds->opaque = vs;
2729     dcl->idle = 1;
2730     vnc_display = vs;
2731 
2732     vs->lsock = -1;
2733 
2734     vs->ds = ds;
2735     QTAILQ_INIT(&vs->clients);
2736     vs->expires = TIME_MAX;
2737 
2738     if (keyboard_layout)
2739         vs->kbd_layout = init_keyboard_layout(name2keysym, keyboard_layout);
2740     else
2741         vs->kbd_layout = init_keyboard_layout(name2keysym, "en-us");
2742 
2743     if (!vs->kbd_layout)
2744         exit(1);
2745 
2746     qemu_mutex_init(&vs->mutex);
2747     vnc_start_worker_thread();
2748 
2749     dcl->dpy_copy = vnc_dpy_copy;
2750     dcl->dpy_update = vnc_dpy_update;
2751     dcl->dpy_resize = vnc_dpy_resize;
2752     dcl->dpy_setdata = vnc_dpy_setdata;
2753     register_displaychangelistener(ds, dcl);
2754     ds->mouse_set = vnc_mouse_set;
2755     ds->cursor_define = vnc_dpy_cursor_define;
2756 }
2757 
2758 
2759 void vnc_display_close(DisplayState *ds)
2760 {
2761     VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2762 
2763     if (!vs)
2764         return;
2765     if (vs->display) {
2766         g_free(vs->display);
2767         vs->display = NULL;
2768     }
2769     if (vs->lsock != -1) {
2770         qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);
2771         close(vs->lsock);
2772         vs->lsock = -1;
2773     }
2774     vs->auth = VNC_AUTH_INVALID;
2775 #ifdef CONFIG_VNC_TLS
2776     vs->subauth = VNC_AUTH_INVALID;
2777     vs->tls.x509verify = 0;
2778 #endif
2779 }
2780 
2781 int vnc_display_disable_login(DisplayState *ds)
2782 {
2783     VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2784 
2785     if (!vs) {
2786         return -1;
2787     }
2788 
2789     if (vs->password) {
2790         g_free(vs->password);
2791     }
2792 
2793     vs->password = NULL;
2794     if (vs->auth == VNC_AUTH_NONE) {
2795         vs->auth = VNC_AUTH_VNC;
2796     }
2797 
2798     return 0;
2799 }
2800 
2801 int vnc_display_password(DisplayState *ds, const char *password)
2802 {
2803     VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2804 
2805     if (!vs) {
2806         return -EINVAL;
2807     }
2808 
2809     if (!password) {
2810         /* This is not the intention of this interface but err on the side
2811            of being safe */
2812         return vnc_display_disable_login(ds);
2813     }
2814 
2815     if (vs->password) {
2816         g_free(vs->password);
2817         vs->password = NULL;
2818     }
2819     vs->password = g_strdup(password);
2820     if (vs->auth == VNC_AUTH_NONE) {
2821         vs->auth = VNC_AUTH_VNC;
2822     }
2823 
2824     return 0;
2825 }
2826 
2827 int vnc_display_pw_expire(DisplayState *ds, time_t expires)
2828 {
2829     VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2830 
2831     if (!vs) {
2832         return -EINVAL;
2833     }
2834 
2835     vs->expires = expires;
2836     return 0;
2837 }
2838 
2839 char *vnc_display_local_addr(DisplayState *ds)
2840 {
2841     VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2842 
2843     return vnc_socket_local_addr("%s:%s", vs->lsock);
2844 }
2845 
2846 int vnc_display_open(DisplayState *ds, const char *display)
2847 {
2848     VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2849     const char *options;
2850     int password = 0;
2851     int reverse = 0;
2852 #ifdef CONFIG_VNC_TLS
2853     int tls = 0, x509 = 0;
2854 #endif
2855 #ifdef CONFIG_VNC_SASL
2856     int sasl = 0;
2857     int saslErr;
2858 #endif
2859 #if defined(CONFIG_VNC_TLS) || defined(CONFIG_VNC_SASL)
2860     int acl = 0;
2861 #endif
2862     int lock_key_sync = 1;
2863 
2864     if (!vnc_display)
2865         return -1;
2866     vnc_display_close(ds);
2867     if (strcmp(display, "none") == 0)
2868         return 0;
2869 
2870     if (!(vs->display = strdup(display)))
2871         return -1;
2872     vs->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
2873 
2874     options = display;
2875     while ((options = strchr(options, ','))) {
2876         options++;
2877         if (strncmp(options, "password", 8) == 0) {
2878             password = 1; /* Require password auth */
2879         } else if (strncmp(options, "reverse", 7) == 0) {
2880             reverse = 1;
2881         } else if (strncmp(options, "no-lock-key-sync", 16) == 0) {
2882             lock_key_sync = 0;
2883 #ifdef CONFIG_VNC_SASL
2884         } else if (strncmp(options, "sasl", 4) == 0) {
2885             sasl = 1; /* Require SASL auth */
2886 #endif
2887 #ifdef CONFIG_VNC_TLS
2888         } else if (strncmp(options, "tls", 3) == 0) {
2889             tls = 1; /* Require TLS */
2890         } else if (strncmp(options, "x509", 4) == 0) {
2891             char *start, *end;
2892             x509 = 1; /* Require x509 certificates */
2893             if (strncmp(options, "x509verify", 10) == 0)
2894                 vs->tls.x509verify = 1; /* ...and verify client certs */
2895 
2896             /* Now check for 'x509=/some/path' postfix
2897              * and use that to setup x509 certificate/key paths */
2898             start = strchr(options, '=');
2899             end = strchr(options, ',');
2900             if (start && (!end || (start < end))) {
2901                 int len = end ? end-(start+1) : strlen(start+1);
2902                 char *path = g_strndup(start + 1, len);
2903 
2904                 VNC_DEBUG("Trying certificate path '%s'\n", path);
2905                 if (vnc_tls_set_x509_creds_dir(vs, path) < 0) {
2906                     fprintf(stderr, "Failed to find x509 certificates/keys in %s\n", path);
2907                     g_free(path);
2908                     g_free(vs->display);
2909                     vs->display = NULL;
2910                     return -1;
2911                 }
2912                 g_free(path);
2913             } else {
2914                 fprintf(stderr, "No certificate path provided\n");
2915                 g_free(vs->display);
2916                 vs->display = NULL;
2917                 return -1;
2918             }
2919 #endif
2920 #if defined(CONFIG_VNC_TLS) || defined(CONFIG_VNC_SASL)
2921         } else if (strncmp(options, "acl", 3) == 0) {
2922             acl = 1;
2923 #endif
2924         } else if (strncmp(options, "lossy", 5) == 0) {
2925             vs->lossy = true;
2926         } else if (strncmp(options, "non-adapative", 13) == 0) {
2927             vs->non_adaptive = true;
2928         } else if (strncmp(options, "share=", 6) == 0) {
2929             if (strncmp(options+6, "ignore", 6) == 0) {
2930                 vs->share_policy = VNC_SHARE_POLICY_IGNORE;
2931             } else if (strncmp(options+6, "allow-exclusive", 15) == 0) {
2932                 vs->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
2933             } else if (strncmp(options+6, "force-shared", 12) == 0) {
2934                 vs->share_policy = VNC_SHARE_POLICY_FORCE_SHARED;
2935             } else {
2936                 fprintf(stderr, "unknown vnc share= option\n");
2937                 g_free(vs->display);
2938                 vs->display = NULL;
2939                 return -1;
2940             }
2941         }
2942     }
2943 
2944 #ifdef CONFIG_VNC_TLS
2945     if (acl && x509 && vs->tls.x509verify) {
2946         if (!(vs->tls.acl = qemu_acl_init("vnc.x509dname"))) {
2947             fprintf(stderr, "Failed to create x509 dname ACL\n");
2948             exit(1);
2949         }
2950     }
2951 #endif
2952 #ifdef CONFIG_VNC_SASL
2953     if (acl && sasl) {
2954         if (!(vs->sasl.acl = qemu_acl_init("vnc.username"))) {
2955             fprintf(stderr, "Failed to create username ACL\n");
2956             exit(1);
2957         }
2958     }
2959 #endif
2960 
2961     /*
2962      * Combinations we support here:
2963      *
2964      *  - no-auth                (clear text, no auth)
2965      *  - password               (clear text, weak auth)
2966      *  - sasl                   (encrypt, good auth *IF* using Kerberos via GSSAPI)
2967      *  - tls                    (encrypt, weak anonymous creds, no auth)
2968      *  - tls + password         (encrypt, weak anonymous creds, weak auth)
2969      *  - tls + sasl             (encrypt, weak anonymous creds, good auth)
2970      *  - tls + x509             (encrypt, good x509 creds, no auth)
2971      *  - tls + x509 + password  (encrypt, good x509 creds, weak auth)
2972      *  - tls + x509 + sasl      (encrypt, good x509 creds, good auth)
2973      *
2974      * NB1. TLS is a stackable auth scheme.
2975      * NB2. the x509 schemes have option to validate a client cert dname
2976      */
2977     if (password) {
2978 #ifdef CONFIG_VNC_TLS
2979         if (tls) {
2980             vs->auth = VNC_AUTH_VENCRYPT;
2981             if (x509) {
2982                 VNC_DEBUG("Initializing VNC server with x509 password auth\n");
2983                 vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;
2984             } else {
2985                 VNC_DEBUG("Initializing VNC server with TLS password auth\n");
2986                 vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
2987             }
2988         } else {
2989 #endif /* CONFIG_VNC_TLS */
2990             VNC_DEBUG("Initializing VNC server with password auth\n");
2991             vs->auth = VNC_AUTH_VNC;
2992 #ifdef CONFIG_VNC_TLS
2993             vs->subauth = VNC_AUTH_INVALID;
2994         }
2995 #endif /* CONFIG_VNC_TLS */
2996 #ifdef CONFIG_VNC_SASL
2997     } else if (sasl) {
2998 #ifdef CONFIG_VNC_TLS
2999         if (tls) {
3000             vs->auth = VNC_AUTH_VENCRYPT;
3001             if (x509) {
3002                 VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
3003                 vs->subauth = VNC_AUTH_VENCRYPT_X509SASL;
3004             } else {
3005                 VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
3006                 vs->subauth = VNC_AUTH_VENCRYPT_TLSSASL;
3007             }
3008         } else {
3009 #endif /* CONFIG_VNC_TLS */
3010             VNC_DEBUG("Initializing VNC server with SASL auth\n");
3011             vs->auth = VNC_AUTH_SASL;
3012 #ifdef CONFIG_VNC_TLS
3013             vs->subauth = VNC_AUTH_INVALID;
3014         }
3015 #endif /* CONFIG_VNC_TLS */
3016 #endif /* CONFIG_VNC_SASL */
3017     } else {
3018 #ifdef CONFIG_VNC_TLS
3019         if (tls) {
3020             vs->auth = VNC_AUTH_VENCRYPT;
3021             if (x509) {
3022                 VNC_DEBUG("Initializing VNC server with x509 no auth\n");
3023                 vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;
3024             } else {
3025                 VNC_DEBUG("Initializing VNC server with TLS no auth\n");
3026                 vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
3027             }
3028         } else {
3029 #endif
3030             VNC_DEBUG("Initializing VNC server with no auth\n");
3031             vs->auth = VNC_AUTH_NONE;
3032 #ifdef CONFIG_VNC_TLS
3033             vs->subauth = VNC_AUTH_INVALID;
3034         }
3035 #endif
3036     }
3037 
3038 #ifdef CONFIG_VNC_SASL
3039     if ((saslErr = sasl_server_init(NULL, "qemu")) != SASL_OK) {
3040         fprintf(stderr, "Failed to initialize SASL auth %s",
3041                 sasl_errstring(saslErr, NULL, NULL));
3042         g_free(vs->display);
3043         vs->display = NULL;
3044         return -1;
3045     }
3046 #endif
3047     vs->lock_key_sync = lock_key_sync;
3048 
3049     if (reverse) {
3050         /* connect to viewer */
3051         if (strncmp(display, "unix:", 5) == 0)
3052             vs->lsock = unix_connect(display+5);
3053         else
3054             vs->lsock = inet_connect(display, true, NULL);
3055         if (-1 == vs->lsock) {
3056             g_free(vs->display);
3057             vs->display = NULL;
3058             return -1;
3059         } else {
3060             int csock = vs->lsock;
3061             vs->lsock = -1;
3062             vnc_connect(vs, csock, 0);
3063         }
3064         return 0;
3065 
3066     } else {
3067         /* listen for connects */
3068         char *dpy;
3069         dpy = g_malloc(256);
3070         if (strncmp(display, "unix:", 5) == 0) {
3071             pstrcpy(dpy, 256, "unix:");
3072             vs->lsock = unix_listen(display+5, dpy+5, 256-5);
3073         } else {
3074             vs->lsock = inet_listen(display, dpy, 256,
3075                                     SOCK_STREAM, 5900, NULL);
3076         }
3077         if (-1 == vs->lsock) {
3078             g_free(dpy);
3079             return -1;
3080         } else {
3081             g_free(vs->display);
3082             vs->display = dpy;
3083         }
3084     }
3085     return qemu_set_fd_handler2(vs->lsock, NULL, vnc_listen_read, NULL, vs);
3086 }
3087 
3088 void vnc_display_add_client(DisplayState *ds, int csock, int skipauth)
3089 {
3090     VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
3091 
3092     return vnc_connect(vs, csock, skipauth);
3093 }
3094