Statistics
| Branch: | Revision:

root / ui / vnc.c @ bd023f95

History | View | Annotate | Download (78.4 kB)

1
/*
2
 * QEMU VNC display driver
3
 *
4
 * Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>
5
 * Copyright (C) 2006 Fabrice Bellard
6
 * Copyright (C) 2009 Red Hat, Inc
7
 *
8
 * Permission is hereby granted, free of charge, to any person obtaining a copy
9
 * of this software and associated documentation files (the "Software"), to deal
10
 * in the Software without restriction, including without limitation the rights
11
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
 * copies of the Software, and to permit persons to whom the Software is
13
 * furnished to do so, subject to the following conditions:
14
 *
15
 * The above copyright notice and this permission notice shall be included in
16
 * all copies or substantial portions of the Software.
17
 *
18
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24
 * THE SOFTWARE.
25
 */
26

    
27
#include "vnc.h"
28
#include "vnc-jobs.h"
29
#include "sysemu.h"
30
#include "qemu_socket.h"
31
#include "qemu-timer.h"
32
#include "acl.h"
33
#include "qemu-objects.h"
34

    
35
#define VNC_REFRESH_INTERVAL_BASE 30
36
#define VNC_REFRESH_INTERVAL_INC  50
37
#define VNC_REFRESH_INTERVAL_MAX  2000
38

    
39
#include "vnc_keysym.h"
40
#include "d3des.h"
41

    
42
#define count_bits(c, v) { \
43
    for (c = 0; v; v >>= 1) \
44
    { \
45
        c += v & 1; \
46
    } \
47
}
48

    
49
static VncDisplay *vnc_display; /* needed for info vnc */
50
static DisplayChangeListener *dcl;
51

    
52
static int vnc_cursor_define(VncState *vs);
53

    
54
static char *addr_to_string(const char *format,
55
                            struct sockaddr_storage *sa,
56
                            socklen_t salen) {
57
    char *addr;
58
    char host[NI_MAXHOST];
59
    char serv[NI_MAXSERV];
60
    int err;
61
    size_t addrlen;
62

    
63
    if ((err = getnameinfo((struct sockaddr *)sa, salen,
64
                           host, sizeof(host),
65
                           serv, sizeof(serv),
66
                           NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
67
        VNC_DEBUG("Cannot resolve address %d: %s\n",
68
                  err, gai_strerror(err));
69
        return NULL;
70
    }
71

    
72
    /* Enough for the existing format + the 2 vars we're
73
     * substituting in. */
74
    addrlen = strlen(format) + strlen(host) + strlen(serv);
75
    addr = qemu_malloc(addrlen + 1);
76
    snprintf(addr, addrlen, format, host, serv);
77
    addr[addrlen] = '\0';
78

    
79
    return addr;
80
}
81

    
82

    
83
char *vnc_socket_local_addr(const char *format, int fd) {
84
    struct sockaddr_storage sa;
85
    socklen_t salen;
86

    
87
    salen = sizeof(sa);
88
    if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0)
89
        return NULL;
90

    
91
    return addr_to_string(format, &sa, salen);
92
}
93

    
94
char *vnc_socket_remote_addr(const char *format, int fd) {
95
    struct sockaddr_storage sa;
96
    socklen_t salen;
97

    
98
    salen = sizeof(sa);
99
    if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0)
100
        return NULL;
101

    
102
    return addr_to_string(format, &sa, salen);
103
}
104

    
105
static int put_addr_qdict(QDict *qdict, struct sockaddr_storage *sa,
106
                          socklen_t salen)
107
{
108
    char host[NI_MAXHOST];
109
    char serv[NI_MAXSERV];
110
    int err;
111

    
112
    if ((err = getnameinfo((struct sockaddr *)sa, salen,
113
                           host, sizeof(host),
114
                           serv, sizeof(serv),
115
                           NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
116
        VNC_DEBUG("Cannot resolve address %d: %s\n",
117
                  err, gai_strerror(err));
118
        return -1;
119
    }
120

    
121
    qdict_put(qdict, "host", qstring_from_str(host));
122
    qdict_put(qdict, "service", qstring_from_str(serv));
123
    qdict_put(qdict, "family",qstring_from_str(inet_strfamily(sa->ss_family)));
124

    
125
    return 0;
126
}
127

    
128
static int vnc_server_addr_put(QDict *qdict, int fd)
129
{
130
    struct sockaddr_storage sa;
131
    socklen_t salen;
132

    
133
    salen = sizeof(sa);
134
    if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0) {
135
        return -1;
136
    }
137

    
138
    return put_addr_qdict(qdict, &sa, salen);
139
}
140

    
141
static int vnc_qdict_remote_addr(QDict *qdict, int fd)
142
{
143
    struct sockaddr_storage sa;
144
    socklen_t salen;
145

    
146
    salen = sizeof(sa);
147
    if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0) {
148
        return -1;
149
    }
150

    
151
    return put_addr_qdict(qdict, &sa, salen);
152
}
153

    
154
static const char *vnc_auth_name(VncDisplay *vd) {
155
    switch (vd->auth) {
156
    case VNC_AUTH_INVALID:
157
        return "invalid";
158
    case VNC_AUTH_NONE:
159
        return "none";
160
    case VNC_AUTH_VNC:
161
        return "vnc";
162
    case VNC_AUTH_RA2:
163
        return "ra2";
164
    case VNC_AUTH_RA2NE:
165
        return "ra2ne";
166
    case VNC_AUTH_TIGHT:
167
        return "tight";
168
    case VNC_AUTH_ULTRA:
169
        return "ultra";
170
    case VNC_AUTH_TLS:
171
        return "tls";
172
    case VNC_AUTH_VENCRYPT:
173
#ifdef CONFIG_VNC_TLS
174
        switch (vd->subauth) {
175
        case VNC_AUTH_VENCRYPT_PLAIN:
176
            return "vencrypt+plain";
177
        case VNC_AUTH_VENCRYPT_TLSNONE:
178
            return "vencrypt+tls+none";
179
        case VNC_AUTH_VENCRYPT_TLSVNC:
180
            return "vencrypt+tls+vnc";
181
        case VNC_AUTH_VENCRYPT_TLSPLAIN:
182
            return "vencrypt+tls+plain";
183
        case VNC_AUTH_VENCRYPT_X509NONE:
184
            return "vencrypt+x509+none";
185
        case VNC_AUTH_VENCRYPT_X509VNC:
186
            return "vencrypt+x509+vnc";
187
        case VNC_AUTH_VENCRYPT_X509PLAIN:
188
            return "vencrypt+x509+plain";
189
        case VNC_AUTH_VENCRYPT_TLSSASL:
190
            return "vencrypt+tls+sasl";
191
        case VNC_AUTH_VENCRYPT_X509SASL:
192
            return "vencrypt+x509+sasl";
193
        default:
194
            return "vencrypt";
195
        }
196
#else
197
        return "vencrypt";
198
#endif
199
    case VNC_AUTH_SASL:
200
        return "sasl";
201
    }
202
    return "unknown";
203
}
204

    
205
static int vnc_server_info_put(QDict *qdict)
206
{
207
    if (vnc_server_addr_put(qdict, vnc_display->lsock) < 0) {
208
        return -1;
209
    }
210

    
211
    qdict_put(qdict, "auth", qstring_from_str(vnc_auth_name(vnc_display)));
212
    return 0;
213
}
214

    
215
static void vnc_client_cache_auth(VncState *client)
216
{
217
    QDict *qdict;
218

    
219
    if (!client->info) {
220
        return;
221
    }
222

    
223
    qdict = qobject_to_qdict(client->info);
224

    
225
#ifdef CONFIG_VNC_TLS
226
    if (client->tls.session &&
227
        client->tls.dname) {
228
        qdict_put(qdict, "x509_dname", qstring_from_str(client->tls.dname));
229
    }
230
#endif
231
#ifdef CONFIG_VNC_SASL
232
    if (client->sasl.conn &&
233
        client->sasl.username) {
234
        qdict_put(qdict, "sasl_username",
235
                  qstring_from_str(client->sasl.username));
236
    }
237
#endif
238
}
239

    
240
static void vnc_client_cache_addr(VncState *client)
241
{
242
    QDict *qdict;
243

    
244
    qdict = qdict_new();
245
    if (vnc_qdict_remote_addr(qdict, client->csock) < 0) {
246
        QDECREF(qdict);
247
        /* XXX: how to report the error? */
248
        return;
249
    }
250

    
251
    client->info = QOBJECT(qdict);
252
}
253

    
254
static void vnc_qmp_event(VncState *vs, MonitorEvent event)
255
{
256
    QDict *server;
257
    QObject *data;
258

    
259
    if (!vs->info) {
260
        return;
261
    }
262

    
263
    server = qdict_new();
264
    if (vnc_server_info_put(server) < 0) {
265
        QDECREF(server);
266
        return;
267
    }
268

    
269
    data = qobject_from_jsonf("{ 'client': %p, 'server': %p }",
270
                              vs->info, QOBJECT(server));
271

    
272
    monitor_protocol_event(event, data);
273

    
274
    qobject_incref(vs->info);
275
    qobject_decref(data);
276
}
277

    
278
static void info_vnc_iter(QObject *obj, void *opaque)
279
{
280
    QDict *client;
281
    Monitor *mon = opaque;
282

    
283
    client = qobject_to_qdict(obj);
284
    monitor_printf(mon, "Client:\n");
285
    monitor_printf(mon, "     address: %s:%s\n",
286
                   qdict_get_str(client, "host"),
287
                   qdict_get_str(client, "service"));
288

    
289
#ifdef CONFIG_VNC_TLS
290
    monitor_printf(mon, "  x509_dname: %s\n",
291
        qdict_haskey(client, "x509_dname") ?
292
        qdict_get_str(client, "x509_dname") : "none");
293
#endif
294
#ifdef CONFIG_VNC_SASL
295
    monitor_printf(mon, "    username: %s\n",
296
        qdict_haskey(client, "sasl_username") ?
297
        qdict_get_str(client, "sasl_username") : "none");
298
#endif
299
}
300

    
301
void do_info_vnc_print(Monitor *mon, const QObject *data)
302
{
303
    QDict *server;
304
    QList *clients;
305

    
306
    server = qobject_to_qdict(data);
307
    if (qdict_get_bool(server, "enabled") == 0) {
308
        monitor_printf(mon, "Server: disabled\n");
309
        return;
310
    }
311

    
312
    monitor_printf(mon, "Server:\n");
313
    monitor_printf(mon, "     address: %s:%s\n",
314
                   qdict_get_str(server, "host"),
315
                   qdict_get_str(server, "service"));
316
    monitor_printf(mon, "        auth: %s\n", qdict_get_str(server, "auth"));
317

    
318
    clients = qdict_get_qlist(server, "clients");
319
    if (qlist_empty(clients)) {
320
        monitor_printf(mon, "Client: none\n");
321
    } else {
322
        qlist_iter(clients, info_vnc_iter, mon);
323
    }
324
}
325

    
326
void do_info_vnc(Monitor *mon, QObject **ret_data)
327
{
328
    if (vnc_display == NULL || vnc_display->display == NULL) {
329
        *ret_data = qobject_from_jsonf("{ 'enabled': false }");
330
    } else {
331
        QList *clist;
332
        VncState *client;
333

    
334
        clist = qlist_new();
335
        QTAILQ_FOREACH(client, &vnc_display->clients, next) {
336
            if (client->info) {
337
                /* incref so that it's not freed by upper layers */
338
                qobject_incref(client->info);
339
                qlist_append_obj(clist, client->info);
340
            }
341
        }
342

    
343
        *ret_data = qobject_from_jsonf("{ 'enabled': true, 'clients': %p }",
344
                                       QOBJECT(clist));
345
        assert(*ret_data != NULL);
346

    
347
        if (vnc_server_info_put(qobject_to_qdict(*ret_data)) < 0) {
348
            qobject_decref(*ret_data);
349
            *ret_data = NULL;
350
        }
351
    }
352
}
353

    
354
/* TODO
355
   1) Get the queue working for IO.
356
   2) there is some weirdness when using the -S option (the screen is grey
357
      and not totally invalidated
358
   3) resolutions > 1024
359
*/
360

    
361
static int vnc_update_client(VncState *vs, int has_dirty);
362
static int vnc_update_client_sync(VncState *vs, int has_dirty);
363
static void vnc_disconnect_start(VncState *vs);
364
static void vnc_disconnect_finish(VncState *vs);
365
static void vnc_init_timer(VncDisplay *vd);
366
static void vnc_remove_timer(VncDisplay *vd);
367

    
368
static void vnc_colordepth(VncState *vs);
369
static void framebuffer_update_request(VncState *vs, int incremental,
370
                                       int x_position, int y_position,
371
                                       int w, int h);
