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