372
static void vnc_refresh(void *opaque);
373
static int vnc_refresh_server_surface(VncDisplay *vd);
374

    
375
static inline void vnc_set_bit(uint32_t *d, int k)
376
{
377
    d[k >> 5] |= 1 << (k & 0x1f);
378
}
379

    
380
static inline void vnc_clear_bit(uint32_t *d, int k)
381
{
382
    d[k >> 5] &= ~(1 << (k & 0x1f));
383
}
384

    
385
static inline void vnc_set_bits(uint32_t *d, int n, int nb_words)
386
{
387
    int j;
388

    
389
    j = 0;
390
    while (n >= 32) {
391
        d[j++] = -1;
392
        n -= 32;
393
    }
394
    if (n > 0)
395
        d[j++] = (1 << n) - 1;
396
    while (j < nb_words)
397
        d[j++] = 0;
398
}
399

    
400
static inline int vnc_get_bit(const uint32_t *d, int k)
401
{
402
    return (d[k >> 5] >> (k & 0x1f)) & 1;
403
}
404

    
405
static inline int vnc_and_bits(const uint32_t *d1, const uint32_t *d2,
406
                               int nb_words)
407
{
408
    int i;
409
    for(i = 0; i < nb_words; i++) {
410
        if ((d1[i] & d2[i]) != 0)
411
            return 1;
412
    }
413
    return 0;
414
}
415

    
416
static void vnc_dpy_update(DisplayState *ds, int x, int y, int w, int h)
417
{
418
    int i;
419
    VncDisplay *vd = ds->opaque;
420
    struct VncSurface *s = &vd->guest;
421

    
422
    h += y;
423

    
424
    /* round x down to ensure the loop only spans one 16-pixel block per,
425
       iteration.  otherwise, if (x % 16) != 0, the last iteration may span
426
       two 16-pixel blocks but we only mark the first as dirty
427
    */
428
    w += (x % 16);
429
    x -= (x % 16);
430

    
431
    x = MIN(x, s->ds->width);
432
    y = MIN(y, s->ds->height);
433
    w = MIN(x + w, s->ds->width) - x;
434
    h = MIN(h, s->ds->height);
435

    
436
    for (; y < h; y++)
437
        for (i = 0; i < w; i += 16)
438
            vnc_set_bit(s->dirty[y], (x + i) / 16);
439
}
440

    
441
void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
442
                            int32_t encoding)
443
{
444
    vnc_write_u16(vs, x);
445
    vnc_write_u16(vs, y);
446
    vnc_write_u16(vs, w);
447
    vnc_write_u16(vs, h);
448

    
449
    vnc_write_s32(vs, encoding);
450
}
451

    
452
void buffer_reserve(Buffer *buffer, size_t len)
453
{
454
    if ((buffer->capacity - buffer->offset) < len) {
455
        buffer->capacity += (len + 1024);
456
        buffer->buffer = qemu_realloc(buffer->buffer, buffer->capacity);
457
        if (buffer->buffer == NULL) {
458
            fprintf(stderr, "vnc: out of memory\n");
459
            exit(1);
460
        }
461
    }
462
}
463

    
464
int buffer_empty(Buffer *buffer)
465
{
466
    return buffer->offset == 0;
467
}
468

    
469
uint8_t *buffer_end(Buffer *buffer)
470
{
471
    return buffer->buffer + buffer->offset;
472
}
473

    
474
void buffer_reset(Buffer *buffer)
475
{
476
        buffer->offset = 0;
477
}
478

    
479
void buffer_free(Buffer *buffer)
480
{
481
    qemu_free(buffer->buffer);
482
    buffer->offset = 0;
483
    buffer->capacity = 0;
484
    buffer->buffer = NULL;
485
}
486

    
487
void buffer_append(Buffer *buffer, const void *data, size_t len)
488
{
489
    memcpy(buffer->buffer + buffer->offset, data, len);
490
    buffer->offset += len;
491
}
492

    
493
static void vnc_desktop_resize(VncState *vs)
494
{
495
    DisplayState *ds = vs->ds;
496

    
497
    if (vs->csock == -1 || !vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
498
        return;
499
    }
500
    if (vs->client_width == ds_get_width(ds) &&
501
        vs->client_height == ds_get_height(ds)) {
502
        return;
503
    }
504
    vs->client_width = ds_get_width(ds);
505
    vs->client_height = ds_get_height(ds);
506
    vnc_lock_output(vs);
507
    vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
508
    vnc_write_u8(vs, 0);
509
    vnc_write_u16(vs, 1); /* number of rects */
510
    vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
511
                           VNC_ENCODING_DESKTOPRESIZE);
512
    vnc_unlock_output(vs);
513
    vnc_flush(vs);
514
}
515

    
516
#ifdef CONFIG_VNC_THREAD
517
static void vnc_abort_display_jobs(VncDisplay *vd)
518
{
519
    VncState *vs;
520

    
521
    QTAILQ_FOREACH(vs, &vd->clients, next) {
522
        vnc_lock_output(vs);
523
        vs->abort = true;
524
        vnc_unlock_output(vs);
525
    }
526
    QTAILQ_FOREACH(vs, &vd->clients, next) {
527
        vnc_jobs_join(vs);
528
    }
529
    QTAILQ_FOREACH(vs, &vd->clients, next) {
530
        vnc_lock_output(vs);
531
        vs->abort = false;
532
        vnc_unlock_output(vs);
533
    }
534
}
535
#else
536
static void vnc_abort_display_jobs(VncDisplay *vd)
537
{
538
}
539
#endif
540

    
541
static void vnc_dpy_resize(DisplayState *ds)
542
{
543
    VncDisplay *vd = ds->opaque;
544
    VncState *vs;
545

    
546
    vnc_abort_display_jobs(vd);
547

    
548
    /* server surface */
549
    if (!vd->server)
550
        vd->server = qemu_mallocz(sizeof(*vd->server));
551
    if (vd->server->data)
552
        qemu_free(vd->server->data);
553
    *(vd->server) = *(ds->surface);
554
    vd->server->data = qemu_mallocz(vd->server->linesize *
555
                                    vd->server->height);
556

    
557
    /* guest surface */
558
    if (!vd->guest.ds)
559
        vd->guest.ds = qemu_mallocz(sizeof(*vd->guest.ds));
560
    if (ds_get_bytes_per_pixel(ds) != vd->guest.ds->pf.bytes_per_pixel)
561
        console_color_init(ds);
562
    *(vd->guest.ds) = *(ds->surface);
563
    memset(vd->guest.dirty, 0xFF, sizeof(vd->guest.dirty));
564

    
565
    QTAILQ_FOREACH(vs, &vd->clients, next) {
566
        vnc_colordepth(vs);
567
        vnc_desktop_resize(vs);
568
        if (vs->vd->cursor) {
569
            vnc_cursor_define(vs);
570
        }
571
        memset(vs->dirty, 0xFF, sizeof(vs->dirty));
572
    }
573
}
574

    
575
/* fastest code */
576
static void vnc_write_pixels_copy(VncState *vs, struct PixelFormat *pf,
577
                                  void *pixels, int size)
578
{
579
    vnc_write(vs, pixels, size);
580
}
581

    
582
/* slowest but generic code. */
583
void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
584
{
585
    uint8_t r, g, b;
586
    VncDisplay *vd = vs->vd;
587

    
588
    r = ((((v & vd->server->pf.rmask) >> vd->server->pf.rshift) << vs->clientds.pf.rbits) >>
589
        vd->server->pf.rbits);
590
    g = ((((v & vd->server->pf.gmask) >> vd->server->pf.gshift) << vs->clientds.pf.gbits) >>
591
        vd->server->pf.gbits);
592
    b = ((((v & vd->server->pf.bmask) >> vd->server->pf.bshift) << vs->clientds.pf.bbits) >>
593
        vd->server->pf.bbits);
594
    v = (r << vs->clientds.pf.rshift) |
595
        (g << vs->clientds.pf.gshift) |
596
        (b << vs->clientds.pf.bshift);
597
    switch(vs->clientds.pf.bytes_per_pixel) {
598
    case 1:
599
        buf[0] = v;
600
        break;
601
    case 2:
602
        if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) {
603
            buf[0] = v >> 8;
604
            buf[1] = v;
605
        } else {
606
            buf[1] = v >> 8;
607
            buf[0] = v;
608
        }
609
        break;
610
    default:
611
    case 4:
612
        if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) {
613
            buf[0] = v >> 24;
614
            buf[1] = v >> 16;
615
            buf[2] = v >> 8;
616
            buf[3] = v;
617
        } else {
618
            buf[3] = v >> 24;
619
            buf[2] = v >> 16;
620
            buf[1] = v >> 8;
621
            buf[0] = v;
622
        }
623
        break;
624
    }
625
}
626

    
627
static void vnc_write_pixels_generic(VncState *vs, struct PixelFormat *pf,
628
                                     void *pixels1, int size)
629
{
630
    uint8_t buf[4];
631

    
632
    if (pf->bytes_per_pixel == 4) {
633
        uint32_t *pixels = pixels1;
634
        int n, i;
635
        n = size >> 2;
636
        for(i = 0; i < n; i++) {
637
            vnc_convert_pixel(vs, buf, pixels[i]);
638
            vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
639
        }
640
    } else if (pf->bytes_per_pixel == 2) {
641
        uint16_t *pixels = pixels1;
642
        int n, i;
643
        n = size >> 1;
644
        for(i = 0; i < n; i++) {
645
            vnc_convert_pixel(vs, buf, pixels[i]);
646
            vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
647
        }
648
    } else if (pf->bytes_per_pixel == 1) {
649
        uint8_t *pixels = pixels1;
650
        int n, i;
651
        n = size;
652
        for(i = 0; i < n; i++) {
653
            vnc_convert_pixel(vs, buf, pixels[i]);
654
            vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
655
        }
656
    } else {
657
        fprintf(stderr, "vnc_write_pixels_generic: VncState color depth not supported\n");
658
    }
659
}
660

    
661
int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
662
{
663
    int i;
664
    uint8_t *row;
665
    VncDisplay *vd = vs->vd;
666

    
667
    row = vd->server->data + y * ds_get_linesize(vs->ds) + x * ds_get_bytes_per_pixel(vs->ds);
668
    for (i = 0; i < h; i++) {
669
        vs->write_pixels(vs, &vd->server->pf, row, w * ds_get_bytes_per_pixel(vs->ds));
670
        row += ds_get_linesize(vs->ds);
671
    }
672
    return 1;
673
}
674

    
675
int vnc_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
676
{
677
    int n = 0;
678

    
679
    switch(vs->vnc_encoding) {
680
        case VNC_ENCODING_ZLIB:
681
            n = vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
682
            break;
683
        case VNC_ENCODING_HEXTILE:
684
            vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
685
            n = vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
686
            break;
687
        case VNC_ENCODING_TIGHT:
688
            n = vnc_tight_send_framebuffer_update(vs, x, y, w, h);
689
            break;
690
        case VNC_ENCODING_TIGHT_PNG:
691
            n = vnc_tight_png_send_framebuffer_update(vs, x, y, w, h);
692
            break;
693
        default:
694
            vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
695
            n = vnc_raw_send_framebuffer_update(vs, x, y, w, h);
696
            break;
697
    }
698
    return n;
699
}
700

    
701
static void vnc_copy(VncState *vs, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
702
{
703
    /* send bitblit op to the vnc client */
704
    vnc_lock_output(vs);
705
    vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
706
    vnc_write_u8(vs, 0);
707
    vnc_write_u16(vs, 1); /* number of rects */
708
    vnc_framebuffer_update(vs, dst_x, dst_y, w, h, VNC_ENCODING_COPYRECT);
709
    vnc_write_u16(vs, src_x);
710
    vnc_write_u16(vs, src_y);
711
    vnc_unlock_output(vs);
712
    vnc_flush(vs);
713
}
714

    
715
static void vnc_dpy_copy(DisplayState *ds, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
716
{
717
    VncDisplay *vd = ds->opaque;
718
    VncState *vs, *vn;
719
    uint8_t *src_row;
720
    uint8_t *dst_row;
721
    int i,x,y,pitch,depth,inc,w_lim,s;
722
    int cmp_bytes;
723

    
724
    vnc_refresh_server_surface(vd);
725
    QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
726
        if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
727
            vs->force_update = 1;
728
            vnc_update_client_sync(vs, 1);
729
            /* vs might be free()ed here */
730
        }
731
    }
732

    
733
    /* do bitblit op on the local surface too */
734
    pitch = ds_get_linesize(vd->ds);
735
    depth = ds_get_bytes_per_pixel(vd->ds);
736
    src_row = vd->server->data + pitch * src_y + depth * src_x;
737
    dst_row = vd->server->data + pitch * dst_y + depth * dst_x;
738
    y = dst_y;
739
    inc = 1;
740
    if (dst_y > src_y) {
741
        /* copy backwards */
742
        src_row += pitch * (h-1);
743
        dst_row += pitch * (h-1);
744
        pitch = -pitch;
745
        y = dst_y + h - 1;
746
        inc = -1;
747
    }
748
    w_lim = w - (16 - (dst_x % 16));
749
    if (w_lim < 0)
750
        w_lim = w;
751
    else
752
        w_lim = w - (w_lim % 16);
753
    for (i = 0; i < h; i++) {
754
        for (x = 0; x <= w_lim;
755
                x += s, src_row += cmp_bytes, dst_row += cmp_bytes) {
756
            if (x == w_lim) {
757
                if ((s = w - w_lim) == 0)
758
                    break;
759
            } else if (!x) {
760
                s = (16 - (dst_x % 16));
761
                s = MIN(s, w_lim);
762
            } else {
763
                s = 16;
764
            }
765
            cmp_bytes = s * depth;
766
            if (memcmp(src_row, dst_row, cmp_bytes) == 0)
767
                continue;
768
            memmove(dst_row, src_row, cmp_bytes);
769
            QTAILQ_FOREACH(vs, &vd->clients, next) {
770
                if (!vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
771
                    vnc_set_bit(vs->dirty[y], ((x + dst_x) / 16));
772
                }
773
            }
774
        }
775
        src_row += pitch - w * depth;
776
        dst_row += pitch - w * depth;
777
        y += inc;
778
    }
779

    
780
    QTAILQ_FOREACH(vs, &vd->clients, next) {
781
        if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
782
            vnc_copy(vs, src_x, src_y, dst_x, dst_y, w, h);
783
        }
784
    }
785
}
786

    
787
static void vnc_mouse_set(int x, int y, int visible)
788
{
789
    /* can we ask the client(s) to move the pointer ??? */
790
}
791

    
792
static int vnc_cursor_define(VncState *vs)
793
{
794
    QEMUCursor *c = vs->vd->cursor;
795
    PixelFormat pf = qemu_default_pixelformat(32);
796
    int isize;
797

    
798
    if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
799
        vnc_write_u8(vs,  VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
800
        vnc_write_u8(vs,  0);  /*  padding     */
801
        vnc_write_u16(vs, 1);  /*  # of rects  */
802
        vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
803
                               VNC_ENCODING_RICH_CURSOR);
804
        isize = c->width * c->height * vs->clientds.pf.bytes_per_pixel;
805
        vnc_write_pixels_generic(vs, &pf, c->data, isize);
806
        vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
807
        return 0;
808
    }
809
    return -1;
810
}
811

    
812
static void vnc_dpy_cursor_define(QEMUCursor *c)
813
{
814
    VncDisplay *vd = vnc_display;
815
    VncState *vs;
816

    
817
    cursor_put(vd->cursor);
818
    qemu_free(vd->cursor_mask);
819

    
820
    vd->cursor = c;
821
    cursor_get(vd->cursor);
822
    vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
823
    vd->cursor_mask = qemu_mallocz(vd->cursor_msize);
824
    cursor_get_mono_mask(c, 0, vd->cursor_mask);
825

    
826
    QTAILQ_FOREACH(vs, &vd->clients, next) {
827
        vnc_cursor_define(vs);
828
    }
829
}
830

    
831
static int find_and_clear_dirty_height(struct VncState *vs,
832
                                       int y, int last_x, int x)
833
{
834
    int h;
835
    VncDisplay *vd = vs->vd;
836

    
837
    for (h = 1; h < (vd->server->height - y); h++) {
838
        int tmp_x;
839
        if (!vnc_get_bit(vs->dirty[y + h], last_x))
840
            break;
841
        for (tmp_x = last_x; tmp_x < x; tmp_x++)
842
            vnc_clear_bit(vs->dirty[y + h], tmp_x);
843
    }
844

    
845
    return h;
846
}
847

    
848
#ifdef CONFIG_VNC_THREAD
849
static int vnc_update_client_sync(VncState *vs, int has_dirty)
850
{
851
    int ret = vnc_update_client(vs, has_dirty);
852
    vnc_jobs_join(vs);
853
    return ret;
854
}
855
#else
856
static int vnc_update_client_sync(VncState *vs, int has_dirty)
857
{
858
    return vnc_update_client(vs, has_dirty);
859
}
860
#endif
861

    
862
static int vnc_update_client(VncState *vs, int has_dirty)
863
{
864
    if (vs->need_update && vs->csock != -1) {
865
        VncDisplay *vd = vs->vd;
866
        VncJob *job;
867
        int y;
868
        int width, height;
869
        int n = 0;
870

    
871

    
872
        if (vs->output.offset && !vs->audio_cap && !vs->force_update)
873
            /* kernel send buffers are full -> drop frames to throttle */
874
            return 0;
875

    
876
        if (!has_dirty && !vs->audio_cap && !vs->force_update)
877
            return 0;
878

    
879
        /*
880
         * Send screen updates to the vnc client using the server
881
         * surface and server dirty map.  guest surface updates
882
         * happening in parallel don't disturb us, the next pass will
883
         * send them to the client.
884
         */
885
        job = vnc_job_new(vs);
886

    
887
        width = MIN(vd->server->width, vs->client_width);
888
        height = MIN(vd->server->height, vs->client_height);
889

    
890
        for (y = 0; y < height; y++) {
891
            int x;
892
            int last_x = -1;
893
            for (x = 0; x < width / 16; x++) {
894
                if (vnc_get_bit(vs->dirty[y], x)) {
895
                    if (last_x == -1) {
896
                        last_x = x;
897
                    }
898
                    vnc_clear_bit(vs->dirty[y], x);
899
                } else {
900
                    if (last_x != -1) {
901
                        int h = find_and_clear_dirty_height(vs, y, last_x, x);
902

    
903
                        n += vnc_job_add_rect(job, last_x * 16, y,
904
                                              (x - last_x) * 16, h);
905
                    }
906
                    last_x = -1;
907
                }
908
            }
909
            if (last_x != -1) {
910
                int h = find_and_clear_dirty_height(vs, y, last_x, x);
911
                n += vnc_job_add_rect(job, last_x * 16, y,
912
                                      (x - last_x) * 16, h);
913
            }
914
        }
915

    
916
        vnc_job_push(job);
917
        vs->force_update = 0;
918
        return n;
919
    }
920

    
921
    if (vs->csock == -1)
922
        vnc_disconnect_finish(vs);
923

    
924
    return 0;
925
}
926

    
927
/* audio */
928
static void audio_capture_notify(void *opaque, audcnotification_e cmd)
929
{
930
    VncState *vs = opaque;
931

    
932
    switch (cmd) {
933
    case AUD_CNOTIFY_DISABLE:
934
        vnc_lock_output(vs);
935
        vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
936
        vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
937
        vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
938
        vnc_unlock_output(vs);
939
        vnc_flush(vs);
940
        break;
941

    
942
    case AUD_CNOTIFY_ENABLE:
943
        vnc_lock_output(vs);
944
        vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
945
        vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
946
        vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
947
        vnc_unlock_output(vs);
948
        vnc_flush(vs);
949
        break;
950
    }
951
}
952

    
953
static void audio_capture_destroy(void *opaque)
954
{
955
}
956

    
957
static void audio_capture(void *opaque, void *buf, int size)
958
{
959
    VncState *vs = opaque;
960

    
961
    vnc_lock_output(vs);
962
    vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
963
    vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
964
    vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
965
    vnc_write_u32(vs, size);
966
    vnc_write(vs, buf, size);
967
    vnc_unlock_output(vs);
968
    vnc_flush(vs);
969
}
970

    
971
static void audio_add(VncState *vs)
972
{
973
    struct audio_capture_ops ops;
974

    
975
    if (vs->audio_cap) {
976
        monitor_printf(default_mon, "audio already running\n");
977
        return;
978
    }
979

    
980
    ops.notify = audio_capture_notify;
981
    ops.destroy = audio_capture_destroy;
982
    ops.capture = audio_capture;
983

    
984
    vs->audio_cap = AUD_add_capture(&vs->as, &ops, vs);
985
    if (!vs->audio_cap) {
986
        monitor_printf(default_mon, "Failed to add audio capture\n");
987
    }
988
}
989

    
990
static void audio_del(VncState *vs)
991
{
992
    if (vs->audio_cap) {
993
        AUD_del_capture(vs->audio_cap, vs);
994
        vs->audio_cap = NULL;
995
    }
996
}
997

    
998
static void vnc_disconnect_start(VncState *vs)
999
{
1000
    if (vs->csock == -1)
1001
        return;
1002
    qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
1003
    closesocket(vs->csock);
1004
    vs->csock = -1;
1005
}
1006

    
1007
static void vnc_disconnect_finish(VncState *vs)
1008
{
1009
    vnc_jobs_join(vs); /* Wait encoding jobs */
1010

    
1011
    vnc_lock_output(vs);
1012
    vnc_qmp_event(vs, QEVENT_VNC_DISCONNECTED);
1013

    
1014
    buffer_free(&vs->input);
1015
    buffer_free(&vs->output);
1016

    
1017
    qobject_decref(vs->info);
1018

    
1019
    vnc_zlib_clear(vs);
1020
    vnc_tight_clear(vs);
1021

    
1022
#ifdef CONFIG_VNC_TLS
1023
    vnc_tls_client_cleanup(vs);
1024
#endif /* CONFIG_VNC_TLS */
1025
#ifdef CONFIG_VNC_SASL
1026
    vnc_sasl_client_cleanup(vs);
1027
#endif /* CONFIG_VNC_SASL */
1028
    audio_del(vs);
1029

    
1030
    QTAILQ_REMOVE(&vs->vd->clients, vs, next);
1031

    
1032
    if (QTAILQ_EMPTY(&vs->vd->clients)) {
1033
        dcl->idle = 1;
1034
    }
1035

    
1036
    qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
1037
    vnc_remove_timer(vs->vd);
1038
    if (vs->vd->lock_key_sync)
1039
        qemu_remove_led_event_handler(vs->led);
1040
    vnc_unlock_output(vs);
1041

    
1042
#ifdef CONFIG_VNC_THREAD
1043
    qemu_mutex_destroy(&vs->output_mutex);
1044
#endif
1045
    qemu_free(vs);
1046
}
1047

    
1048
int vnc_client_io_error(VncState *vs, int ret, int last_errno)
1049
{
1050
    if (ret == 0 || ret == -1) {
1051
        if (ret == -1) {
1052
            switch (last_errno) {
1053
                case EINTR:
1054
                case EAGAIN:
1055
#ifdef _WIN32
1056
                case WSAEWOULDBLOCK:
1057
#endif
1058
                    return 0;
1059
                default:
1060
                    break;
1061
            }
1062
        }
1063

    
1064
        VNC_DEBUG("Closing down client sock: ret %d, errno %d\n",
1065
                  ret, ret < 0 ? last_errno : 0);
1066
        vnc_disconnect_start(vs);
1067

    
1068
        return 0;
1069
    }
1070
    return ret;
1071
}
1072

    
1073

    
1074
void vnc_client_error(VncState *vs)
1075
{
1076
    VNC_DEBUG("Closing down client sock: protocol error\n");
1077
    vnc_disconnect_start(vs);
1078
}
1079

    
1080

    
1081
/*
1082
 * Called to write a chunk of data to the client socket. The data may
1083
 * be the raw data, or may have already been encoded by SASL.
1084
 * The data will be written either straight onto the socket, or
1085
 * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1086
 *
1087
 * NB, it is theoretically possible to have 2 layers of encryption,
1088
 * both SASL, and this TLS layer. It is highly unlikely in practice
1089
 * though, since SASL encryption will typically be a no-op if TLS
1090
 * is active
1091
 *
1092
 * Returns the number of bytes written, which may be less than
1093
 * the requested 'datalen' if the socket would block. Returns
1094
 * -1 on error, and disconnects the client socket.
1095
 */
1096
long vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
1097
{
1098
    long ret;
1099
#ifdef CONFIG_VNC_TLS
1100
    if (vs->tls.session) {
1101
        ret = gnutls_write(vs->tls.session, data, datalen);
1102
        if (ret < 0) {
1103
            if (ret == GNUTLS_E_AGAIN)
1104
                errno = EAGAIN;
1105
            else
1106
                errno = EIO;
1107
            ret = -1;
1108
        }
1109
    } else
1110
#endif /* CONFIG_VNC_TLS */
1111
        ret = send(vs->csock, (const void *)data, datalen, 0);
1112
    VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
1113
    return vnc_client_io_error(vs, ret, socket_error());
1114
}
1115

    
1116

    
1117
/*
1118
 * Called to write buffered data to the client socket, when not
1119
 * using any SASL SSF encryption layers. Will write as much data
1120
 * as possible without blocking. If all buffered data is written,
1121
 * will switch the FD poll() handler back to read monitoring.
1122
 *
1123
 * Returns the number of bytes written, which may be less than
1124
 * the buffered output data if the socket would block. Returns
1125
 * -1 on error, and disconnects the client socket.
1126
 */
1127
static long vnc_client_write_plain(VncState *vs)
1128
{
1129
    long ret;
1130

    
1131
#ifdef CONFIG_VNC_SASL
1132
    VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
1133
              vs->output.buffer, vs->output.capacity, vs->output.offset,
1134
              vs->sasl.waitWriteSSF);
1135

    
1136
    if (vs->sasl.conn &&
1137
        vs->sasl.runSSF &&
1138
        vs->sasl.waitWriteSSF) {
1139
        ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
1140
        if (ret)
1141
            vs->sasl.waitWriteSSF -= ret;
1142
    } else
1143
#endif /* CONFIG_VNC_SASL */
1144
        ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
1145
    if (!ret)
1146
        return 0;
1147

    
1148
    memmove(vs->output.buffer, vs->output.buffer + ret, (vs->output.offset - ret));
1149
    vs->output.offset -= ret;
1150

    
1151
    if (vs->output.offset == 0) {
1152
        qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
1153
    }
1154

    
1155
    return ret;
1156
}
1157

    
1158

    
1159
/*
1160
 * First function called whenever there is data to be written to
1161
 * the client socket. Will delegate actual work according to whether
1162
 * SASL SSF layers are enabled (thus requiring encryption calls)
1163
 */
1164
static void vnc_client_write_locked(void *opaque)
1165
{
1166
    VncState *vs = opaque;
1167

    
1168
#ifdef CONFIG_VNC_SASL
1169
    if (vs->sasl.conn &&
1170
        vs->sasl.runSSF &&
1171
        !vs->sasl.waitWriteSSF) {
1172
        vnc_client_write_sasl(vs);
1173
    } else
1174
#endif /* CONFIG_VNC_SASL */
1175
        vnc_client_write_plain(vs);
1176
}
1177

    
1178
void vnc_client_write(void *opaque)
1179
{
1180
    VncState *vs = opaque;
1181

    
1182
    vnc_lock_output(vs);
1183
    if (vs->output.offset) {
1184
        vnc_client_write_locked(opaque);
1185
    } else {
1186
        qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
1187
    }
1188
    vnc_unlock_output(vs);
1189
}
1190

    
1191
void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
1192
{
1193
    vs->read_handler = func;
1194
    vs->read_handler_expect = expecting;
1195
}
1196

    
1197

    
1198
/*
1199
 * Called to read a chunk of data from the client socket. The data may
1200
 * be the raw data, or may need to be further decoded by SASL.
1201
 * The data will be read either straight from to the socket, or
1202
 * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1203
 *
1204
 * NB, it is theoretically possible to have 2 layers of encryption,
1205
 * both SASL, and this TLS layer. It is highly unlikely in practice
1206
 * though, since SASL encryption will typically be a no-op if TLS
1207
 * is active
1208
 *
1209
 * Returns the number of bytes read, which may be less than
1210
 * the requested 'datalen' if the socket would block. Returns
1211
 * -1 on error, and disconnects the client socket.
1212
 */
1213
long vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
1214
{
1215
    long ret;
1216
#ifdef CONFIG_VNC_TLS
1217
    if (vs->tls.session) {
1218
        ret = gnutls_read(vs->tls.session, data, datalen);
1219
        if (ret < 0) {
1220
            if (ret == GNUTLS_E_AGAIN)
1221
                errno = EAGAIN;
1222
            else
1223
                errno = EIO;
1224
            ret = -1;
1225
        }
1226
    } else
1227
#endif /* CONFIG_VNC_TLS */
1228
        ret = recv(vs->csock, (void *)data, datalen, 0);
1229
    VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
1230
    return vnc_client_io_error(vs, ret, socket_error());
1231
}
1232

    
1233

    
1234
/*
1235
 * Called to read data from the client socket to the input buffer,
1236
 * when not using any SASL SSF encryption layers. Will read as much
1237
 * data as possible without blocking.
1238
 *
1239
 * Returns the number of bytes read. Returns -1 on error, and
1240
 * disconnects the client socket.
1241
 */
1242
static long vnc_client_read_plain(VncState *vs)
1243
{
1244
    int ret;
1245
    VNC_DEBUG("Read plain %p size %zd offset %zd\n",
1246
              vs->input.buffer, vs->input.capacity, vs->input.offset);
1247
    buffer_reserve(&vs->input, 4096);
1248
    ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
1249
    if (!ret)
1250
        return 0;
1251
    vs->input.offset += ret;
1252
    return ret;
1253
}
1254

    
1255

    
1256
/*
1257
 * First function called whenever there is more data to be read from
1258
 * the client socket. Will delegate actual work according to whether
1259
 * SASL SSF layers are enabled (thus requiring decryption calls)
1260
 */
1261
void vnc_client_read(void *opaque)
1262
{
1263
    VncState *vs = opaque;
1264
    long ret;
1265

    
1266
#ifdef CONFIG_VNC_SASL
1267
    if (vs->sasl.conn && vs->sasl.runSSF)
1268
        ret = vnc_client_read_sasl(vs);
1269
    else
1270
#endif /* CONFIG_VNC_SASL */
1271
        ret = vnc_client_read_plain(vs);
1272
    if (!ret) {
1273
        if (vs->csock == -1)
1274
            vnc_disconnect_finish(vs);
1275
        return;
1276
    }
1277

    
1278
    while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
1279
        size_t len = vs->read_handler_expect;
1280
        int ret;
1281

    
1282
        ret = vs->read_handler(vs, vs->input.buffer, len);
1283
        if (vs->csock == -1) {
1284
            vnc_disconnect_finish(vs);
1285
            return;
1286
        }
1287

    
1288
        if (!ret) {
1289
            memmove(vs->input.buffer, vs->input.buffer + len, (vs->input.offset - len));
1290
            vs->input.offset -= len;
1291
        } else {
1292
            vs->read_handler_expect = ret;
1293
        }
1294
    }
1295
}
1296

    
1297
void vnc_write(VncState *vs, const void *data, size_t len)
1298
{
1299
    buffer_reserve(&vs->output, len);
1300

    
1301
    if (vs->csock != -1 && buffer_empty(&vs->output)) {
1302
        qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
1303
    }
1304

    
1305
    buffer_append(&vs->output, data, len);
1306
}
1307

    
1308
void vnc_write_s32(VncState *vs, int32_t value)
1309
{
1310
    vnc_write_u32(vs, *(uint32_t *)&value);
1311
}
1312

    
1313
void vnc_write_u32(VncState *vs, uint32_t value)
1314
{
1315
    uint8_t buf[4];
1316

    
1317
    buf[0] = (value >> 24) & 0xFF;
1318
    buf[1] = (value >> 16) & 0xFF;
1319
    buf[2] = (value >>  8) & 0xFF;
1320
    buf[3] = value & 0xFF;
1321

    
1322
    vnc_write(vs, buf, 4);
1323
}
1324

    
1325
void vnc_write_u16(VncState *vs, uint16_t value)
1326
{
1327
    uint8_t buf[2];
1328

    
1329
    buf[0] = (value >> 8) & 0xFF;
1330
    buf[1] = value & 0xFF;
1331

    
1332
    vnc_write(vs, buf, 2);
1333
}
1334

    
1335
void vnc_write_u8(VncState *vs, uint8_t value)
1336
{
1337
    vnc_write(vs, (char *)&value, 1);
1338
}
1339

    
1340
void vnc_flush(VncState *vs)
1341
{
1342
    vnc_lock_output(vs);
1343
    if (vs->csock != -1 && vs->output.offset) {
1344
        vnc_client_write_locked(vs);
1345
    }
1346
    vnc_unlock_output(vs);
1347
}
1348

    
1349
uint8_t read_u8(uint8_t *data, size_t offset)
1350
{
1351
    return data[offset];
1352
}
1353

    
1354
uint16_t read_u16(uint8_t *data, size_t offset)
1355
{
1356
    return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1357
}
1358

    
1359
int32_t read_s32(uint8_t *data, size_t offset)
1360
{
1361
    return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
1362
                     (data[offset + 2] << 8) | data[offset + 3]);
1363
}
1364

    
1365
uint32_t read_u32(uint8_t *data, size_t offset)
1366
{
1367
    return ((data[offset] << 24) | (data[offset + 1] << 16) |
1368
            (data[offset + 2] << 8) | data[offset + 3]);
1369
}
1370

    
1371
static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
1372
{
1373
}
1374

    
1375
static void check_pointer_type_change(Notifier *notifier)
1376
{
1377
    VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
1378
    int absolute = kbd_mouse_is_absolute();
1379

    
1380
    if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1381
        vnc_lock_output(vs);
1382
        vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1383
        vnc_write_u8(vs, 0);
1384
        vnc_write_u16(vs, 1);
1385
        vnc_framebuffer_update(vs, absolute, 0,
1386
                               ds_get_width(vs->ds), ds_get_height(vs->ds),
1387
                               VNC_ENCODING_POINTER_TYPE_CHANGE);
1388
        vnc_unlock_output(vs);
1389
        vnc_flush(vs);
1390
    }
1391
    vs->absolute = absolute;
1392
}
1393

    
1394
static void pointer_event(VncState *vs, int button_mask, int x, int y)
1395
{
1396
    int buttons = 0;
1397
    int dz = 0;
1398

    
1399
    if (button_mask & 0x01)
1400
        buttons |= MOUSE_EVENT_LBUTTON;
1401
    if (button_mask & 0x02)
1402
        buttons |= MOUSE_EVENT_MBUTTON;
1403
    if (button_mask & 0x04)
1404
        buttons |= MOUSE_EVENT_RBUTTON;
1405
    if (button_mask & 0x08)
1406
        dz = -1;
1407
    if (button_mask & 0x10)
1408
        dz = 1;
1409

    
1410
    if (vs->absolute) {
1411
        kbd_mouse_event(ds_get_width(vs->ds) > 1 ?
1412
                          x * 0x7FFF / (ds_get_width(vs->ds) - 1) : 0x4000,
1413
                        ds_get_height(vs->ds) > 1 ?
1414
                          y * 0x7FFF / (ds_get_height(vs->ds) - 1) : 0x4000,
1415
                        dz, buttons);
1416
    } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
1417
        x -= 0x7FFF;
1418
        y -= 0x7FFF;
1419

    
1420
        kbd_mouse_event(x, y, dz, buttons);
1421
    } else {
1422
        if (vs->last_x != -1)
1423
            kbd_mouse_event(x - vs->last_x,
1424
                            y - vs->last_y,
1425
                            dz, buttons);
1426
        vs->last_x = x;
1427
        vs->last_y = y;
1428
    }
1429
}
1430

    
1431
static void reset_keys(VncState *vs)
1432
{
1433
    int i;
1434
    for(i = 0; i < 256; i++) {
1435
        if (vs->modifiers_state[i]) {
1436
            if (i & SCANCODE_GREY)
1437
                kbd_put_keycode(SCANCODE_EMUL0);
1438
            kbd_put_keycode(i | SCANCODE_UP);
1439
            vs->modifiers_state[i] = 0;
1440
        }
1441
    }
1442
}
1443

    
1444
static void press_key(VncState *vs, int keysym)
1445
{
1446
    int keycode = keysym2scancode(vs->vd->kbd_layout, keysym) & SCANCODE_KEYMASK;
1447
    if (keycode & SCANCODE_GREY)
1448
        kbd_put_keycode(SCANCODE_EMUL0);
1449
    kbd_put_keycode(keycode & SCANCODE_KEYCODEMASK);
1450
    if (keycode & SCANCODE_GREY)
1451
        kbd_put_keycode(SCANCODE_EMUL0);
1452
    kbd_put_keycode(keycode | SCANCODE_UP);
1453
}
1454

    
1455
static void kbd_leds(void *opaque, int ledstate)
1456
{
1457
    VncState *vs = opaque;
1458
    int caps, num;
1459

    
1460
    caps = ledstate & QEMU_CAPS_LOCK_LED ? 1 : 0;
1461
    num  = ledstate & QEMU_NUM_LOCK_LED  ? 1 : 0;
1462

    
1463
    if (vs->modifiers_state[0x3a] != caps) {
1464
        vs->modifiers_state[0x3a] = caps;
1465
    }
1466
    if (vs->modifiers_state[0x45] != num) {
1467
        vs->modifiers_state[0x45] = num;
1468
    }
1469
}
1470

    
1471
static void do_key_event(VncState *vs, int down, int keycode, int sym)
1472
{
1473
    /* QEMU console switch */
1474
    switch(keycode) {
1475
    case 0x2a:                          /* Left Shift */
1476
    case 0x36:                          /* Right Shift */
1477
    case 0x1d:                          /* Left CTRL */
1478
    case 0x9d:                          /* Right CTRL */
1479
    case 0x38:                          /* Left ALT */
1480
    case 0xb8:                          /* Right ALT */
1481
        if (down)
1482
            vs->modifiers_state[keycode] = 1;
1483
        else
1484
            vs->modifiers_state[keycode] = 0;
1485
        break;
1486
    case 0x02 ... 0x0a: /* '1' to '9' keys */
1487
        if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
1488
            /* Reset the modifiers sent to the current console */
1489
            reset_keys(vs);
1490
            console_select(keycode - 0x02);
1491
            return;
1492
        }
1493
        break;
1494
    case 0x3a:                        /* CapsLock */
1495
    case 0x45:                        /* NumLock */
1496
        if (down)
1497
            vs->modifiers_state[keycode] ^= 1;
1498
        break;
1499
    }
1500

    
1501
    if (vs->vd->lock_key_sync &&
1502
        keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
1503
        /* If the numlock state needs to change then simulate an additional
1504
           keypress before sending this one.  This will happen if the user
1505
           toggles numlock away from the VNC window.
1506
        */
1507
        if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1508
            if (!vs->modifiers_state[0x45]) {
1509
                vs->modifiers_state[0x45] = 1;
1510
                press_key(vs, 0xff7f);
1511
            }
1512
        } else {
1513
            if (vs->modifiers_state[0x45]) {
1514
                vs->modifiers_state[0x45] = 0;
1515
                press_key(vs, 0xff7f);
1516
            }
1517
        }
1518
    }
1519

    
1520
    if (vs->vd->lock_key_sync &&
1521
        ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
1522
        /* If the capslock state needs to change then simulate an additional
1523
           keypress before sending this one.  This will happen if the user
1524
           toggles capslock away from the VNC window.
1525
        */
1526
        int uppercase = !!(sym >= 'A' && sym <= 'Z');
1527
        int shift = !!(vs->modifiers_state[0x2a] | vs->modifiers_state[0x36]);
1528
        int capslock = !!(vs->modifiers_state[0x3a]);
1529
        if (capslock) {
1530
            if (uppercase == shift) {
1531
                vs->modifiers_state[0x3a] = 0;
1532
                press_key(vs, 0xffe5);
1533
            }
1534
        } else {
1535
            if (uppercase != shift) {
1536
                vs->modifiers_state[0x3a] = 1;
1537
                press_key(vs, 0xffe5);
1538
            }
1539
        }
1540
    }
1541

    
1542
    if (is_graphic_console()) {
1543
        if (keycode & SCANCODE_GREY)
1544
            kbd_put_keycode(SCANCODE_EMUL0);
1545
        if (down)
1546
            kbd_put_keycode(keycode & SCANCODE_KEYCODEMASK);
1547
        else
1548
            kbd_put_keycode(keycode | SCANCODE_UP);
1549
    } else {
1550
        /* QEMU console emulation */
1551
        if (down) {
1552
            int numlock = vs->modifiers_state[0x45];
1553
            switch (keycode) {
1554
            case 0x2a:                          /* Left Shift */
1555
            case 0x36:                          /* Right Shift */
1556
            case 0x1d:                          /* Left CTRL */
1557
            case 0x9d:                          /* Right CTRL */
1558
            case 0x38:                          /* Left ALT */
1559
            case 0xb8:                          /* Right ALT */
1560
                break;
1561
            case 0xc8:
1562
                kbd_put_keysym(QEMU_KEY_UP);
1563
                break;
1564
            case 0xd0:
1565
                kbd_put_keysym(QEMU_KEY_DOWN);
1566
                break;
1567
            case 0xcb:
1568
                kbd_put_keysym(QEMU_KEY_LEFT);
1569
                break;
1570
            case 0xcd:
1571
                kbd_put_keysym(QEMU_KEY_RIGHT);
1572
                break;
1573
            case 0xd3:
1574
                kbd_put_keysym(QEMU_KEY_DELETE);
1575
                break;
1576
            case 0xc7:
1577
                kbd_put_keysym(QEMU_KEY_HOME);
1578
                break;
1579
            case 0xcf:
1580
                kbd_put_keysym(QEMU_KEY_END);
1581
                break;
1582
            case 0xc9:
1583
                kbd_put_keysym(QEMU_KEY_PAGEUP);
1584
                break;
1585
            case 0xd1:
1586
                kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1587
                break;
1588

    
1589
            case 0x47:
1590
                kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
1591
                break;
1592
            case 0x48:
1593
                kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
1594
                break;
1595
            case 0x49:
1596
                kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
1597
                break;
1598
            case 0x4b:
1599
                kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
1600
                break;
1601
            case 0x4c:
1602
                kbd_put_keysym('5');
1603
                break;
1604
            case 0x4d:
1605
                kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
1606
                break;
1607
            case 0x4f:
1608
                kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
1609
                break;
1610
            case 0x50:
1611
                kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
1612
                break;
1613
            case 0x51:
1614
                kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
1615
                break;
1616
            case 0x52:
1617
                kbd_put_keysym('0');
1618
                break;
1619
            case 0x53:
1620
                kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
1621
                break;
1622

    
1623
            case 0xb5:
1624
                kbd_put_keysym('/');
1625
                break;
1626
            case 0x37:
1627
                kbd_put_keysym('*');
1628
                break;
1629
            case 0x4a:
1630
                kbd_put_keysym('-');
1631
                break;
1632
            case 0x4e:
1633
                kbd_put_keysym('+');
1634
                break;
1635
            case 0x9c:
1636
                kbd_put_keysym('\n');
1637
                break;
1638

    
1639
            default:
1640
                kbd_put_keysym(sym);
1641
                break;
1642
            }
1643
        }
1644
    }
1645
}
1646

    
1647
static void key_event(VncState *vs, int down, uint32_t sym)
1648
{
1649
    int keycode;
1650
    int lsym = sym;
1651

    
1652
    if (lsym >= 'A' && lsym <= 'Z' && is_graphic_console()) {
1653
        lsym = lsym - 'A' + 'a';
1654
    }
1655

    
1656
    keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF) & SCANCODE_KEYMASK;
1657
    do_key_event(vs, down, keycode, sym);
1658
}
1659

    
1660
static void ext_key_event(VncState *vs, int down,
1661
                          uint32_t sym, uint16_t keycode)
1662
{
1663
    /* if the user specifies a keyboard layout, always use it */
1664
    if (keyboard_layout)
1665
        key_event(vs, down, sym);
1666
    else
1667
        do_key_event(vs, down, keycode, sym);
1668
}
1669

    
1670
static void framebuffer_update_request(VncState *vs, int incremental,
1671
                                       int x_position, int y_position,
1672
                                       int w, int h)
1673
{
1674
    if (y_position > ds_get_height(vs->ds))
1675
        y_position = ds_get_height(vs->ds);
1676
    if (y_position + h >= ds_get_height(vs->ds))
1677
        h = ds_get_height(vs->ds) - y_position;
1678

    
1679
    int i;
1680
    vs->need_update = 1;
1681
    if (!incremental) {
1682
        vs->force_update = 1;
1683
        for (i = 0; i < h; i++) {
1684
            vnc_set_bits(vs->dirty[y_position + i],
1685
                         (ds_get_width(vs->ds) / 16), VNC_DIRTY_WORDS);
1686
        }
1687
    }
1688
}
1689

    
1690
static void send_ext_key_event_ack(VncState *vs)
1691
{
1692
    vnc_lock_output(vs);
1693
    vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1694
    vnc_write_u8(vs, 0);
1695
    vnc_write_u16(vs, 1);
1696
    vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1697
                           VNC_ENCODING_EXT_KEY_EVENT);
1698
    vnc_unlock_output(vs);
1699
    vnc_flush(vs);
1700
}
1701

    
1702
static void send_ext_audio_ack(VncState *vs)
1703
{
1704
    vnc_lock_output(vs);
1705
    vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1706
    vnc_write_u8(vs, 0);
1707
    vnc_write_u16(vs, 1);
1708
    vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1709
                           VNC_ENCODING_AUDIO);
1710
    vnc_unlock_output(vs);
1711
    vnc_flush(vs);
1712
}
1713

    
1714
static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
1715
{
1716
    int i;
1717
    unsigned int enc = 0;
1718

    
1719
    vs->features = 0;
1720
    vs->vnc_encoding = 0;
1721
    vs->tight.compression = 9;
1722
    vs->tight.quality = -1; /* Lossless by default */
1723
    vs->absolute = -1;
1724

    
1725
    /*
1726
     * Start from the end because the encodings are sent in order of preference.
1727
     * This way the prefered encoding (first encoding defined in the array)
1728
     * will be set at the end of the loop.
1729
     */
1730
    for (i = n_encodings - 1; i >= 0; i--) {
1731
        enc = encodings[i];
1732
        switch (enc) {
1733
        case VNC_ENCODING_RAW:
1734
            vs->vnc_encoding = enc;
1735
            break;
1736
        case VNC_ENCODING_COPYRECT:
1737
            vs->features |= VNC_FEATURE_COPYRECT_MASK;
1738
            break;
1739
        case VNC_ENCODING_HEXTILE:
1740
            vs->features |= VNC_FEATURE_HEXTILE_MASK;
1741
            vs->vnc_encoding = enc;
1742
            break;
1743
        case VNC_ENCODING_TIGHT:
1744
            vs->features |= VNC_FEATURE_TIGHT_MASK;
1745
            vs->vnc_encoding = enc;
1746
            break;
1747
        case VNC_ENCODING_TIGHT_PNG:
1748
            vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;
1749
            vs->vnc_encoding = enc;
1750
            break;
1751
        case VNC_ENCODING_ZLIB:
1752
            vs->features |= VNC_FEATURE_ZLIB_MASK;
1753
            vs->vnc_encoding = enc;
1754
            break;
1755
        case VNC_ENCODING_DESKTOPRESIZE:
1756
            vs->features |= VNC_FEATURE_RESIZE_MASK;
1757
            break;
1758
        case VNC_ENCODING_POINTER_TYPE_CHANGE:
1759
            vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
1760
            break;
1761
        case VNC_ENCODING_RICH_CURSOR:
1762
            vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
1763
            break;
1764
        case VNC_ENCODING_EXT_KEY_EVENT:
1765
            send_ext_key_event_ack(vs);
1766
            break;
1767
        case VNC_ENCODING_AUDIO:
1768
            send_ext_audio_ack(vs);
1769
            break;
1770
        case VNC_ENCODING_WMVi:
1771
            vs->features |= VNC_FEATURE_WMVI_MASK;
1772
            break;
1773
        case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
1774
            vs->tight.compression = (enc & 0x0F);
1775
            break;
1776
        case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
1777
            vs->tight.quality = (enc & 0x0F);
1778
            break;
1779
        default:
1780
            VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
1781
            break;
1782
        }
1783
    }
1784
    vnc_desktop_resize(vs);
1785
    check_pointer_type_change(&vs->mouse_mode_notifier);
1786
}
1787

    
1788
static void set_pixel_conversion(VncState *vs)
1789
{
1790
    if ((vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) ==
1791
        (vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG) && 
1792
        !memcmp(&(vs->clientds.pf), &(vs->ds->surface->pf), sizeof(PixelFormat))) {
1793
        vs->write_pixels = vnc_write_pixels_copy;
1794
        vnc_hextile_set_pixel_conversion(vs, 0);
1795
    } else {
1796
        vs->write_pixels = vnc_write_pixels_generic;
1797
        vnc_hextile_set_pixel_conversion(vs, 1);
1798
    }
1799
}
1800

    
1801
static void set_pixel_format(VncState *vs,
1802
                             int bits_per_pixel, int depth,
1803
                             int big_endian_flag, int true_color_flag,
1804
                             int red_max, int green_max, int blue_max,
1805
                             int red_shift, int green_shift, int blue_shift)
1806
{
1807
    if (!true_color_flag) {
1808
        vnc_client_error(vs);
1809
        return;
1810
    }
1811

    
1812
    vs->clientds = *(vs->vd->guest.ds);
1813
    vs->clientds.pf.rmax = red_max;
1814
    count_bits(vs->clientds.pf.rbits, red_max);
1815
    vs->clientds.pf.rshift = red_shift;
1816
    vs->clientds.pf.rmask = red_max << red_shift;
1817
    vs->clientds.pf.gmax = green_max;
1818
    count_bits(vs->clientds.pf.gbits, green_max);
1819
    vs->clientds.pf.gshift = green_shift;
1820
    vs->clientds.pf.gmask = green_max << green_shift;
1821
    vs->clientds.pf.bmax = blue_max;
1822
    count_bits(vs->clientds.pf.bbits, blue_max);
1823
    vs->clientds.pf.bshift = blue_shift;
1824
    vs->clientds.pf.bmask = blue_max << blue_shift;
1825
    vs->clientds.pf.bits_per_pixel = bits_per_pixel;
1826
    vs->clientds.pf.bytes_per_pixel = bits_per_pixel / 8;
1827
    vs->clientds.pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
1828
    vs->clientds.flags = big_endian_flag ? QEMU_BIG_ENDIAN_FLAG : 0x00;
1829

    
1830
    set_pixel_conversion(vs);
1831

    
1832
    vga_hw_invalidate();
1833
    vga_hw_update();
1834
}
1835

    
1836
static void pixel_format_message (VncState *vs) {
1837
    char pad[3] = { 0, 0, 0 };
1838

    
1839
    vnc_write_u8(vs, vs->ds->surface->pf.bits_per_pixel); /* bits-per-pixel */
1840
    vnc_write_u8(vs, vs->ds->surface->pf.depth); /* depth */
1841

    
1842
#ifdef HOST_WORDS_BIGENDIAN
1843
    vnc_write_u8(vs, 1);             /* big-endian-flag */
1844
#else
1845
    vnc_write_u8(vs, 0);             /* big-endian-flag */
1846
#endif
1847
    vnc_write_u8(vs, 1);             /* true-color-flag */
1848
    vnc_write_u16(vs, vs->ds->surface->pf.rmax);     /* red-max */
1849
    vnc_write_u16(vs, vs->ds->surface->pf.gmax);     /* green-max */
1850
    vnc_write_u16(vs, vs->ds->surface->pf.bmax);     /* blue-max */
1851
    vnc_write_u8(vs, vs->ds->surface->pf.rshift);    /* red-shift */
1852
    vnc_write_u8(vs, vs->ds->surface->pf.gshift);    /* green-shift */
1853
    vnc_write_u8(vs, vs->ds->surface->pf.bshift);    /* blue-shift */
1854

    
1855
    vnc_hextile_set_pixel_conversion(vs, 0);
1856

    
1857
    vs->clientds = *(vs->ds->surface);
1858
    vs->clientds.flags &= ~QEMU_ALLOCATED_FLAG;
1859
    vs->write_pixels = vnc_write_pixels_copy;
1860

    
1861
    vnc_write(vs, pad, 3);           /* padding */
1862
}
1863

    
1864
static void vnc_dpy_setdata(DisplayState *ds)
1865
{
1866
    /* We don't have to do anything */
1867
}
1868

    
1869
static void vnc_colordepth(VncState *vs)
1870
{
1871
    if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
1872
        /* Sending a WMVi message to notify the client*/
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); /* number of rects */
1877
        vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), 
1878
                               ds_get_height(vs->ds), VNC_ENCODING_WMVi);
1879
        pixel_format_message(vs);
1880
        vnc_unlock_output(vs);
1881
        vnc_flush(vs);
1882
    } else {
1883
        set_pixel_conversion(vs);
1884
    }
1885
}
1886

    
1887
static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
1888
{
1889
    int i;
1890
    uint16_t limit;
1891
    VncDisplay *vd = vs->vd;
1892

    
1893
    if (data[0] > 3) {
1894
        vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
1895
        if (!qemu_timer_expired(vd->timer, qemu_get_clock(rt_clock) + vd->timer_interval))
1896
            qemu_mod_timer(vd->timer, qemu_get_clock(rt_clock) + vd->timer_interval);
1897
    }
1898

    
1899
    switch (data[0]) {
1900
    case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
1901
        if (len == 1)
1902
            return 20;
1903

    
1904
        set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
1905
                         read_u8(data, 6), read_u8(data, 7),
1906
                         read_u16(data, 8), read_u16(data, 10),
1907
                         read_u16(data, 12), read_u8(data, 14),
1908
                         read_u8(data, 15), read_u8(data, 16));
1909
        break;
1910
    case VNC_MSG_CLIENT_SET_ENCODINGS:
1911
        if (len == 1)
1912
            return 4;
1913

    
1914
        if (len == 4) {
1915
            limit = read_u16(data, 2);
1916
            if (limit > 0)
1917
                return 4 + (limit * 4);
1918
        } else
1919
            limit = read_u16(data, 2);
1920

    
1921
        for (i = 0; i < limit; i++) {
1922
            int32_t val = read_s32(data, 4 + (i * 4));
1923
            memcpy(data + 4 + (i * 4), &val, sizeof(val));
1924
        }
1925

    
1926
        set_encodings(vs, (int32_t *)(data + 4), limit);
1927
        break;
1928
    case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
1929
        if (len == 1)
1930
            return 10;
1931

    
1932
        framebuffer_update_request(vs,
1933
                                   read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
1934
                                   read_u16(data, 6), read_u16(data, 8));
1935
        break;
1936
    case VNC_MSG_CLIENT_KEY_EVENT:
1937
        if (len == 1)
1938
            return 8;
1939

    
1940
        key_event(vs, read_u8(data, 1), read_u32(data, 4));
1941
        break;
1942
    case VNC_MSG_CLIENT_POINTER_EVENT:
1943
        if (len == 1)
1944
            return 6;
1945

    
1946
        pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
1947
        break;
1948
    case VNC_MSG_CLIENT_CUT_TEXT:
1949
        if (len == 1)
1950
            return 8;
1951

    
1952
        if (len == 8) {
1953
            uint32_t dlen = read_u32(data, 4);
1954
            if (dlen > 0)
1955
                return 8 + dlen;
1956
        }
1957

    
1958
        client_cut_text(vs, read_u32(data, 4), data + 8);
1959
        break;
1960
    case VNC_MSG_CLIENT_QEMU:
1961
        if (len == 1)
1962
            return 2;
1963

    
1964
        switch (read_u8(data, 1)) {
1965
        case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
1966
            if (len == 2)
1967
                return 12;
1968

    
1969
            ext_key_event(vs, read_u16(data, 2),
1970
                          read_u32(data, 4), read_u32(data, 8));
1971
            break;
1972
        case VNC_MSG_CLIENT_QEMU_AUDIO:
1973
            if (len == 2)
1974
                return 4;
1975

    
1976
            switch (read_u16 (data, 2)) {
1977
            case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
1978
                audio_add(vs);
1979
                break;
1980
            case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
1981
                audio_del(vs);
1982
                break;
1983
            case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
1984
                if (len == 4)
1985
                    return 10;
1986
                switch (read_u8(data, 4)) {
1987
                case 0: vs->as.fmt = AUD_FMT_U8; break;
1988
                case 1: vs->as.fmt = AUD_FMT_S8; break;
1989
                case 2: vs->as.fmt = AUD_FMT_U16; break;
1990
                case 3: vs->as.fmt = AUD_FMT_S16; break;
1991
                case 4: vs->as.fmt = AUD_FMT_U32; break;
1992
                case 5: vs->as.fmt = AUD_FMT_S32; break;
1993
                default:
1994
                    printf("Invalid audio format %d\n", read_u8(data, 4));
1995
                    vnc_client_error(vs);
1996
                    break;
1997
                }
1998
                vs->as.nchannels = read_u8(data, 5);
1999
                if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2000
                    printf("Invalid audio channel coount %d\n",
2001
                           read_u8(data, 5));
2002
                    vnc_client_error(vs);
2003
                    break;
2004
                }
2005
                vs->as.freq = read_u32(data, 6);
2006
                break;
2007
            default:
2008
                printf ("Invalid audio message %d\n", read_u8(data, 4));
2009
                vnc_client_error(vs);
2010
                break;
2011
            }
2012
            break;
2013

    
2014
        default:
2015
            printf("Msg: %d\n", read_u16(data, 0));
2016
            vnc_client_error(vs);
2017
            break;
2018
        }
2019
        break;
2020
    default:
2021
        printf("Msg: %d\n", data[0]);
2022
        vnc_client_error(vs);
2023
        break;
2024
    }
2025

    
2026
    vnc_read_when(vs, protocol_client_msg, 1);
2027
    return 0;
2028
}
2029

    
2030
static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
2031
{
2032
    char buf[1024];
2033
    int size;
2034

    
2035
    vs->client_width = ds_get_width(vs->ds);
2036
    vs->client_height = ds_get_height(vs->ds);
2037
    vnc_write_u16(vs, vs->client_width);
2038
    vnc_write_u16(vs, vs->client_height);
2039

    
2040
    pixel_format_message(vs);
2041

    
2042
    if (qemu_name)
2043
        size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
2044
    else
2045
        size = snprintf(buf, sizeof(buf), "QEMU");
2046

    
2047
    vnc_write_u32(vs, size);
2048
    vnc_write(vs, buf, size);
2049
    vnc_flush(vs);
2050

    
2051
    vnc_client_cache_auth(vs);
2052
    vnc_qmp_event(vs, QEVENT_VNC_INITIALIZED);
2053

    
2054
    vnc_read_when(vs, protocol_client_msg, 1);
2055

    
2056
    return 0;
2057
}
2058

    
2059
void start_client_init(VncState *vs)
2060
{
2061
    vnc_read_when(vs, protocol_client_init, 1);
2062
}
2063

    
2064
static void make_challenge(VncState *vs)
2065
{
2066
    int i;
2067

    
2068
    srand(time(NULL)+getpid()+getpid()*987654+rand());
2069

    
2070
    for (i = 0 ; i < sizeof(vs->challenge) ; i++)
2071
        vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
2072
}
2073

    
2074
static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
2075
{
2076
    unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2077
    int i, j, pwlen;
2078
    unsigned char key[8];
2079

    
2080
    if (!vs->vd->password || !vs->vd->password[0]) {
2081
        VNC_DEBUG("No password configured on server");
2082
        vnc_write_u32(vs, 1); /* Reject auth */
2083
        if (vs->minor >= 8) {
2084
            static const char err[] = "Authentication failed";
2085
            vnc_write_u32(vs, sizeof(err));
2086
            vnc_write(vs, err, sizeof(err));
2087
        }
2088
        vnc_flush(vs);
2089
        vnc_client_error(vs);
2090
        return 0;
2091
    }
2092

    
2093
    memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
2094

    
2095
    /* Calculate the expected challenge response */
2096
    pwlen = strlen(vs->vd->password);
2097
    for (i=0; i<sizeof(key); i++)
2098
        key[i] = i<pwlen ? vs->vd->password[i] : 0;
2099
    deskey(key, EN0);
2100
    for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
2101
        des(response+j, response+j);
2102

    
2103
    /* Compare expected vs actual challenge response */
2104
    if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
2105
        VNC_DEBUG("Client challenge reponse did not match\n");
2106
        vnc_write_u32(vs, 1); /* Reject auth */
2107
        if (vs->minor >= 8) {
2108
            static const char err[] = "Authentication failed";
2109
            vnc_write_u32(vs, sizeof(err));
2110
            vnc_write(vs, err, sizeof(err));
2111
        }
2112
        vnc_flush(vs);
2113
        vnc_client_error(vs);
2114
    } else {
2115
        VNC_DEBUG("Accepting VNC challenge response\n");
2116
        vnc_write_u32(vs, 0); /* Accept auth */
2117
        vnc_flush(vs);
2118

    
2119
        start_client_init(vs);
2120
    }
2121
    return 0;
2122
}
2123

    
2124
void start_auth_vnc(VncState *vs)
2125
{
2126
    make_challenge(vs);
2127
    /* Send client a 'random' challenge */
2128
    vnc_write(vs, vs->challenge, sizeof(vs->challenge));
2129
    vnc_flush(vs);
2130

    
2131
    vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
2132
}
2133

    
2134

    
2135
static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
2136
{
2137
    /* We only advertise 1 auth scheme at a time, so client
2138
     * must pick the one we sent. Verify this */
2139
    if (data[0] != vs->vd->auth) { /* Reject auth */
2140
       VNC_DEBUG("Reject auth %d because it didn't match advertized\n", (int)data[0]);
2141
       vnc_write_u32(vs, 1);
2142
       if (vs->minor >= 8) {
2143
           static const char err[] = "Authentication failed";
2144
           vnc_write_u32(vs, sizeof(err));
2145
           vnc_write(vs, err, sizeof(err));
2146
       }
2147
       vnc_client_error(vs);
2148
    } else { /* Accept requested auth */
2149
       VNC_DEBUG("Client requested auth %d\n", (int)data[0]);
2150
       switch (vs->vd->auth) {
2151
       case VNC_AUTH_NONE:
2152
           VNC_DEBUG("Accept auth none\n");
2153
           if (vs->minor >= 8) {
2154
               vnc_write_u32(vs, 0); /* Accept auth completion */
2155
               vnc_flush(vs);
2156
           }
2157
           start_client_init(vs);
2158
           break;
2159

    
2160
       case VNC_AUTH_VNC:
2161
           VNC_DEBUG("Start VNC auth\n");
2162
           start_auth_vnc(vs);
2163
           break;
2164

    
2165
#ifdef CONFIG_VNC_TLS
2166
       case VNC_AUTH_VENCRYPT:
2167
           VNC_DEBUG("Accept VeNCrypt auth\n");;
2168
           start_auth_vencrypt(vs);
2169
           break;
2170
#endif /* CONFIG_VNC_TLS */
2171

    
2172
#ifdef CONFIG_VNC_SASL
2173
       case VNC_AUTH_SASL:
2174
           VNC_DEBUG("Accept SASL auth\n");
2175
           start_auth_sasl(vs);
2176
           break;
2177
#endif /* CONFIG_VNC_SASL */
2178

    
2179
       default: /* Should not be possible, but just in case */
2180
           VNC_DEBUG("Reject auth %d server code bug\n", vs->vd->auth);
2181
           vnc_write_u8(vs, 1);
2182
           if (vs->minor >= 8) {
2183
               static const char err[] = "Authentication failed";
2184
               vnc_write_u32(vs, sizeof(err));
2185
               vnc_write(vs, err, sizeof(err));
2186
           }
2187
           vnc_client_error(vs);
2188
       }
2189
    }
2190
    return 0;
2191
}
2192

    
2193
static int protocol_version(VncState *vs, uint8_t *version, size_t len)
2194
{
2195
    char local[13];
2196

    
2197
    memcpy(local, version, 12);
2198
    local[12] = 0;
2199

    
2200
    if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2201
        VNC_DEBUG("Malformed protocol version %s\n", local);
2202
        vnc_client_error(vs);
2203
        return 0;
2204
    }
2205
    VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2206
    if (vs->major != 3 ||
2207
        (vs->minor != 3 &&
2208
         vs->minor != 4 &&
2209
         vs->minor != 5 &&
2210
         vs->minor != 7 &&
2211
         vs->minor != 8)) {
2212
        VNC_DEBUG("Unsupported client version\n");
2213
        vnc_write_u32(vs, VNC_AUTH_INVALID);
2214
        vnc_flush(vs);
2215
        vnc_client_error(vs);
2216
        return 0;
2217
    }
2218
    /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2219
     * as equivalent to v3.3 by servers
2220
     */
2221
    if (vs->minor == 4 || vs->minor == 5)
2222
        vs->minor = 3;
2223

    
2224
    if (vs->minor == 3) {
2225
        if (vs->vd->auth == VNC_AUTH_NONE) {
2226
            VNC_DEBUG("Tell client auth none\n");
2227
            vnc_write_u32(vs, vs->vd->auth);
2228
            vnc_flush(vs);
2229
            start_client_init(vs);
2230
       } else if (vs->vd->auth == VNC_AUTH_VNC) {
2231
            VNC_DEBUG("Tell client VNC auth\n");
2232
            vnc_write_u32(vs, vs->vd->auth);
2233
            vnc_flush(vs);
2234
            start_auth_vnc(vs);
2235
       } else {
2236
            VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->vd->auth);
2237
            vnc_write_u32(vs, VNC_AUTH_INVALID);
2238
            vnc_flush(vs);
2239
            vnc_client_error(vs);
2240
       }
2241
    } else {
2242
        VNC_DEBUG("Telling client we support auth %d\n", vs->vd->auth);
2243
        vnc_write_u8(vs, 1); /* num auth */
2244
        vnc_write_u8(vs, vs->vd->auth);
2245
        vnc_read_when(vs, protocol_client_auth, 1);
2246
        vnc_flush(vs);
2247
    }
2248

    
2249
    return 0;
2250
}
2251

    
2252
static int vnc_refresh_server_surface(VncDisplay *vd)
2253
{
2254
    int y;
2255
    uint8_t *guest_row;
2256
    uint8_t *server_row;
2257
    int cmp_bytes;
2258
    uint32_t width_mask[VNC_DIRTY_WORDS];
2259
    VncState *vs;
2260
    int has_dirty = 0;
2261

    
2262
    /*
2263
     * Walk through the guest dirty map.
2264
     * Check and copy modified bits from guest to server surface.
2265
     * Update server dirty map.
2266
     */
2267
    vnc_set_bits(width_mask, (ds_get_width(vd->ds) / 16), VNC_DIRTY_WORDS);
2268
    cmp_bytes = 16 * ds_get_bytes_per_pixel(vd->ds);
2269
    guest_row  = vd->guest.ds->data;
2270
    server_row = vd->server->data;
2271
    for (y = 0; y < vd->guest.ds->height; y++) {
2272
        if (vnc_and_bits(vd->guest.dirty[y], width_mask, VNC_DIRTY_WORDS)) {
2273
            int x;
2274
            uint8_t *guest_ptr;
2275
            uint8_t *server_ptr;
2276

    
2277
            guest_ptr  = guest_row;
2278
            server_ptr = server_row;
2279

    
2280
            for (x = 0; x < vd->guest.ds->width;
2281
                    x += 16, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
2282
                if (!vnc_get_bit(vd->guest.dirty[y], (x / 16)))
2283
                    continue;
2284
                vnc_clear_bit(vd->guest.dirty[y], (x / 16));
2285
                if (memcmp(server_ptr, guest_ptr, cmp_bytes) == 0)
2286
                    continue;
2287
                memcpy(server_ptr, guest_ptr, cmp_bytes);
2288
                QTAILQ_FOREACH(vs, &vd->clients, next) {
2289
                    vnc_set_bit(vs->dirty[y], (x / 16));
2290
                }
2291
                has_dirty++;
2292
            }
2293
        }
2294
        guest_row  += ds_get_linesize(vd->ds);
2295
        server_row += ds_get_linesize(vd->ds);
2296
    }
2297
    return has_dirty;
2298
}
2299

    
2300
static void vnc_refresh(void *opaque)
2301
{
2302
    VncDisplay *vd = opaque;
2303
    VncState *vs, *vn;
2304
    int has_dirty, rects = 0;
2305

    
2306
    vga_hw_update();
2307

    
2308
    if (vnc_trylock_display(vd)) {
2309
        vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
2310
        qemu_mod_timer(vd->timer, qemu_get_clock(rt_clock) +
2311
                       vd->timer_interval);
2312
        return;
2313
    }
2314

    
2315
    has_dirty = vnc_refresh_server_surface(vd);
2316
    vnc_unlock_display(vd);
2317

    
2318
    QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
2319
        rects += vnc_update_client(vs, has_dirty);
2320
        /* vs might be free()ed here */
2321
    }
2322

    
2323
    /* vd->timer could be NULL now if the last client disconnected,
2324
     * in this case don't update the timer */
2325
    if (vd->timer == NULL)
2326
        return;
2327

    
2328
    if (has_dirty && rects) {
2329
        vd->timer_interval /= 2;
2330
        if (vd->timer_interval < VNC_REFRESH_INTERVAL_BASE)
2331
            vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
2332
    } else {
2333
        vd->timer_interval += VNC_REFRESH_INTERVAL_INC;
2334
        if (vd->timer_interval > VNC_REFRESH_INTERVAL_MAX)
2335
            vd->timer_interval = VNC_REFRESH_INTERVAL_MAX;
2336
    }
2337
    qemu_mod_timer(vd->timer, qemu_get_clock(rt_clock) + vd->timer_interval);
2338
}
2339

    
2340
static void vnc_init_timer(VncDisplay *vd)
2341
{
2342
    vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
2343
    if (vd->timer == NULL && !QTAILQ_EMPTY(&vd->clients)) {
2344
        vd->timer = qemu_new_timer(rt_clock, vnc_refresh, vd);
2345
        vnc_refresh(vd);
2346
    }
2347
}
2348

    
2349
static void vnc_remove_timer(VncDisplay *vd)
2350
{
2351
    if (vd->timer != NULL && QTAILQ_EMPTY(&vd->clients)) {
2352
        qemu_del_timer(vd->timer);
2353
        qemu_free_timer(vd->timer);
2354
        vd->timer = NULL;
2355
    }
2356
}
2357

    
2358
static void vnc_connect(VncDisplay *vd, int csock)
2359
{
2360
    VncState *vs = qemu_mallocz(sizeof(VncState));
2361
    vs->csock = csock;
2362

    
2363
    VNC_DEBUG("New client on socket %d\n", csock);
2364
    dcl->idle = 0;
2365
    socket_set_nonblock(vs->csock);
2366
    qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
2367

    
2368
    vnc_client_cache_addr(vs);
2369
    vnc_qmp_event(vs, QEVENT_VNC_CONNECTED);
2370

    
2371
    vs->vd = vd;
2372
    vs->ds = vd->ds;
2373
    vs->last_x = -1;
2374
    vs->last_y = -1;
2375

    
2376
    vs->as.freq = 44100;
2377
    vs->as.nchannels = 2;
2378
    vs->as.fmt = AUD_FMT_S16;
2379
    vs->as.endianness = 0;
2380

    
2381
#ifdef CONFIG_VNC_THREAD
2382
    qemu_mutex_init(&vs->output_mutex);
2383
#endif
2384

    
2385
    QTAILQ_INSERT_HEAD(&vd->clients, vs, next);
2386

    
2387
    vga_hw_update();
2388

    
2389
    vnc_write(vs, "RFB 003.008\n", 12);
2390
    vnc_flush(vs);
2391
    vnc_read_when(vs, protocol_version, 12);
2392
    reset_keys(vs);
2393
    if (vs->vd->lock_key_sync)
2394
        vs->led = qemu_add_led_event_handler(kbd_leds, vs);
2395

    
2396
    vs->mouse_mode_notifier.notify = check_pointer_type_change;
2397
    qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
2398

    
2399
    vnc_init_timer(vd);
2400

    
2401
    /* vs might be free()ed here */
2402
}
2403

    
2404
static void vnc_listen_read(void *opaque)
2405
{
2406
    VncDisplay *vs = opaque;
2407
    struct sockaddr_in addr;
2408
    socklen_t addrlen = sizeof(addr);
2409

    
2410
    /* Catch-up */
2411
    vga_hw_update();
2412

    
2413
    int csock = qemu_accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
2414
    if (csock != -1) {
2415
        vnc_connect(vs, csock);
2416
    }
2417
}
2418

    
2419
void vnc_display_init(DisplayState *ds)
2420
{
2421
    VncDisplay *vs = qemu_mallocz(sizeof(*vs));
2422

    
2423
    dcl = qemu_mallocz(sizeof(DisplayChangeListener));
2424

    
2425
    ds->opaque = vs;
2426
    dcl->idle = 1;
2427
    vnc_display = vs;
2428

    
2429
    vs->lsock = -1;
2430

    
2431
    vs->ds = ds;
2432
    QTAILQ_INIT(&vs->clients);
2433

    
2434
    if (keyboard_layout)
2435
        vs->kbd_layout = init_keyboard_layout(name2keysym, keyboard_layout);
2436
    else
2437
        vs->kbd_layout = init_keyboard_layout(name2keysym, "en-us");
2438

    
2439
    if (!vs->kbd_layout)
2440
        exit(1);
2441

    
2442
#ifdef CONFIG_VNC_THREAD
2443
    qemu_mutex_init(&vs->mutex);
2444
    vnc_start_worker_thread();
2445
#endif
2446

    
2447
    dcl->dpy_copy = vnc_dpy_copy;
2448
    dcl->dpy_update = vnc_dpy_update;
2449
    dcl->dpy_resize = vnc_dpy_resize;
2450
    dcl->dpy_setdata = vnc_dpy_setdata;
2451
    register_displaychangelistener(ds, dcl);
2452
    ds->mouse_set = vnc_mouse_set;
2453
    ds->cursor_define = vnc_dpy_cursor_define;
2454
}
2455

    
2456

    
2457
void vnc_display_close(DisplayState *ds)
2458
{
2459
    VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2460

    
2461
    if (!vs)
2462
        return;
2463
    if (vs->display) {
2464
        qemu_free(vs->display);
2465
        vs->display = NULL;
2466
    }
2467
    if (vs->lsock != -1) {
2468
        qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);
2469
        close(vs->lsock);
2470
        vs->lsock = -1;
2471
    }
2472
    vs->auth = VNC_AUTH_INVALID;
2473
#ifdef CONFIG_VNC_TLS
2474
    vs->subauth = VNC_AUTH_INVALID;
2475
    vs->tls.x509verify = 0;
2476
#endif
2477
}
2478

    
2479
int vnc_display_password(DisplayState *ds, const char *password)
2480
{
2481
    VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2482

    
2483
    if (!vs) {
2484
        return -1;
2485
    }
2486

    
2487
    if (vs->password) {
2488
        qemu_free(vs->password);
2489
        vs->password = NULL;
2490
    }
2491
    if (password && password[0]) {
2492
        if (!(vs->password = qemu_strdup(password)))
2493
            return -1;
2494
        if (vs->auth == VNC_AUTH_NONE) {
2495
            vs->auth = VNC_AUTH_VNC;
2496
        }
2497
    } else {
2498
        vs->auth = VNC_AUTH_NONE;
2499
    }
2500

    
2501
    return 0;
2502
}
2503

    
2504
char *vnc_display_local_addr(DisplayState *ds)
2505
{
2506
    VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2507
    
2508
    return vnc_socket_local_addr("%s:%s", vs->lsock);
2509
}
2510

    
2511
int vnc_display_open(DisplayState *ds, const char *display)
2512
{
2513
    VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2514
    const char *options;
2515
    int password = 0;
2516
    int reverse = 0;
2517
#ifdef CONFIG_VNC_TLS
2518
    int tls = 0, x509 = 0;
2519
#endif
2520
#ifdef CONFIG_VNC_SASL
2521
    int sasl = 0;
2522
    int saslErr;
2523
#endif
2524
    int acl = 0;
2525
    int lock_key_sync = 1;
2526

    
2527
    if (!vnc_display)
2528
        return -1;
2529
    vnc_display_close(ds);
2530
    if (strcmp(display, "none") == 0)
2531
        return 0;
2532

    
2533
    if (!(vs->display = strdup(display)))
2534
        return -1;
2535

    
2536
    options = display;
2537
    while ((options = strchr(options, ','))) {
2538
        options++;
2539
        if (strncmp(options, "password", 8) == 0) {
2540
            password = 1; /* Require password auth */
2541
        } else if (strncmp(options, "reverse", 7) == 0) {
2542
            reverse = 1;
2543
        } else if (strncmp(options, "no-lock-key-sync", 9) == 0) {
2544
            lock_key_sync = 0;
2545
#ifdef CONFIG_VNC_SASL
2546
        } else if (strncmp(options, "sasl", 4) == 0) {
2547
            sasl = 1; /* Require SASL auth */
2548
#endif
2549
#ifdef CONFIG_VNC_TLS
2550
        } else if (strncmp(options, "tls", 3) == 0) {
2551
            tls = 1; /* Require TLS */
2552
        } else if (strncmp(options, "x509", 4) == 0) {
2553
            char *start, *end;
2554
            x509 = 1; /* Require x509 certificates */
2555
            if (strncmp(options, "x509verify", 10) == 0)
2556
                vs->tls.x509verify = 1; /* ...and verify client certs */
2557

    
2558
            /* Now check for 'x509=/some/path' postfix
2559
             * and use that to setup x509 certificate/key paths */
2560
            start = strchr(options, '=');
2561
            end = strchr(options, ',');
2562
            if (start && (!end || (start < end))) {
2563
                int len = end ? end-(start+1) : strlen(start+1);
2564
                char *path = qemu_strndup(start + 1, len);
2565

    
2566
                VNC_DEBUG("Trying certificate path '%s'\n", path);
2567
                if (vnc_tls_set_x509_creds_dir(vs, path) < 0) {
2568
                    fprintf(stderr, "Failed to find x509 certificates/keys in %s\n", path);
2569
                    qemu_free(path);
2570
                    qemu_free(vs->display);
2571
                    vs->display = NULL;
2572
                    return -1;
2573
                }
2574
                qemu_free(path);
2575
            } else {
2576
                fprintf(stderr, "No certificate path provided\n");
2577
                qemu_free(vs->display);
2578
                vs->display = NULL;
2579
                return -1;
2580
            }
2581
#endif
2582
        } else if (strncmp(options, "acl", 3) == 0) {
2583
            acl = 1;
2584
        } else if (strncmp(options, "lossy", 5) == 0) {
2585
            vs->lossy = true;
2586
        }
2587
    }
2588

    
2589
#ifdef CONFIG_VNC_TLS
2590
    if (acl && x509 && vs->tls.x509verify) {
2591
        if (!(vs->tls.acl = qemu_acl_init("vnc.x509dname"))) {
2592
            fprintf(stderr, "Failed to create x509 dname ACL\n");
2593
            exit(1);
2594
        }
2595
    }
2596
#endif
2597
#ifdef CONFIG_VNC_SASL
2598
    if (acl && sasl) {
2599
        if (!(vs->sasl.acl = qemu_acl_init("vnc.username"))) {
2600
            fprintf(stderr, "Failed to create username ACL\n");
2601
            exit(1);
2602
        }
2603
    }
2604
#endif
2605

    
2606
    /*
2607
     * Combinations we support here:
2608
     *
2609
     *  - no-auth                (clear text, no auth)
2610
     *  - password               (clear text, weak auth)
2611
     *  - sasl                   (encrypt, good auth *IF* using Kerberos via GSSAPI)
2612
     *  - tls                    (encrypt, weak anonymous creds, no auth)
2613
     *  - tls + password         (encrypt, weak anonymous creds, weak auth)
2614
     *  - tls + sasl             (encrypt, weak anonymous creds, good auth)
2615
     *  - tls + x509             (encrypt, good x509 creds, no auth)
2616
     *  - tls + x509 + password  (encrypt, good x509 creds, weak auth)
2617
     *  - tls + x509 + sasl      (encrypt, good x509 creds, good auth)
2618
     *
2619
     * NB1. TLS is a stackable auth scheme.
2620
     * NB2. the x509 schemes have option to validate a client cert dname
2621
     */
2622
    if (password) {
2623
#ifdef CONFIG_VNC_TLS
2624
        if (tls) {
2625
            vs->auth = VNC_AUTH_VENCRYPT;
2626
            if (x509) {
2627
                VNC_DEBUG("Initializing VNC server with x509 password auth\n");
2628
                vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;
2629
            } else {
2630
                VNC_DEBUG("Initializing VNC server with TLS password auth\n");
2631
                vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
2632
            }
2633
        } else {
2634
#endif /* CONFIG_VNC_TLS */
2635
            VNC_DEBUG("Initializing VNC server with password auth\n");
2636
            vs->auth = VNC_AUTH_VNC;
2637
#ifdef CONFIG_VNC_TLS
2638
            vs->subauth = VNC_AUTH_INVALID;
2639
        }
2640
#endif /* CONFIG_VNC_TLS */
2641
#ifdef CONFIG_VNC_SASL
2642
    } else if (sasl) {
2643
#ifdef CONFIG_VNC_TLS
2644
        if (tls) {
2645
            vs->auth = VNC_AUTH_VENCRYPT;
2646
            if (x509) {
2647
                VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
2648
                vs->subauth = VNC_AUTH_VENCRYPT_X509SASL;
2649
            } else {
2650
                VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
2651
                vs->subauth = VNC_AUTH_VENCRYPT_TLSSASL;
2652
            }
2653
        } else {
2654
#endif /* CONFIG_VNC_TLS */
2655
            VNC_DEBUG("Initializing VNC server with SASL auth\n");
2656
            vs->auth = VNC_AUTH_SASL;
2657
#ifdef CONFIG_VNC_TLS
2658
            vs->subauth = VNC_AUTH_INVALID;
2659
        }
2660
#endif /* CONFIG_VNC_TLS */
2661
#endif /* CONFIG_VNC_SASL */
2662
    } else {
2663
#ifdef CONFIG_VNC_TLS
2664
        if (tls) {
2665
            vs->auth = VNC_AUTH_VENCRYPT;
2666
            if (x509) {
2667
                VNC_DEBUG("Initializing VNC server with x509 no auth\n");
2668
                vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;
2669
            } else {
2670
                VNC_DEBUG("Initializing VNC server with TLS no auth\n");
2671
                vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
2672
            }
2673
        } else {
2674
#endif
2675
            VNC_DEBUG("Initializing VNC server with no auth\n");
2676
            vs->auth = VNC_AUTH_NONE;
2677
#ifdef CONFIG_VNC_TLS
2678
            vs->subauth = VNC_AUTH_INVALID;
2679
        }
2680
#endif
2681
    }
2682

    
2683
#ifdef CONFIG_VNC_SASL
2684
    if ((saslErr = sasl_server_init(NULL, "qemu")) != SASL_OK) {
2685
        fprintf(stderr, "Failed to initialize SASL auth %s",
2686
                sasl_errstring(saslErr, NULL, NULL));
2687
        free(vs->display);
2688
        vs->display = NULL;
2689
        return -1;
2690
    }
2691
#endif
2692
    vs->lock_key_sync = lock_key_sync;
2693

    
2694
    if (reverse) {
2695
        /* connect to viewer */
2696
        if (strncmp(display, "unix:", 5) == 0)
2697
            vs->lsock = unix_connect(display+5);
2698
        else
2699
            vs->lsock = inet_connect(display, SOCK_STREAM);
2700
        if (-1 == vs->lsock) {
2701
            free(vs->display);
2702
            vs->display = NULL;
2703
            return -1;
2704
        } else {
2705
            int csock = vs->lsock;
2706
            vs->lsock = -1;
2707
            vnc_connect(vs, csock);
2708
        }
2709
        return 0;
2710

    
2711
    } else {
2712
        /* listen for connects */
2713
        char *dpy;
2714
        dpy = qemu_malloc(256);
2715
        if (strncmp(display, "unix:", 5) == 0) {
2716
            pstrcpy(dpy, 256, "unix:");
2717
            vs->lsock = unix_listen(display+5, dpy+5, 256-5);
2718
        } else {
2719
            vs->lsock = inet_listen(display, dpy, 256, SOCK_STREAM, 5900);
2720
        }
2721
        if (-1 == vs->lsock) {
2722
            free(dpy);
2723
            return -1;
2724
        } else {
2725
            free(vs->display);
2726
            vs->display = dpy;
2727
        }
2728
    }
2729
    return qemu_set_fd_handler2(vs->lsock, NULL, vnc_listen_read, NULL, vs);
2730
}