Statistics
| Branch: | Revision:

root / vnc.c @ 161c4f20

History | View | Annotate | Download (76.3 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 "sysemu.h"
29
#include "qemu_socket.h"
30
#include "qemu-timer.h"
31
#include "acl.h"
32
#include "qemu-objects.h"
33

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

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

    
41
#define count_bits(c, v) { \
42
    for (c = 0; v; v >>= 1) \
43
    { \
44
        c += v & 1; \
45
    } \
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
/**
327
 * do_info_vnc(): Show VNC server information
328
 *
329
 * Return a QDict with server information. Connected clients are returned
330
 * as a QList of QDicts.
331
 *
332
 * The main QDict contains the following:
333
 *
334
 * - "enabled": true or false
335
 * - "host": server's IP address
336
 * - "family": address family ("ipv4" or "ipv6")
337
 * - "service": server's port number
338
 * - "auth": authentication method
339
 * - "clients": a QList of all connected clients
340
 *
341
 * Clients are described by a QDict, with the following information:
342
 *
343
 * - "host": client's IP address
344
 * - "family": address family ("ipv4" or "ipv6")
345
 * - "service": client's port number
346
 * - "x509_dname": TLS dname (optional)
347
 * - "sasl_username": SASL username (optional)
348
 *
349
 * Example:
350
 *
351
 * { "enabled": true, "host": "0.0.0.0", "service": "50402", "auth": "vnc",
352
 *   "family": "ipv4",
353
 *   "clients": [{ "host": "127.0.0.1", "service": "50401", "family": "ipv4" }]}
354
 */
355
void do_info_vnc(Monitor *mon, QObject **ret_data)
356
{
357
    if (vnc_display == NULL || vnc_display->display == NULL) {
358
        *ret_data = qobject_from_jsonf("{ 'enabled': false }");
359
    } else {
360
        QList *clist;
361
        VncState *client;
362

    
363
        clist = qlist_new();
364
        QTAILQ_FOREACH(client, &vnc_display->clients, next) {
365
            if (client->info) {
366
                /* incref so that it's not freed by upper layers */
367
                qobject_incref(client->info);
368
                qlist_append_obj(clist, client->info);
369
            }
370
        }
371

    
372
        *ret_data = qobject_from_jsonf("{ 'enabled': true, 'clients': %p }",
373
                                       QOBJECT(clist));
374
        assert(*ret_data != NULL);
375

    
376
        if (vnc_server_info_put(qobject_to_qdict(*ret_data)) < 0) {
377
            qobject_decref(*ret_data);
378
            *ret_data = NULL;
379
        }
380
    }
381
}
382

    
383
static inline uint32_t vnc_has_feature(VncState *vs, int feature) {
384
    return (vs->features & (1 << feature));
385
}
386

    
387
/* TODO
388
   1) Get the queue working for IO.
389
   2) there is some weirdness when using the -S option (the screen is grey
390
      and not totally invalidated
391
   3) resolutions > 1024
392
*/
393

    
394
static int vnc_update_client(VncState *vs, int has_dirty);
395
static void vnc_disconnect_start(VncState *vs);
396
static void vnc_disconnect_finish(VncState *vs);
397
static void vnc_init_timer(VncDisplay *vd);
398
static void vnc_remove_timer(VncDisplay *vd);
399

    
400
static void vnc_colordepth(VncState *vs);
401
static void framebuffer_update_request(VncState *vs, int incremental,
402
                                       int x_position, int y_position,
403
                                       int w, int h);
404
static void vnc_refresh(void *opaque);
405
static int vnc_refresh_server_surface(VncDisplay *vd);
406

    
407
static inline void vnc_set_bit(uint32_t *d, int k)
408
{
409
    d[k >> 5] |= 1 << (k & 0x1f);
410
}
411

    
412
static inline void vnc_clear_bit(uint32_t *d, int k)
413
{
414
    d[k >> 5] &= ~(1 << (k & 0x1f));
415
}
416

    
417
static inline void vnc_set_bits(uint32_t *d, int n, int nb_words)
418
{
419
    int j;
420

    
421
    j = 0;
422
    while (n >= 32) {
423
        d[j++] = -1;
424
        n -= 32;
425
    }
426
    if (n > 0)
427
        d[j++] = (1 << n) - 1;
428
    while (j < nb_words)
429
        d[j++] = 0;
430
}
431

    
432
static inline int vnc_get_bit(const uint32_t *d, int k)
433
{
434
    return (d[k >> 5] >> (k & 0x1f)) & 1;
435
}
436

    
437
static inline int vnc_and_bits(const uint32_t *d1, const uint32_t *d2,
438
                               int nb_words)
439
{
440
    int i;
441
    for(i = 0; i < nb_words; i++) {
442
        if ((d1[i] & d2[i]) != 0)
443
            return 1;
444
    }
445
    return 0;
446
}
447

    
448
static void vnc_dpy_update(DisplayState *ds, int x, int y, int w, int h)
449
{
450
    int i;
451
    VncDisplay *vd = ds->opaque;
452
    struct VncSurface *s = &vd->guest;
453

    
454
    h += y;
455

    
456
    /* round x down to ensure the loop only spans one 16-pixel block per,
457
       iteration.  otherwise, if (x % 16) != 0, the last iteration may span
458
       two 16-pixel blocks but we only mark the first as dirty
459
    */
460
    w += (x % 16);
461
    x -= (x % 16);
462

    
463
    x = MIN(x, s->ds->width);
464
    y = MIN(y, s->ds->height);
465
    w = MIN(x + w, s->ds->width) - x;
466
    h = MIN(h, s->ds->height);
467

    
468
    for (; y < h; y++)
469
        for (i = 0; i < w; i += 16)
470
            vnc_set_bit(s->dirty[y], (x + i) / 16);
471
}
472

    
473
void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
474
                            int32_t encoding)
475
{
476
    vnc_write_u16(vs, x);
477
    vnc_write_u16(vs, y);
478
    vnc_write_u16(vs, w);
479
    vnc_write_u16(vs, h);
480

    
481
    vnc_write_s32(vs, encoding);
482
}
483

    
484
void buffer_reserve(Buffer *buffer, size_t len)
485
{
486
    if ((buffer->capacity - buffer->offset) < len) {
487
        buffer->capacity += (len + 1024);
488
        buffer->buffer = qemu_realloc(buffer->buffer, buffer->capacity);
489
        if (buffer->buffer == NULL) {
490
            fprintf(stderr, "vnc: out of memory\n");
491
            exit(1);
492
        }
493
    }
494
}
495

    
496
int buffer_empty(Buffer *buffer)
497
{
498
    return buffer->offset == 0;
499
}
500

    
501
uint8_t *buffer_end(Buffer *buffer)
502
{
503
    return buffer->buffer + buffer->offset;
504
}
505

    
506
void buffer_reset(Buffer *buffer)
507
{
508
        buffer->offset = 0;
509
}
510

    
511
void buffer_free(Buffer *buffer)
512
{
513
    qemu_free(buffer->buffer);
514
    buffer->offset = 0;
515
    buffer->capacity = 0;
516
    buffer->buffer = NULL;
517
}
518

    
519
void buffer_append(Buffer *buffer, const void *data, size_t len)
520
{
521
    memcpy(buffer->buffer + buffer->offset, data, len);
522
    buffer->offset += len;
523
}
524

    
525
static void vnc_dpy_resize(DisplayState *ds)
526
{
527
    int size_changed;
528
    VncDisplay *vd = ds->opaque;
529
    VncState *vs;
530

    
531
    /* server surface */
532
    if (!vd->server)
533
        vd->server = qemu_mallocz(sizeof(*vd->server));
534
    if (vd->server->data)
535
        qemu_free(vd->server->data);
536
    *(vd->server) = *(ds->surface);
537
    vd->server->data = qemu_mallocz(vd->server->linesize *
538
                                    vd->server->height);
539

    
540
    /* guest surface */
541
    if (!vd->guest.ds)
542
        vd->guest.ds = qemu_mallocz(sizeof(*vd->guest.ds));
543
    if (ds_get_bytes_per_pixel(ds) != vd->guest.ds->pf.bytes_per_pixel)
544
        console_color_init(ds);
545
    size_changed = ds_get_width(ds) != vd->guest.ds->width ||
546
                   ds_get_height(ds) != vd->guest.ds->height;
547
    *(vd->guest.ds) = *(ds->surface);
548
    memset(vd->guest.dirty, 0xFF, sizeof(vd->guest.dirty));
549

    
550
    QTAILQ_FOREACH(vs, &vd->clients, next) {
551
        vnc_colordepth(vs);
552
        if (size_changed) {
553
            if (vs->csock != -1 && vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
554
                vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
555
                vnc_write_u8(vs, 0);
556
                vnc_write_u16(vs, 1); /* number of rects */
557
                vnc_framebuffer_update(vs, 0, 0, ds_get_width(ds), ds_get_height(ds),
558
                        VNC_ENCODING_DESKTOPRESIZE);
559
                vnc_flush(vs);
560
            }
561
        }
562
        if (vs->vd->cursor) {
563
            vnc_cursor_define(vs);
564
        }
565
        memset(vs->dirty, 0xFF, sizeof(vs->dirty));
566
    }
567
}
568

    
569
/* fastest code */
570
static void vnc_write_pixels_copy(VncState *vs, struct PixelFormat *pf,
571
                                  void *pixels, int size)
572
{
573
    vnc_write(vs, pixels, size);
574
}
575

    
576
/* slowest but generic code. */
577
void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
578
{
579
    uint8_t r, g, b;
580
    VncDisplay *vd = vs->vd;
581

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

    
621
static void vnc_write_pixels_generic(VncState *vs, struct PixelFormat *pf,
622
                                     void *pixels1, int size)
623
{
624
    uint8_t buf[4];
625

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

    
655
void vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
656
{
657
    int i;
658
    uint8_t *row;
659
    VncDisplay *vd = vs->vd;
660

    
661
    row = vd->server->data + y * ds_get_linesize(vs->ds) + x * ds_get_bytes_per_pixel(vs->ds);
662
    for (i = 0; i < h; i++) {
663
        vs->write_pixels(vs, &vd->server->pf, row, w * ds_get_bytes_per_pixel(vs->ds));
664
        row += ds_get_linesize(vs->ds);
665
    }
666
}
667

    
668
static void send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
669
{
670
    switch(vs->vnc_encoding) {
671
        case VNC_ENCODING_ZLIB:
672
            vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
673
            break;
674
        case VNC_ENCODING_HEXTILE:
675
            vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
676
            vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
677
            break;
678
        default:
679
            vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
680
            vnc_raw_send_framebuffer_update(vs, x, y, w, h);
681
            break;
682
    }
683
}
684

    
685
static void vnc_copy(VncState *vs, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
686
{
687
    /* send bitblit op to the vnc client */
688
    vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
689
    vnc_write_u8(vs, 0);
690
    vnc_write_u16(vs, 1); /* number of rects */
691
    vnc_framebuffer_update(vs, dst_x, dst_y, w, h, VNC_ENCODING_COPYRECT);
692
    vnc_write_u16(vs, src_x);
693
    vnc_write_u16(vs, src_y);
694
    vnc_flush(vs);
695
}
696

    
697
static void vnc_dpy_copy(DisplayState *ds, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
698
{
699
    VncDisplay *vd = ds->opaque;
700
    VncState *vs, *vn;
701
    uint8_t *src_row;
702
    uint8_t *dst_row;
703
    int i,x,y,pitch,depth,inc,w_lim,s;
704
    int cmp_bytes;
705

    
706
    vnc_refresh_server_surface(vd);
707
    QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
708
        if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
709
            vs->force_update = 1;
710
            vnc_update_client(vs, 1);
711
            /* vs might be free()ed here */
712
        }
713
    }
714

    
715
    /* do bitblit op on the local surface too */
716
    pitch = ds_get_linesize(vd->ds);
717
    depth = ds_get_bytes_per_pixel(vd->ds);
718
    src_row = vd->server->data + pitch * src_y + depth * src_x;
719
    dst_row = vd->server->data + pitch * dst_y + depth * dst_x;
720
    y = dst_y;
721
    inc = 1;
722
    if (dst_y > src_y) {
723
        /* copy backwards */
724
        src_row += pitch * (h-1);
725
        dst_row += pitch * (h-1);
726
        pitch = -pitch;
727
        y = dst_y + h - 1;
728
        inc = -1;
729
    }
730
    w_lim = w - (16 - (dst_x % 16));
731
    if (w_lim < 0)
732
        w_lim = w;
733
    else
734
        w_lim = w - (w_lim % 16);
735
    for (i = 0; i < h; i++) {
736
        for (x = 0; x <= w_lim;
737
                x += s, src_row += cmp_bytes, dst_row += cmp_bytes) {
738
            if (x == w_lim) {
739
                if ((s = w - w_lim) == 0)
740
                    break;
741
            } else if (!x) {
742
                s = (16 - (dst_x % 16));
743
                s = MIN(s, w_lim);
744
            } else {
745
                s = 16;
746
            }
747
            cmp_bytes = s * depth;
748
            if (memcmp(src_row, dst_row, cmp_bytes) == 0)
749
                continue;
750
            memmove(dst_row, src_row, cmp_bytes);
751
            QTAILQ_FOREACH(vs, &vd->clients, next) {
752
                if (!vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
753
                    vnc_set_bit(vs->dirty[y], ((x + dst_x) / 16));
754
                }
755
            }
756
        }
757
        src_row += pitch - w * depth;
758
        dst_row += pitch - w * depth;
759
        y += inc;
760
    }
761

    
762
    QTAILQ_FOREACH(vs, &vd->clients, next) {
763
        if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
764
            vnc_copy(vs, src_x, src_y, dst_x, dst_y, w, h);
765
        }
766
    }
767
}
768

    
769
static void vnc_mouse_set(int x, int y, int visible)
770
{
771
    /* can we ask the client(s) to move the pointer ??? */
772
}
773

    
774
static int vnc_cursor_define(VncState *vs)
775
{
776
    QEMUCursor *c = vs->vd->cursor;
777
    PixelFormat pf = qemu_default_pixelformat(32);
778
    int isize;
779

    
780
    if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
781
        vnc_write_u8(vs,  VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
782
        vnc_write_u8(vs,  0);  /*  padding     */
783
        vnc_write_u16(vs, 1);  /*  # of rects  */
784
        vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
785
                               VNC_ENCODING_RICH_CURSOR);
786
        isize = c->width * c->height * vs->clientds.pf.bytes_per_pixel;
787
        vnc_write_pixels_generic(vs, &pf, c->data, isize);
788
        vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
789
        return 0;
790
    }
791
    return -1;
792
}
793

    
794
static void vnc_dpy_cursor_define(QEMUCursor *c)
795
{
796
    VncDisplay *vd = vnc_display;
797
    VncState *vs;
798

    
799
    cursor_put(vd->cursor);
800
    qemu_free(vd->cursor_mask);
801

    
802
    vd->cursor = c;
803
    cursor_get(vd->cursor);
804
    vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
805
    vd->cursor_mask = qemu_mallocz(vd->cursor_msize);
806
    cursor_get_mono_mask(c, 0, vd->cursor_mask);
807

    
808
    QTAILQ_FOREACH(vs, &vd->clients, next) {
809
        vnc_cursor_define(vs);
810
    }
811
}
812

    
813
static int find_and_clear_dirty_height(struct VncState *vs,
814
                                       int y, int last_x, int x)
815
{
816
    int h;
817
    VncDisplay *vd = vs->vd;
818

    
819
    for (h = 1; h < (vd->server->height - y); h++) {
820
        int tmp_x;
821
        if (!vnc_get_bit(vs->dirty[y + h], last_x))
822
            break;
823
        for (tmp_x = last_x; tmp_x < x; tmp_x++)
824
            vnc_clear_bit(vs->dirty[y + h], tmp_x);
825
    }
826

    
827
    return h;
828
}
829

    
830
static int vnc_update_client(VncState *vs, int has_dirty)
831
{
832
    if (vs->need_update && vs->csock != -1) {
833
        VncDisplay *vd = vs->vd;
834
        int y;
835
        int n_rectangles;
836
        int saved_offset;
837

    
838
        if (vs->output.offset && !vs->audio_cap && !vs->force_update)
839
            /* kernel send buffers are full -> drop frames to throttle */
840
            return 0;
841

    
842
        if (!has_dirty && !vs->audio_cap && !vs->force_update)
843
            return 0;
844

    
845
        /*
846
         * Send screen updates to the vnc client using the server
847
         * surface and server dirty map.  guest surface updates
848
         * happening in parallel don't disturb us, the next pass will
849
         * send them to the client.
850
         */
851
        n_rectangles = 0;
852
        vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
853
        vnc_write_u8(vs, 0);
854
        saved_offset = vs->output.offset;
855
        vnc_write_u16(vs, 0);
856

    
857
        for (y = 0; y < vd->server->height; y++) {
858
            int x;
859
            int last_x = -1;
860
            for (x = 0; x < vd->server->width / 16; x++) {
861
                if (vnc_get_bit(vs->dirty[y], x)) {
862
                    if (last_x == -1) {
863
                        last_x = x;
864
                    }
865
                    vnc_clear_bit(vs->dirty[y], x);
866
                } else {
867
                    if (last_x != -1) {
868
                        int h = find_and_clear_dirty_height(vs, y, last_x, x);
869
                        send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
870
                        n_rectangles++;
871
                    }
872
                    last_x = -1;
873
                }
874
            }
875
            if (last_x != -1) {
876
                int h = find_and_clear_dirty_height(vs, y, last_x, x);
877
                send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
878
                n_rectangles++;
879
            }
880
        }
881
        vs->output.buffer[saved_offset] = (n_rectangles >> 8) & 0xFF;
882
        vs->output.buffer[saved_offset + 1] = n_rectangles & 0xFF;
883
        vnc_flush(vs);
884
        vs->force_update = 0;
885
        return n_rectangles;
886
    }
887

    
888
    if (vs->csock == -1)
889
        vnc_disconnect_finish(vs);
890

    
891
    return 0;
892
}
893

    
894
/* audio */
895
static void audio_capture_notify(void *opaque, audcnotification_e cmd)
896
{
897
    VncState *vs = opaque;
898

    
899
    switch (cmd) {
900
    case AUD_CNOTIFY_DISABLE:
901
        vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
902
        vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
903
        vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
904
        vnc_flush(vs);
905
        break;
906

    
907
    case AUD_CNOTIFY_ENABLE:
908
        vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
909
        vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
910
        vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
911
        vnc_flush(vs);
912
        break;
913
    }
914
}
915

    
916
static void audio_capture_destroy(void *opaque)
917
{
918
}
919

    
920
static void audio_capture(void *opaque, void *buf, int size)
921
{
922
    VncState *vs = opaque;
923

    
924
    vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
925
    vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
926
    vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
927
    vnc_write_u32(vs, size);
928
    vnc_write(vs, buf, size);
929
    vnc_flush(vs);
930
}
931

    
932
static void audio_add(VncState *vs)
933
{
934
    struct audio_capture_ops ops;
935

    
936
    if (vs->audio_cap) {
937
        monitor_printf(default_mon, "audio already running\n");
938
        return;
939
    }
940

    
941
    ops.notify = audio_capture_notify;
942
    ops.destroy = audio_capture_destroy;
943
    ops.capture = audio_capture;
944

    
945
    vs->audio_cap = AUD_add_capture(&vs->as, &ops, vs);
946
    if (!vs->audio_cap) {
947
        monitor_printf(default_mon, "Failed to add audio capture\n");
948
    }
949
}
950

    
951
static void audio_del(VncState *vs)
952
{
953
    if (vs->audio_cap) {
954
        AUD_del_capture(vs->audio_cap, vs);
955
        vs->audio_cap = NULL;
956
    }
957
}
958

    
959
static void vnc_disconnect_start(VncState *vs)
960
{
961
    if (vs->csock == -1)
962
        return;
963
    qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
964
    closesocket(vs->csock);
965
    vs->csock = -1;
966
}
967

    
968
static void vnc_disconnect_finish(VncState *vs)
969
{
970
    vnc_qmp_event(vs, QEVENT_VNC_DISCONNECTED);
971

    
972
    buffer_free(&vs->input);
973
    buffer_free(&vs->output);
974

    
975
    qobject_decref(vs->info);
976

    
977
    vnc_zlib_clear(vs);
978

    
979
#ifdef CONFIG_VNC_TLS
980
    vnc_tls_client_cleanup(vs);
981
#endif /* CONFIG_VNC_TLS */
982
#ifdef CONFIG_VNC_SASL
983
    vnc_sasl_client_cleanup(vs);
984
#endif /* CONFIG_VNC_SASL */
985
    audio_del(vs);
986

    
987
    QTAILQ_REMOVE(&vs->vd->clients, vs, next);
988

    
989
    if (QTAILQ_EMPTY(&vs->vd->clients)) {
990
        dcl->idle = 1;
991
    }
992

    
993
    qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
994
    vnc_remove_timer(vs->vd);
995
    if (vs->vd->lock_key_sync)
996
        qemu_remove_led_event_handler(vs->led);
997
    qemu_free(vs);
998
}
999

    
1000
int vnc_client_io_error(VncState *vs, int ret, int last_errno)
1001
{
1002
    if (ret == 0 || ret == -1) {
1003
        if (ret == -1) {
1004
            switch (last_errno) {
1005
                case EINTR:
1006
                case EAGAIN:
1007
#ifdef _WIN32
1008
                case WSAEWOULDBLOCK:
1009
#endif
1010
                    return 0;
1011
                default:
1012
                    break;
1013
            }
1014
        }
1015

    
1016
        VNC_DEBUG("Closing down client sock: ret %d, errno %d\n",
1017
                  ret, ret < 0 ? last_errno : 0);
1018
        vnc_disconnect_start(vs);
1019

    
1020
        return 0;
1021
    }
1022
    return ret;
1023
}
1024

    
1025

    
1026
void vnc_client_error(VncState *vs)
1027
{
1028
    VNC_DEBUG("Closing down client sock: protocol error\n");
1029
    vnc_disconnect_start(vs);
1030
}
1031

    
1032

    
1033
/*
1034
 * Called to write a chunk of data to the client socket. The data may
1035
 * be the raw data, or may have already been encoded by SASL.
1036
 * The data will be written either straight onto the socket, or
1037
 * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1038
 *
1039
 * NB, it is theoretically possible to have 2 layers of encryption,
1040
 * both SASL, and this TLS layer. It is highly unlikely in practice
1041
 * though, since SASL encryption will typically be a no-op if TLS
1042
 * is active
1043
 *
1044
 * Returns the number of bytes written, which may be less than
1045
 * the requested 'datalen' if the socket would block. Returns
1046
 * -1 on error, and disconnects the client socket.
1047
 */
1048
long vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
1049
{
1050
    long ret;
1051
#ifdef CONFIG_VNC_TLS
1052
    if (vs->tls.session) {
1053
        ret = gnutls_write(vs->tls.session, data, datalen);
1054
        if (ret < 0) {
1055
            if (ret == GNUTLS_E_AGAIN)
1056
                errno = EAGAIN;
1057
            else
1058
                errno = EIO;
1059
            ret = -1;
1060
        }
1061
    } else
1062
#endif /* CONFIG_VNC_TLS */
1063
        ret = send(vs->csock, (const void *)data, datalen, 0);
1064
    VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
1065
    return vnc_client_io_error(vs, ret, socket_error());
1066
}
1067

    
1068

    
1069
/*
1070
 * Called to write buffered data to the client socket, when not
1071
 * using any SASL SSF encryption layers. Will write as much data
1072
 * as possible without blocking. If all buffered data is written,
1073
 * will switch the FD poll() handler back to read monitoring.
1074
 *
1075
 * Returns the number of bytes written, which may be less than
1076
 * the buffered output data if the socket would block. Returns
1077
 * -1 on error, and disconnects the client socket.
1078
 */
1079
static long vnc_client_write_plain(VncState *vs)
1080
{
1081
    long ret;
1082

    
1083
#ifdef CONFIG_VNC_SASL
1084
    VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
1085
              vs->output.buffer, vs->output.capacity, vs->output.offset,
1086
              vs->sasl.waitWriteSSF);
1087

    
1088
    if (vs->sasl.conn &&
1089
        vs->sasl.runSSF &&
1090
        vs->sasl.waitWriteSSF) {
1091
        ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
1092
        if (ret)
1093
            vs->sasl.waitWriteSSF -= ret;
1094
    } else
1095
#endif /* CONFIG_VNC_SASL */
1096
        ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
1097
    if (!ret)
1098
        return 0;
1099

    
1100
    memmove(vs->output.buffer, vs->output.buffer + ret, (vs->output.offset - ret));
1101
    vs->output.offset -= ret;
1102

    
1103
    if (vs->output.offset == 0) {
1104
        qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
1105
    }
1106

    
1107
    return ret;
1108
}
1109

    
1110

    
1111
/*
1112
 * First function called whenever there is data to be written to
1113
 * the client socket. Will delegate actual work according to whether
1114
 * SASL SSF layers are enabled (thus requiring encryption calls)
1115
 */
1116
void vnc_client_write(void *opaque)
1117
{
1118
    VncState *vs = opaque;
1119

    
1120
#ifdef CONFIG_VNC_SASL
1121
    if (vs->sasl.conn &&
1122
        vs->sasl.runSSF &&
1123
        !vs->sasl.waitWriteSSF) {
1124
        vnc_client_write_sasl(vs);
1125
    } else
1126
#endif /* CONFIG_VNC_SASL */
1127
        vnc_client_write_plain(vs);
1128
}
1129

    
1130
void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
1131
{
1132
    vs->read_handler = func;
1133
    vs->read_handler_expect = expecting;
1134
}
1135

    
1136

    
1137
/*
1138
 * Called to read a chunk of data from the client socket. The data may
1139
 * be the raw data, or may need to be further decoded by SASL.
1140
 * The data will be read either straight from to the socket, or
1141
 * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1142
 *
1143
 * NB, it is theoretically possible to have 2 layers of encryption,
1144
 * both SASL, and this TLS layer. It is highly unlikely in practice
1145
 * though, since SASL encryption will typically be a no-op if TLS
1146
 * is active
1147
 *
1148
 * Returns the number of bytes read, which may be less than
1149
 * the requested 'datalen' if the socket would block. Returns
1150
 * -1 on error, and disconnects the client socket.
1151
 */
1152
long vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
1153
{
1154
    long ret;
1155
#ifdef CONFIG_VNC_TLS
1156
    if (vs->tls.session) {
1157
        ret = gnutls_read(vs->tls.session, data, datalen);
1158
        if (ret < 0) {
1159
            if (ret == GNUTLS_E_AGAIN)
1160
                errno = EAGAIN;
1161
            else
1162
                errno = EIO;
1163
            ret = -1;
1164
        }
1165
    } else
1166
#endif /* CONFIG_VNC_TLS */
1167
        ret = recv(vs->csock, (void *)data, datalen, 0);
1168
    VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
1169
    return vnc_client_io_error(vs, ret, socket_error());
1170
}
1171

    
1172

    
1173
/*
1174
 * Called to read data from the client socket to the input buffer,
1175
 * when not using any SASL SSF encryption layers. Will read as much
1176
 * data as possible without blocking.
1177
 *
1178
 * Returns the number of bytes read. Returns -1 on error, and
1179
 * disconnects the client socket.
1180
 */
1181
static long vnc_client_read_plain(VncState *vs)
1182
{
1183
    int ret;
1184
    VNC_DEBUG("Read plain %p size %zd offset %zd\n",
1185
              vs->input.buffer, vs->input.capacity, vs->input.offset);
1186
    buffer_reserve(&vs->input, 4096);
1187
    ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
1188
    if (!ret)
1189
        return 0;
1190
    vs->input.offset += ret;
1191
    return ret;
1192
}
1193

    
1194

    
1195
/*
1196
 * First function called whenever there is more data to be read from
1197
 * the client socket. Will delegate actual work according to whether
1198
 * SASL SSF layers are enabled (thus requiring decryption calls)
1199
 */
1200
void vnc_client_read(void *opaque)
1201
{
1202
    VncState *vs = opaque;
1203
    long ret;
1204

    
1205
#ifdef CONFIG_VNC_SASL
1206
    if (vs->sasl.conn && vs->sasl.runSSF)
1207
        ret = vnc_client_read_sasl(vs);
1208
    else
1209
#endif /* CONFIG_VNC_SASL */
1210
        ret = vnc_client_read_plain(vs);
1211
    if (!ret) {
1212
        if (vs->csock == -1)
1213
            vnc_disconnect_finish(vs);
1214
        return;
1215
    }
1216

    
1217
    while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
1218
        size_t len = vs->read_handler_expect;
1219
        int ret;
1220

    
1221
        ret = vs->read_handler(vs, vs->input.buffer, len);
1222
        if (vs->csock == -1) {
1223
            vnc_disconnect_finish(vs);
1224
            return;
1225
        }
1226

    
1227
        if (!ret) {
1228
            memmove(vs->input.buffer, vs->input.buffer + len, (vs->input.offset - len));
1229
            vs->input.offset -= len;
1230
        } else {
1231
            vs->read_handler_expect = ret;
1232
        }
1233
    }
1234
}
1235

    
1236
void vnc_write(VncState *vs, const void *data, size_t len)
1237
{
1238
    buffer_reserve(&vs->output, len);
1239

    
1240
    if (vs->csock != -1 && buffer_empty(&vs->output)) {
1241
        qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
1242
    }
1243

    
1244
    buffer_append(&vs->output, data, len);
1245
}
1246

    
1247
void vnc_write_s32(VncState *vs, int32_t value)
1248
{
1249
    vnc_write_u32(vs, *(uint32_t *)&value);
1250
}
1251

    
1252
void vnc_write_u32(VncState *vs, uint32_t value)
1253
{
1254
    uint8_t buf[4];
1255

    
1256
    buf[0] = (value >> 24) & 0xFF;
1257
    buf[1] = (value >> 16) & 0xFF;
1258
    buf[2] = (value >>  8) & 0xFF;
1259
    buf[3] = value & 0xFF;
1260

    
1261
    vnc_write(vs, buf, 4);
1262
}
1263

    
1264
void vnc_write_u16(VncState *vs, uint16_t value)
1265
{
1266
    uint8_t buf[2];
1267

    
1268
    buf[0] = (value >> 8) & 0xFF;
1269
    buf[1] = value & 0xFF;
1270

    
1271
    vnc_write(vs, buf, 2);
1272
}
1273

    
1274
void vnc_write_u8(VncState *vs, uint8_t value)
1275
{
1276
    vnc_write(vs, (char *)&value, 1);
1277
}
1278

    
1279
void vnc_flush(VncState *vs)
1280
{
1281
    if (vs->csock != -1 && vs->output.offset)
1282
        vnc_client_write(vs);
1283
}
1284

    
1285
uint8_t read_u8(uint8_t *data, size_t offset)
1286
{
1287
    return data[offset];
1288
}
1289

    
1290
uint16_t read_u16(uint8_t *data, size_t offset)
1291
{
1292
    return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1293
}
1294

    
1295
int32_t read_s32(uint8_t *data, size_t offset)
1296
{
1297
    return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
1298
                     (data[offset + 2] << 8) | data[offset + 3]);
1299
}
1300

    
1301
uint32_t read_u32(uint8_t *data, size_t offset)
1302
{
1303
    return ((data[offset] << 24) | (data[offset + 1] << 16) |
1304
            (data[offset + 2] << 8) | data[offset + 3]);
1305
}
1306

    
1307
static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
1308
{
1309
}
1310

    
1311
static void check_pointer_type_change(Notifier *notifier)
1312
{
1313
    VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
1314
    int absolute = kbd_mouse_is_absolute();
1315

    
1316
    if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1317
        vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1318
        vnc_write_u8(vs, 0);
1319
        vnc_write_u16(vs, 1);
1320
        vnc_framebuffer_update(vs, absolute, 0,
1321
                               ds_get_width(vs->ds), ds_get_height(vs->ds),
1322
                               VNC_ENCODING_POINTER_TYPE_CHANGE);
1323
        vnc_flush(vs);
1324
    }
1325
    vs->absolute = absolute;
1326
}
1327

    
1328
static void pointer_event(VncState *vs, int button_mask, int x, int y)
1329
{
1330
    int buttons = 0;
1331
    int dz = 0;
1332

    
1333
    if (button_mask & 0x01)
1334
        buttons |= MOUSE_EVENT_LBUTTON;
1335
    if (button_mask & 0x02)
1336
        buttons |= MOUSE_EVENT_MBUTTON;
1337
    if (button_mask & 0x04)
1338
        buttons |= MOUSE_EVENT_RBUTTON;
1339
    if (button_mask & 0x08)
1340
        dz = -1;
1341
    if (button_mask & 0x10)
1342
        dz = 1;
1343

    
1344
    if (vs->absolute) {
1345
        kbd_mouse_event(ds_get_width(vs->ds) > 1 ?
1346
                          x * 0x7FFF / (ds_get_width(vs->ds) - 1) : 0x4000,
1347
                        ds_get_height(vs->ds) > 1 ?
1348
                          y * 0x7FFF / (ds_get_height(vs->ds) - 1) : 0x4000,
1349
                        dz, buttons);
1350
    } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
1351
        x -= 0x7FFF;
1352
        y -= 0x7FFF;
1353

    
1354
        kbd_mouse_event(x, y, dz, buttons);
1355
    } else {
1356
        if (vs->last_x != -1)
1357
            kbd_mouse_event(x - vs->last_x,
1358
                            y - vs->last_y,
1359
                            dz, buttons);
1360
        vs->last_x = x;
1361
        vs->last_y = y;
1362
    }
1363
}
1364

    
1365
static void reset_keys(VncState *vs)
1366
{
1367
    int i;
1368
    for(i = 0; i < 256; i++) {
1369
        if (vs->modifiers_state[i]) {
1370
            if (i & SCANCODE_GREY)
1371
                kbd_put_keycode(SCANCODE_EMUL0);
1372
            kbd_put_keycode(i | SCANCODE_UP);
1373
            vs->modifiers_state[i] = 0;
1374
        }
1375
    }
1376
}
1377

    
1378
static void press_key(VncState *vs, int keysym)
1379
{
1380
    int keycode = keysym2scancode(vs->vd->kbd_layout, keysym) & SCANCODE_KEYMASK;
1381
    if (keycode & SCANCODE_GREY)
1382
        kbd_put_keycode(SCANCODE_EMUL0);
1383
    kbd_put_keycode(keycode & SCANCODE_KEYCODEMASK);
1384
    if (keycode & SCANCODE_GREY)
1385
        kbd_put_keycode(SCANCODE_EMUL0);
1386
    kbd_put_keycode(keycode | SCANCODE_UP);
1387
}
1388

    
1389
static void kbd_leds(void *opaque, int ledstate)
1390
{
1391
    VncState *vs = opaque;
1392
    int caps, num;
1393

    
1394
    caps = ledstate & QEMU_CAPS_LOCK_LED ? 1 : 0;
1395
    num  = ledstate & QEMU_NUM_LOCK_LED  ? 1 : 0;
1396

    
1397
    if (vs->modifiers_state[0x3a] != caps) {
1398
        vs->modifiers_state[0x3a] = caps;
1399
    }
1400
    if (vs->modifiers_state[0x45] != num) {
1401
        vs->modifiers_state[0x45] = num;
1402
    }
1403
}
1404

    
1405
static void do_key_event(VncState *vs, int down, int keycode, int sym)
1406
{
1407
    /* QEMU console switch */
1408
    switch(keycode) {
1409
    case 0x2a:                          /* Left Shift */
1410
    case 0x36:                          /* Right Shift */
1411
    case 0x1d:                          /* Left CTRL */
1412
    case 0x9d:                          /* Right CTRL */
1413
    case 0x38:                          /* Left ALT */
1414
    case 0xb8:                          /* Right ALT */
1415
        if (down)
1416
            vs->modifiers_state[keycode] = 1;
1417
        else
1418
            vs->modifiers_state[keycode] = 0;
1419
        break;
1420
    case 0x02 ... 0x0a: /* '1' to '9' keys */
1421
        if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
1422
            /* Reset the modifiers sent to the current console */
1423
            reset_keys(vs);
1424
            console_select(keycode - 0x02);
1425
            return;
1426
        }
1427
        break;
1428
    case 0x3a:                        /* CapsLock */
1429
    case 0x45:                        /* NumLock */
1430
        if (down)
1431
            vs->modifiers_state[keycode] ^= 1;
1432
        break;
1433
    }
1434

    
1435
    if (vs->vd->lock_key_sync &&
1436
        keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
1437
        /* If the numlock state needs to change then simulate an additional
1438
           keypress before sending this one.  This will happen if the user
1439
           toggles numlock away from the VNC window.
1440
        */
1441
        if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1442
            if (!vs->modifiers_state[0x45]) {
1443
                vs->modifiers_state[0x45] = 1;
1444
                press_key(vs, 0xff7f);
1445
            }
1446
        } else {
1447
            if (vs->modifiers_state[0x45]) {
1448
                vs->modifiers_state[0x45] = 0;
1449
                press_key(vs, 0xff7f);
1450
            }
1451
        }
1452
    }
1453

    
1454
    if (vs->vd->lock_key_sync &&
1455
        ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
1456
        /* If the capslock state needs to change then simulate an additional
1457
           keypress before sending this one.  This will happen if the user
1458
           toggles capslock away from the VNC window.
1459
        */
1460
        int uppercase = !!(sym >= 'A' && sym <= 'Z');
1461
        int shift = !!(vs->modifiers_state[0x2a] | vs->modifiers_state[0x36]);
1462
        int capslock = !!(vs->modifiers_state[0x3a]);
1463
        if (capslock) {
1464
            if (uppercase == shift) {
1465
                vs->modifiers_state[0x3a] = 0;
1466
                press_key(vs, 0xffe5);
1467
            }
1468
        } else {
1469
            if (uppercase != shift) {
1470
                vs->modifiers_state[0x3a] = 1;
1471
                press_key(vs, 0xffe5);
1472
            }
1473
        }
1474
    }
1475

    
1476
    if (is_graphic_console()) {
1477
        if (keycode & SCANCODE_GREY)
1478
            kbd_put_keycode(SCANCODE_EMUL0);
1479
        if (down)
1480
            kbd_put_keycode(keycode & SCANCODE_KEYCODEMASK);
1481
        else
1482
            kbd_put_keycode(keycode | SCANCODE_UP);
1483
    } else {
1484
        /* QEMU console emulation */
1485
        if (down) {
1486
            int numlock = vs->modifiers_state[0x45];
1487
            switch (keycode) {
1488
            case 0x2a:                          /* Left Shift */
1489
            case 0x36:                          /* Right Shift */
1490
            case 0x1d:                          /* Left CTRL */
1491
            case 0x9d:                          /* Right CTRL */
1492
            case 0x38:                          /* Left ALT */
1493
            case 0xb8:                          /* Right ALT */
1494
                break;
1495
            case 0xc8:
1496
                kbd_put_keysym(QEMU_KEY_UP);
1497
                break;
1498
            case 0xd0:
1499
                kbd_put_keysym(QEMU_KEY_DOWN);
1500
                break;
1501
            case 0xcb:
1502
                kbd_put_keysym(QEMU_KEY_LEFT);
1503
                break;
1504
            case 0xcd:
1505
                kbd_put_keysym(QEMU_KEY_RIGHT);
1506
                break;
1507
            case 0xd3:
1508
                kbd_put_keysym(QEMU_KEY_DELETE);
1509
                break;
1510
            case 0xc7:
1511
                kbd_put_keysym(QEMU_KEY_HOME);
1512
                break;
1513
            case 0xcf:
1514
                kbd_put_keysym(QEMU_KEY_END);
1515
                break;
1516
            case 0xc9:
1517
                kbd_put_keysym(QEMU_KEY_PAGEUP);
1518
                break;
1519
            case 0xd1:
1520
                kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1521
                break;
1522

    
1523
            case 0x47:
1524
                kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
1525
                break;
1526
            case 0x48:
1527
                kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
1528
                break;
1529
            case 0x49:
1530
                kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
1531
                break;
1532
            case 0x4b:
1533
                kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
1534
                break;
1535
            case 0x4c:
1536
                kbd_put_keysym('5');
1537
                break;
1538
            case 0x4d:
1539
                kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
1540
                break;
1541
            case 0x4f:
1542
                kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
1543
                break;
1544
            case 0x50:
1545
                kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
1546
                break;
1547
            case 0x51:
1548
                kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
1549
                break;
1550
            case 0x52:
1551
                kbd_put_keysym('0');
1552
                break;
1553
            case 0x53:
1554
                kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
1555
                break;
1556

    
1557
            case 0xb5:
1558
                kbd_put_keysym('/');
1559
                break;
1560
            case 0x37:
1561
                kbd_put_keysym('*');
1562
                break;
1563
            case 0x4a:
1564
                kbd_put_keysym('-');
1565
                break;
1566
            case 0x4e:
1567
                kbd_put_keysym('+');
1568
                break;
1569
            case 0x9c:
1570
                kbd_put_keysym('\n');
1571
                break;
1572

    
1573
            default:
1574
                kbd_put_keysym(sym);
1575
                break;
1576
            }
1577
        }
1578
    }
1579
}
1580

    
1581
static void key_event(VncState *vs, int down, uint32_t sym)
1582
{
1583
    int keycode;
1584
    int lsym = sym;
1585

    
1586
    if (lsym >= 'A' && lsym <= 'Z' && is_graphic_console()) {
1587
        lsym = lsym - 'A' + 'a';
1588
    }
1589

    
1590
    keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF) & SCANCODE_KEYMASK;
1591
    do_key_event(vs, down, keycode, sym);
1592
}
1593

    
1594
static void ext_key_event(VncState *vs, int down,
1595
                          uint32_t sym, uint16_t keycode)
1596
{
1597
    /* if the user specifies a keyboard layout, always use it */
1598
    if (keyboard_layout)
1599
        key_event(vs, down, sym);
1600
    else
1601
        do_key_event(vs, down, keycode, sym);
1602
}
1603

    
1604
static void framebuffer_update_request(VncState *vs, int incremental,
1605
                                       int x_position, int y_position,
1606
                                       int w, int h)
1607
{
1608
    if (y_position > ds_get_height(vs->ds))
1609
        y_position = ds_get_height(vs->ds);
1610
    if (y_position + h >= ds_get_height(vs->ds))
1611
        h = ds_get_height(vs->ds) - y_position;
1612

    
1613
    int i;
1614
    vs->need_update = 1;
1615
    if (!incremental) {
1616
        vs->force_update = 1;
1617
        for (i = 0; i < h; i++) {
1618
            vnc_set_bits(vs->dirty[y_position + i],
1619
                         (ds_get_width(vs->ds) / 16), VNC_DIRTY_WORDS);
1620
        }
1621
    }
1622
}
1623

    
1624
static void send_ext_key_event_ack(VncState *vs)
1625
{
1626
    vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1627
    vnc_write_u8(vs, 0);
1628
    vnc_write_u16(vs, 1);
1629
    vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1630
                           VNC_ENCODING_EXT_KEY_EVENT);
1631
    vnc_flush(vs);
1632
}
1633

    
1634
static void send_ext_audio_ack(VncState *vs)
1635
{
1636
    vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1637
    vnc_write_u8(vs, 0);
1638
    vnc_write_u16(vs, 1);
1639
    vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1640
                           VNC_ENCODING_AUDIO);
1641
    vnc_flush(vs);
1642
}
1643

    
1644
static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
1645
{
1646
    int i;
1647
    unsigned int enc = 0;
1648

    
1649
    vs->features = 0;
1650
    vs->vnc_encoding = 0;
1651
    vs->tight_compression = 9;
1652
    vs->tight_quality = 9;
1653
    vs->absolute = -1;
1654

    
1655
    /*
1656
     * Start from the end because the encodings are sent in order of preference.
1657
     * This way the prefered encoding (first encoding defined in the array)
1658
     * will be set at the end of the loop.
1659
     */
1660
    for (i = n_encodings - 1; i >= 0; i--) {
1661
        enc = encodings[i];
1662
        switch (enc) {
1663
        case VNC_ENCODING_RAW:
1664
            vs->vnc_encoding = enc;
1665
            break;
1666
        case VNC_ENCODING_COPYRECT:
1667
            vs->features |= VNC_FEATURE_COPYRECT_MASK;
1668
            break;
1669
        case VNC_ENCODING_HEXTILE:
1670
            vs->features |= VNC_FEATURE_HEXTILE_MASK;
1671
            vs->vnc_encoding = enc;
1672
            break;
1673
        case VNC_ENCODING_ZLIB:
1674
            vs->features |= VNC_FEATURE_ZLIB_MASK;
1675
            vs->vnc_encoding = enc;
1676
            break;
1677
        case VNC_ENCODING_DESKTOPRESIZE:
1678
            vs->features |= VNC_FEATURE_RESIZE_MASK;
1679
            break;
1680
        case VNC_ENCODING_POINTER_TYPE_CHANGE:
1681
            vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
1682
            break;
1683
        case VNC_ENCODING_RICH_CURSOR:
1684
            vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
1685
            break;
1686
        case VNC_ENCODING_EXT_KEY_EVENT:
1687
            send_ext_key_event_ack(vs);
1688
            break;
1689
        case VNC_ENCODING_AUDIO:
1690
            send_ext_audio_ack(vs);
1691
            break;
1692
        case VNC_ENCODING_WMVi:
1693
            vs->features |= VNC_FEATURE_WMVI_MASK;
1694
            break;
1695
        case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
1696
            vs->tight_compression = (enc & 0x0F);
1697
            break;
1698
        case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
1699
            vs->tight_quality = (enc & 0x0F);
1700
            break;
1701
        default:
1702
            VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
1703
            break;
1704
        }
1705
    }
1706
    check_pointer_type_change(&vs->mouse_mode_notifier);
1707
}
1708

    
1709
static void set_pixel_conversion(VncState *vs)
1710
{
1711
    if ((vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) ==
1712
        (vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG) && 
1713
        !memcmp(&(vs->clientds.pf), &(vs->ds->surface->pf), sizeof(PixelFormat))) {
1714
        vs->write_pixels = vnc_write_pixels_copy;
1715
        vnc_hextile_set_pixel_conversion(vs, 0);
1716
    } else {
1717
        vs->write_pixels = vnc_write_pixels_generic;
1718
        vnc_hextile_set_pixel_conversion(vs, 1);
1719
    }
1720
}
1721

    
1722
static void set_pixel_format(VncState *vs,
1723
                             int bits_per_pixel, int depth,
1724
                             int big_endian_flag, int true_color_flag,
1725
                             int red_max, int green_max, int blue_max,
1726
                             int red_shift, int green_shift, int blue_shift)
1727
{
1728
    if (!true_color_flag) {
1729
        vnc_client_error(vs);
1730
        return;
1731
    }
1732

    
1733
    vs->clientds = *(vs->vd->guest.ds);
1734
    vs->clientds.pf.rmax = red_max;
1735
    count_bits(vs->clientds.pf.rbits, red_max);
1736
    vs->clientds.pf.rshift = red_shift;
1737
    vs->clientds.pf.rmask = red_max << red_shift;
1738
    vs->clientds.pf.gmax = green_max;
1739
    count_bits(vs->clientds.pf.gbits, green_max);
1740
    vs->clientds.pf.gshift = green_shift;
1741
    vs->clientds.pf.gmask = green_max << green_shift;
1742
    vs->clientds.pf.bmax = blue_max;
1743
    count_bits(vs->clientds.pf.bbits, blue_max);
1744
    vs->clientds.pf.bshift = blue_shift;
1745
    vs->clientds.pf.bmask = blue_max << blue_shift;
1746
    vs->clientds.pf.bits_per_pixel = bits_per_pixel;
1747
    vs->clientds.pf.bytes_per_pixel = bits_per_pixel / 8;
1748
    vs->clientds.pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
1749
    vs->clientds.flags = big_endian_flag ? QEMU_BIG_ENDIAN_FLAG : 0x00;
1750

    
1751
    set_pixel_conversion(vs);
1752

    
1753
    vga_hw_invalidate();
1754
    vga_hw_update();
1755
}
1756

    
1757
static void pixel_format_message (VncState *vs) {
1758
    char pad[3] = { 0, 0, 0 };
1759

    
1760
    vnc_write_u8(vs, vs->ds->surface->pf.bits_per_pixel); /* bits-per-pixel */
1761
    vnc_write_u8(vs, vs->ds->surface->pf.depth); /* depth */
1762

    
1763
#ifdef HOST_WORDS_BIGENDIAN
1764
    vnc_write_u8(vs, 1);             /* big-endian-flag */
1765
#else
1766
    vnc_write_u8(vs, 0);             /* big-endian-flag */
1767
#endif
1768
    vnc_write_u8(vs, 1);             /* true-color-flag */
1769
    vnc_write_u16(vs, vs->ds->surface->pf.rmax);     /* red-max */
1770
    vnc_write_u16(vs, vs->ds->surface->pf.gmax);     /* green-max */
1771
    vnc_write_u16(vs, vs->ds->surface->pf.bmax);     /* blue-max */
1772
    vnc_write_u8(vs, vs->ds->surface->pf.rshift);    /* red-shift */
1773
    vnc_write_u8(vs, vs->ds->surface->pf.gshift);    /* green-shift */
1774
    vnc_write_u8(vs, vs->ds->surface->pf.bshift);    /* blue-shift */
1775

    
1776
    vnc_hextile_set_pixel_conversion(vs, 0);
1777

    
1778
    vs->clientds = *(vs->ds->surface);
1779
    vs->clientds.flags &= ~QEMU_ALLOCATED_FLAG;
1780
    vs->write_pixels = vnc_write_pixels_copy;
1781

    
1782
    vnc_write(vs, pad, 3);           /* padding */
1783
}
1784

    
1785
static void vnc_dpy_setdata(DisplayState *ds)
1786
{
1787
    /* We don't have to do anything */
1788
}
1789

    
1790
static void vnc_colordepth(VncState *vs)
1791
{
1792
    if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
1793
        /* Sending a WMVi message to notify the client*/
1794
        vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
1795
        vnc_write_u8(vs, 0);
1796
        vnc_write_u16(vs, 1); /* number of rects */
1797
        vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), 
1798
                               ds_get_height(vs->ds), VNC_ENCODING_WMVi);
1799
        pixel_format_message(vs);
1800
        vnc_flush(vs);
1801
    } else {
1802
        set_pixel_conversion(vs);
1803
    }
1804
}
1805

    
1806
static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
1807
{
1808
    int i;
1809
    uint16_t limit;
1810
    VncDisplay *vd = vs->vd;
1811

    
1812
    if (data[0] > 3) {
1813
        vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
1814
        if (!qemu_timer_expired(vd->timer, qemu_get_clock(rt_clock) + vd->timer_interval))
1815
            qemu_mod_timer(vd->timer, qemu_get_clock(rt_clock) + vd->timer_interval);
1816
    }
1817

    
1818
    switch (data[0]) {
1819
    case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
1820
        if (len == 1)
1821
            return 20;
1822

    
1823
        set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
1824
                         read_u8(data, 6), read_u8(data, 7),
1825
                         read_u16(data, 8), read_u16(data, 10),
1826
                         read_u16(data, 12), read_u8(data, 14),
1827
                         read_u8(data, 15), read_u8(data, 16));
1828
        break;
1829
    case VNC_MSG_CLIENT_SET_ENCODINGS:
1830
        if (len == 1)
1831
            return 4;
1832

    
1833
        if (len == 4) {
1834
            limit = read_u16(data, 2);
1835
            if (limit > 0)
1836
                return 4 + (limit * 4);
1837
        } else
1838
            limit = read_u16(data, 2);
1839

    
1840
        for (i = 0; i < limit; i++) {
1841
            int32_t val = read_s32(data, 4 + (i * 4));
1842
            memcpy(data + 4 + (i * 4), &val, sizeof(val));
1843
        }
1844

    
1845
        set_encodings(vs, (int32_t *)(data + 4), limit);
1846
        break;
1847
    case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
1848
        if (len == 1)
1849
            return 10;
1850

    
1851
        framebuffer_update_request(vs,
1852
                                   read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
1853
                                   read_u16(data, 6), read_u16(data, 8));
1854
        break;
1855
    case VNC_MSG_CLIENT_KEY_EVENT:
1856
        if (len == 1)
1857
            return 8;
1858

    
1859
        key_event(vs, read_u8(data, 1), read_u32(data, 4));
1860
        break;
1861
    case VNC_MSG_CLIENT_POINTER_EVENT:
1862
        if (len == 1)
1863
            return 6;
1864

    
1865
        pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
1866
        break;
1867
    case VNC_MSG_CLIENT_CUT_TEXT:
1868
        if (len == 1)
1869
            return 8;
1870

    
1871
        if (len == 8) {
1872
            uint32_t dlen = read_u32(data, 4);
1873
            if (dlen > 0)
1874
                return 8 + dlen;
1875
        }
1876

    
1877
        client_cut_text(vs, read_u32(data, 4), data + 8);
1878
        break;
1879
    case VNC_MSG_CLIENT_QEMU:
1880
        if (len == 1)
1881
            return 2;
1882

    
1883
        switch (read_u8(data, 1)) {
1884
        case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
1885
            if (len == 2)
1886
                return 12;
1887

    
1888
            ext_key_event(vs, read_u16(data, 2),
1889
                          read_u32(data, 4), read_u32(data, 8));
1890
            break;
1891
        case VNC_MSG_CLIENT_QEMU_AUDIO:
1892
            if (len == 2)
1893
                return 4;
1894

    
1895
            switch (read_u16 (data, 2)) {
1896
            case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
1897
                audio_add(vs);
1898
                break;
1899
            case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
1900
                audio_del(vs);
1901
                break;
1902
            case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
1903
                if (len == 4)
1904
                    return 10;
1905
                switch (read_u8(data, 4)) {
1906
                case 0: vs->as.fmt = AUD_FMT_U8; break;
1907
                case 1: vs->as.fmt = AUD_FMT_S8; break;
1908
                case 2: vs->as.fmt = AUD_FMT_U16; break;
1909
                case 3: vs->as.fmt = AUD_FMT_S16; break;
1910
                case 4: vs->as.fmt = AUD_FMT_U32; break;
1911
                case 5: vs->as.fmt = AUD_FMT_S32; break;
1912
                default:
1913
                    printf("Invalid audio format %d\n", read_u8(data, 4));
1914
                    vnc_client_error(vs);
1915
                    break;
1916
                }
1917
                vs->as.nchannels = read_u8(data, 5);
1918
                if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
1919
                    printf("Invalid audio channel coount %d\n",
1920
                           read_u8(data, 5));
1921
                    vnc_client_error(vs);
1922
                    break;
1923
                }
1924
                vs->as.freq = read_u32(data, 6);
1925
                break;
1926
            default:
1927
                printf ("Invalid audio message %d\n", read_u8(data, 4));
1928
                vnc_client_error(vs);
1929
                break;
1930
            }
1931
            break;
1932

    
1933
        default:
1934
            printf("Msg: %d\n", read_u16(data, 0));
1935
            vnc_client_error(vs);
1936
            break;
1937
        }
1938
        break;
1939
    default:
1940
        printf("Msg: %d\n", data[0]);
1941
        vnc_client_error(vs);
1942
        break;
1943
    }
1944

    
1945
    vnc_read_when(vs, protocol_client_msg, 1);
1946
    return 0;
1947
}
1948

    
1949
static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
1950
{
1951
    char buf[1024];
1952
    int size;
1953

    
1954
    vnc_write_u16(vs, ds_get_width(vs->ds));
1955
    vnc_write_u16(vs, ds_get_height(vs->ds));
1956

    
1957
    pixel_format_message(vs);
1958

    
1959
    if (qemu_name)
1960
        size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
1961
    else
1962
        size = snprintf(buf, sizeof(buf), "QEMU");
1963

    
1964
    vnc_write_u32(vs, size);
1965
    vnc_write(vs, buf, size);
1966
    vnc_flush(vs);
1967

    
1968
    vnc_client_cache_auth(vs);
1969
    vnc_qmp_event(vs, QEVENT_VNC_INITIALIZED);
1970

    
1971
    vnc_read_when(vs, protocol_client_msg, 1);
1972

    
1973
    return 0;
1974
}
1975

    
1976
void start_client_init(VncState *vs)
1977
{
1978
    vnc_read_when(vs, protocol_client_init, 1);
1979
}
1980

    
1981
static void make_challenge(VncState *vs)
1982
{
1983
    int i;
1984

    
1985
    srand(time(NULL)+getpid()+getpid()*987654+rand());
1986

    
1987
    for (i = 0 ; i < sizeof(vs->challenge) ; i++)
1988
        vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
1989
}
1990

    
1991
static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
1992
{
1993
    unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
1994
    int i, j, pwlen;
1995
    unsigned char key[8];
1996

    
1997
    if (!vs->vd->password || !vs->vd->password[0]) {
1998
        VNC_DEBUG("No password configured on server");
1999
        vnc_write_u32(vs, 1); /* Reject auth */
2000
        if (vs->minor >= 8) {
2001
            static const char err[] = "Authentication failed";
2002
            vnc_write_u32(vs, sizeof(err));
2003
            vnc_write(vs, err, sizeof(err));
2004
        }
2005
        vnc_flush(vs);
2006
        vnc_client_error(vs);
2007
        return 0;
2008
    }
2009

    
2010
    memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
2011

    
2012
    /* Calculate the expected challenge response */
2013
    pwlen = strlen(vs->vd->password);
2014
    for (i=0; i<sizeof(key); i++)
2015
        key[i] = i<pwlen ? vs->vd->password[i] : 0;
2016
    deskey(key, EN0);
2017
    for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
2018
        des(response+j, response+j);
2019

    
2020
    /* Compare expected vs actual challenge response */
2021
    if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
2022
        VNC_DEBUG("Client challenge reponse did not match\n");
2023
        vnc_write_u32(vs, 1); /* Reject auth */
2024
        if (vs->minor >= 8) {
2025
            static const char err[] = "Authentication failed";
2026
            vnc_write_u32(vs, sizeof(err));
2027
            vnc_write(vs, err, sizeof(err));
2028
        }
2029
        vnc_flush(vs);
2030
        vnc_client_error(vs);
2031
    } else {
2032
        VNC_DEBUG("Accepting VNC challenge response\n");
2033
        vnc_write_u32(vs, 0); /* Accept auth */
2034
        vnc_flush(vs);
2035

    
2036
        start_client_init(vs);
2037
    }
2038
    return 0;
2039
}
2040

    
2041
void start_auth_vnc(VncState *vs)
2042
{
2043
    make_challenge(vs);
2044
    /* Send client a 'random' challenge */
2045
    vnc_write(vs, vs->challenge, sizeof(vs->challenge));
2046
    vnc_flush(vs);
2047

    
2048
    vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
2049
}
2050

    
2051

    
2052
static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
2053
{
2054
    /* We only advertise 1 auth scheme at a time, so client
2055
     * must pick the one we sent. Verify this */
2056
    if (data[0] != vs->vd->auth) { /* Reject auth */
2057
       VNC_DEBUG("Reject auth %d because it didn't match advertized\n", (int)data[0]);
2058
       vnc_write_u32(vs, 1);
2059
       if (vs->minor >= 8) {
2060
           static const char err[] = "Authentication failed";
2061
           vnc_write_u32(vs, sizeof(err));
2062
           vnc_write(vs, err, sizeof(err));
2063
       }
2064
       vnc_client_error(vs);
2065
    } else { /* Accept requested auth */
2066
       VNC_DEBUG("Client requested auth %d\n", (int)data[0]);
2067
       switch (vs->vd->auth) {
2068
       case VNC_AUTH_NONE:
2069
           VNC_DEBUG("Accept auth none\n");
2070
           if (vs->minor >= 8) {
2071
               vnc_write_u32(vs, 0); /* Accept auth completion */
2072
               vnc_flush(vs);
2073
           }
2074
           start_client_init(vs);
2075
           break;
2076

    
2077
       case VNC_AUTH_VNC:
2078
           VNC_DEBUG("Start VNC auth\n");
2079
           start_auth_vnc(vs);
2080
           break;
2081

    
2082
#ifdef CONFIG_VNC_TLS
2083
       case VNC_AUTH_VENCRYPT:
2084
           VNC_DEBUG("Accept VeNCrypt auth\n");;
2085
           start_auth_vencrypt(vs);
2086
           break;
2087
#endif /* CONFIG_VNC_TLS */
2088

    
2089
#ifdef CONFIG_VNC_SASL
2090
       case VNC_AUTH_SASL:
2091
           VNC_DEBUG("Accept SASL auth\n");
2092
           start_auth_sasl(vs);
2093
           break;
2094
#endif /* CONFIG_VNC_SASL */
2095

    
2096
       default: /* Should not be possible, but just in case */
2097
           VNC_DEBUG("Reject auth %d server code bug\n", vs->vd->auth);
2098
           vnc_write_u8(vs, 1);
2099
           if (vs->minor >= 8) {
2100
               static const char err[] = "Authentication failed";
2101
               vnc_write_u32(vs, sizeof(err));
2102
               vnc_write(vs, err, sizeof(err));
2103
           }
2104
           vnc_client_error(vs);
2105
       }
2106
    }
2107
    return 0;
2108
}
2109

    
2110
static int protocol_version(VncState *vs, uint8_t *version, size_t len)
2111
{
2112
    char local[13];
2113

    
2114
    memcpy(local, version, 12);
2115
    local[12] = 0;
2116

    
2117
    if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2118
        VNC_DEBUG("Malformed protocol version %s\n", local);
2119
        vnc_client_error(vs);
2120
        return 0;
2121
    }
2122
    VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2123
    if (vs->major != 3 ||
2124
        (vs->minor != 3 &&
2125
         vs->minor != 4 &&
2126
         vs->minor != 5 &&
2127
         vs->minor != 7 &&
2128
         vs->minor != 8)) {
2129
        VNC_DEBUG("Unsupported client version\n");
2130
        vnc_write_u32(vs, VNC_AUTH_INVALID);
2131
        vnc_flush(vs);
2132
        vnc_client_error(vs);
2133
        return 0;
2134
    }
2135
    /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2136
     * as equivalent to v3.3 by servers
2137
     */
2138
    if (vs->minor == 4 || vs->minor == 5)
2139
        vs->minor = 3;
2140

    
2141
    if (vs->minor == 3) {
2142
        if (vs->vd->auth == VNC_AUTH_NONE) {
2143
            VNC_DEBUG("Tell client auth none\n");
2144
            vnc_write_u32(vs, vs->vd->auth);
2145
            vnc_flush(vs);
2146
            start_client_init(vs);
2147
       } else if (vs->vd->auth == VNC_AUTH_VNC) {
2148
            VNC_DEBUG("Tell client VNC auth\n");
2149
            vnc_write_u32(vs, vs->vd->auth);
2150
            vnc_flush(vs);
2151
            start_auth_vnc(vs);
2152
       } else {
2153
            VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->vd->auth);
2154
            vnc_write_u32(vs, VNC_AUTH_INVALID);
2155
            vnc_flush(vs);
2156
            vnc_client_error(vs);
2157
       }
2158
    } else {
2159
        VNC_DEBUG("Telling client we support auth %d\n", vs->vd->auth);
2160
        vnc_write_u8(vs, 1); /* num auth */
2161
        vnc_write_u8(vs, vs->vd->auth);
2162
        vnc_read_when(vs, protocol_client_auth, 1);
2163
        vnc_flush(vs);
2164
    }
2165

    
2166
    return 0;
2167
}
2168

    
2169
static int vnc_refresh_server_surface(VncDisplay *vd)
2170
{
2171
    int y;
2172
    uint8_t *guest_row;
2173
    uint8_t *server_row;
2174
    int cmp_bytes;
2175
    uint32_t width_mask[VNC_DIRTY_WORDS];
2176
    VncState *vs;
2177
    int has_dirty = 0;
2178

    
2179
    /*
2180
     * Walk through the guest dirty map.
2181
     * Check and copy modified bits from guest to server surface.
2182
     * Update server dirty map.
2183
     */
2184
    vnc_set_bits(width_mask, (ds_get_width(vd->ds) / 16), VNC_DIRTY_WORDS);
2185
    cmp_bytes = 16 * ds_get_bytes_per_pixel(vd->ds);
2186
    guest_row  = vd->guest.ds->data;
2187
    server_row = vd->server->data;
2188
    for (y = 0; y < vd->guest.ds->height; y++) {
2189
        if (vnc_and_bits(vd->guest.dirty[y], width_mask, VNC_DIRTY_WORDS)) {
2190
            int x;
2191
            uint8_t *guest_ptr;
2192
            uint8_t *server_ptr;
2193

    
2194
            guest_ptr  = guest_row;
2195
            server_ptr = server_row;
2196

    
2197
            for (x = 0; x < vd->guest.ds->width;
2198
                    x += 16, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
2199
                if (!vnc_get_bit(vd->guest.dirty[y], (x / 16)))
2200
                    continue;
2201
                vnc_clear_bit(vd->guest.dirty[y], (x / 16));
2202
                if (memcmp(server_ptr, guest_ptr, cmp_bytes) == 0)
2203
                    continue;
2204
                memcpy(server_ptr, guest_ptr, cmp_bytes);
2205
                QTAILQ_FOREACH(vs, &vd->clients, next) {
2206
                    vnc_set_bit(vs->dirty[y], (x / 16));
2207
                }
2208
                has_dirty++;
2209
            }
2210
        }
2211
        guest_row  += ds_get_linesize(vd->ds);
2212
        server_row += ds_get_linesize(vd->ds);
2213
    }
2214
    return has_dirty;
2215
}
2216

    
2217
static void vnc_refresh(void *opaque)
2218
{
2219
    VncDisplay *vd = opaque;
2220
    VncState *vs, *vn;
2221
    int has_dirty, rects = 0;
2222

    
2223
    vga_hw_update();
2224

    
2225
    has_dirty = vnc_refresh_server_surface(vd);
2226

    
2227
    QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
2228
        rects += vnc_update_client(vs, has_dirty);
2229
        /* vs might be free()ed here */
2230
    }
2231
    /* vd->timer could be NULL now if the last client disconnected,
2232
     * in this case don't update the timer */
2233
    if (vd->timer == NULL)
2234
        return;
2235

    
2236
    if (has_dirty && rects) {
2237
        vd->timer_interval /= 2;
2238
        if (vd->timer_interval < VNC_REFRESH_INTERVAL_BASE)
2239
            vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
2240
    } else {
2241
        vd->timer_interval += VNC_REFRESH_INTERVAL_INC;
2242
        if (vd->timer_interval > VNC_REFRESH_INTERVAL_MAX)
2243
            vd->timer_interval = VNC_REFRESH_INTERVAL_MAX;
2244
    }
2245
    qemu_mod_timer(vd->timer, qemu_get_clock(rt_clock) + vd->timer_interval);
2246
}
2247

    
2248
static void vnc_init_timer(VncDisplay *vd)
2249
{
2250
    vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
2251
    if (vd->timer == NULL && !QTAILQ_EMPTY(&vd->clients)) {
2252
        vd->timer = qemu_new_timer(rt_clock, vnc_refresh, vd);
2253
        vnc_refresh(vd);
2254
    }
2255
}
2256

    
2257
static void vnc_remove_timer(VncDisplay *vd)
2258
{
2259
    if (vd->timer != NULL && QTAILQ_EMPTY(&vd->clients)) {
2260
        qemu_del_timer(vd->timer);
2261
        qemu_free_timer(vd->timer);
2262
        vd->timer = NULL;
2263
    }
2264
}
2265

    
2266
static void vnc_connect(VncDisplay *vd, int csock)
2267
{
2268
    VncState *vs = qemu_mallocz(sizeof(VncState));
2269
    vs->csock = csock;
2270

    
2271
    VNC_DEBUG("New client on socket %d\n", csock);
2272
    dcl->idle = 0;
2273
    socket_set_nonblock(vs->csock);
2274
    qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
2275

    
2276
    vnc_client_cache_addr(vs);
2277
    vnc_qmp_event(vs, QEVENT_VNC_CONNECTED);
2278

    
2279
    vs->vd = vd;
2280
    vs->ds = vd->ds;
2281
    vs->last_x = -1;
2282
    vs->last_y = -1;
2283

    
2284
    vs->as.freq = 44100;
2285
    vs->as.nchannels = 2;
2286
    vs->as.fmt = AUD_FMT_S16;
2287
    vs->as.endianness = 0;
2288

    
2289
    QTAILQ_INSERT_HEAD(&vd->clients, vs, next);
2290

    
2291
    vga_hw_update();
2292

    
2293
    vnc_write(vs, "RFB 003.008\n", 12);
2294
    vnc_flush(vs);
2295
    vnc_read_when(vs, protocol_version, 12);
2296
    reset_keys(vs);
2297
    if (vs->vd->lock_key_sync)
2298
        vs->led = qemu_add_led_event_handler(kbd_leds, vs);
2299

    
2300
    vs->mouse_mode_notifier.notify = check_pointer_type_change;
2301
    qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
2302

    
2303
    vnc_init_timer(vd);
2304

    
2305
    /* vs might be free()ed here */
2306
}
2307

    
2308
static void vnc_listen_read(void *opaque)
2309
{
2310
    VncDisplay *vs = opaque;
2311
    struct sockaddr_in addr;
2312
    socklen_t addrlen = sizeof(addr);
2313

    
2314
    /* Catch-up */
2315
    vga_hw_update();
2316

    
2317
    int csock = qemu_accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
2318
    if (csock != -1) {
2319
        vnc_connect(vs, csock);
2320
    }
2321
}
2322

    
2323
void vnc_display_init(DisplayState *ds)
2324
{
2325
    VncDisplay *vs = qemu_mallocz(sizeof(*vs));
2326

    
2327
    dcl = qemu_mallocz(sizeof(DisplayChangeListener));
2328

    
2329
    ds->opaque = vs;
2330
    dcl->idle = 1;
2331
    vnc_display = vs;
2332

    
2333
    vs->lsock = -1;
2334

    
2335
    vs->ds = ds;
2336
    QTAILQ_INIT(&vs->clients);
2337

    
2338
    if (keyboard_layout)
2339
        vs->kbd_layout = init_keyboard_layout(name2keysym, keyboard_layout);
2340
    else
2341
        vs->kbd_layout = init_keyboard_layout(name2keysym, "en-us");
2342

    
2343
    if (!vs->kbd_layout)
2344
        exit(1);
2345

    
2346
    dcl->dpy_copy = vnc_dpy_copy;
2347
    dcl->dpy_update = vnc_dpy_update;
2348
    dcl->dpy_resize = vnc_dpy_resize;
2349
    dcl->dpy_setdata = vnc_dpy_setdata;
2350
    register_displaychangelistener(ds, dcl);
2351
    ds->mouse_set = vnc_mouse_set;
2352
    ds->cursor_define = vnc_dpy_cursor_define;
2353
}
2354

    
2355

    
2356
void vnc_display_close(DisplayState *ds)
2357
{
2358
    VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2359

    
2360
    if (!vs)
2361
        return;
2362
    if (vs->display) {
2363
        qemu_free(vs->display);
2364
        vs->display = NULL;
2365
    }
2366
    if (vs->lsock != -1) {
2367
        qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);
2368
        close(vs->lsock);
2369
        vs->lsock = -1;
2370
    }
2371
    vs->auth = VNC_AUTH_INVALID;
2372
#ifdef CONFIG_VNC_TLS
2373
    vs->subauth = VNC_AUTH_INVALID;
2374
    vs->tls.x509verify = 0;
2375
#endif
2376
}
2377

    
2378
int vnc_display_password(DisplayState *ds, const char *password)
2379
{
2380
    VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2381

    
2382
    if (!vs) {
2383
        return -1;
2384
    }
2385

    
2386
    if (vs->password) {
2387
        qemu_free(vs->password);
2388
        vs->password = NULL;
2389
    }
2390
    if (password && password[0]) {
2391
        if (!(vs->password = qemu_strdup(password)))
2392
            return -1;
2393
        if (vs->auth == VNC_AUTH_NONE) {
2394
            vs->auth = VNC_AUTH_VNC;
2395
        }
2396
    } else {
2397
        vs->auth = VNC_AUTH_NONE;
2398
    }
2399

    
2400
    return 0;
2401
}
2402

    
2403
char *vnc_display_local_addr(DisplayState *ds)
2404
{
2405
    VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2406
    
2407
    return vnc_socket_local_addr("%s:%s", vs->lsock);
2408
}
2409

    
2410
int vnc_display_open(DisplayState *ds, const char *display)
2411
{
2412
    VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2413
    const char *options;
2414
    int password = 0;
2415
    int reverse = 0;
2416
#ifdef CONFIG_VNC_TLS
2417
    int tls = 0, x509 = 0;
2418
#endif
2419
#ifdef CONFIG_VNC_SASL
2420
    int sasl = 0;
2421
    int saslErr;
2422
#endif
2423
    int acl = 0;
2424
    int lock_key_sync = 1;
2425

    
2426
    if (!vnc_display)
2427
        return -1;
2428
    vnc_display_close(ds);
2429
    if (strcmp(display, "none") == 0)
2430
        return 0;
2431

    
2432
    if (!(vs->display = strdup(display)))
2433
        return -1;
2434

    
2435
    options = display;
2436
    while ((options = strchr(options, ','))) {
2437
        options++;
2438
        if (strncmp(options, "password", 8) == 0) {
2439
            password = 1; /* Require password auth */
2440
        } else if (strncmp(options, "reverse", 7) == 0) {
2441
            reverse = 1;
2442
        } else if (strncmp(options, "no-lock-key-sync", 9) == 0) {
2443
            lock_key_sync = 0;
2444
#ifdef CONFIG_VNC_SASL
2445
        } else if (strncmp(options, "sasl", 4) == 0) {
2446
            sasl = 1; /* Require SASL auth */
2447
#endif
2448
#ifdef CONFIG_VNC_TLS
2449
        } else if (strncmp(options, "tls", 3) == 0) {
2450
            tls = 1; /* Require TLS */
2451
        } else if (strncmp(options, "x509", 4) == 0) {
2452
            char *start, *end;
2453
            x509 = 1; /* Require x509 certificates */
2454
            if (strncmp(options, "x509verify", 10) == 0)
2455
                vs->tls.x509verify = 1; /* ...and verify client certs */
2456

    
2457
            /* Now check for 'x509=/some/path' postfix
2458
             * and use that to setup x509 certificate/key paths */
2459
            start = strchr(options, '=');
2460
            end = strchr(options, ',');
2461
            if (start && (!end || (start < end))) {
2462
                int len = end ? end-(start+1) : strlen(start+1);
2463
                char *path = qemu_strndup(start + 1, len);
2464

    
2465
                VNC_DEBUG("Trying certificate path '%s'\n", path);
2466
                if (vnc_tls_set_x509_creds_dir(vs, path) < 0) {
2467
                    fprintf(stderr, "Failed to find x509 certificates/keys in %s\n", path);
2468
                    qemu_free(path);
2469
                    qemu_free(vs->display);
2470
                    vs->display = NULL;
2471
                    return -1;
2472
                }
2473
                qemu_free(path);
2474
            } else {
2475
                fprintf(stderr, "No certificate path provided\n");
2476
                qemu_free(vs->display);
2477
                vs->display = NULL;
2478
                return -1;
2479
            }
2480
#endif
2481
        } else if (strncmp(options, "acl", 3) == 0) {
2482
            acl = 1;
2483
        }
2484
    }
2485

    
2486
#ifdef CONFIG_VNC_TLS
2487
    if (acl && x509 && vs->tls.x509verify) {
2488
        if (!(vs->tls.acl = qemu_acl_init("vnc.x509dname"))) {
2489
            fprintf(stderr, "Failed to create x509 dname ACL\n");
2490
            exit(1);
2491
        }
2492
    }
2493
#endif
2494
#ifdef CONFIG_VNC_SASL
2495
    if (acl && sasl) {
2496
        if (!(vs->sasl.acl = qemu_acl_init("vnc.username"))) {
2497
            fprintf(stderr, "Failed to create username ACL\n");
2498
            exit(1);
2499
        }
2500
    }
2501
#endif
2502

    
2503
    /*
2504
     * Combinations we support here:
2505
     *
2506
     *  - no-auth                (clear text, no auth)
2507
     *  - password               (clear text, weak auth)
2508
     *  - sasl                   (encrypt, good auth *IF* using Kerberos via GSSAPI)
2509
     *  - tls                    (encrypt, weak anonymous creds, no auth)
2510
     *  - tls + password         (encrypt, weak anonymous creds, weak auth)
2511
     *  - tls + sasl             (encrypt, weak anonymous creds, good auth)
2512
     *  - tls + x509             (encrypt, good x509 creds, no auth)
2513
     *  - tls + x509 + password  (encrypt, good x509 creds, weak auth)
2514
     *  - tls + x509 + sasl      (encrypt, good x509 creds, good auth)
2515
     *
2516
     * NB1. TLS is a stackable auth scheme.
2517
     * NB2. the x509 schemes have option to validate a client cert dname
2518
     */
2519
    if (password) {
2520
#ifdef CONFIG_VNC_TLS
2521
        if (tls) {
2522
            vs->auth = VNC_AUTH_VENCRYPT;
2523
            if (x509) {
2524
                VNC_DEBUG("Initializing VNC server with x509 password auth\n");
2525
                vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;
2526
            } else {
2527
                VNC_DEBUG("Initializing VNC server with TLS password auth\n");
2528
                vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
2529
            }
2530
        } else {
2531
#endif /* CONFIG_VNC_TLS */
2532
            VNC_DEBUG("Initializing VNC server with password auth\n");
2533
            vs->auth = VNC_AUTH_VNC;
2534
#ifdef CONFIG_VNC_TLS
2535
            vs->subauth = VNC_AUTH_INVALID;
2536
        }
2537
#endif /* CONFIG_VNC_TLS */
2538
#ifdef CONFIG_VNC_SASL
2539
    } else if (sasl) {
2540
#ifdef CONFIG_VNC_TLS
2541
        if (tls) {
2542
            vs->auth = VNC_AUTH_VENCRYPT;
2543
            if (x509) {
2544
                VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
2545
                vs->subauth = VNC_AUTH_VENCRYPT_X509SASL;
2546
            } else {
2547
                VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
2548
                vs->subauth = VNC_AUTH_VENCRYPT_TLSSASL;
2549
            }
2550
        } else {
2551
#endif /* CONFIG_VNC_TLS */
2552
            VNC_DEBUG("Initializing VNC server with SASL auth\n");
2553
            vs->auth = VNC_AUTH_SASL;
2554
#ifdef CONFIG_VNC_TLS
2555
            vs->subauth = VNC_AUTH_INVALID;
2556
        }
2557
#endif /* CONFIG_VNC_TLS */
2558
#endif /* CONFIG_VNC_SASL */
2559
    } else {
2560
#ifdef CONFIG_VNC_TLS
2561
        if (tls) {
2562
            vs->auth = VNC_AUTH_VENCRYPT;
2563
            if (x509) {
2564
                VNC_DEBUG("Initializing VNC server with x509 no auth\n");
2565
                vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;
2566
            } else {
2567
                VNC_DEBUG("Initializing VNC server with TLS no auth\n");
2568
                vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
2569
            }
2570
        } else {
2571
#endif
2572
            VNC_DEBUG("Initializing VNC server with no auth\n");
2573
            vs->auth = VNC_AUTH_NONE;
2574
#ifdef CONFIG_VNC_TLS
2575
            vs->subauth = VNC_AUTH_INVALID;
2576
        }
2577
#endif
2578
    }
2579

    
2580
#ifdef CONFIG_VNC_SASL
2581
    if ((saslErr = sasl_server_init(NULL, "qemu")) != SASL_OK) {
2582
        fprintf(stderr, "Failed to initialize SASL auth %s",
2583
                sasl_errstring(saslErr, NULL, NULL));
2584
        free(vs->display);
2585
        vs->display = NULL;
2586
        return -1;
2587
    }
2588
#endif
2589
    vs->lock_key_sync = lock_key_sync;
2590

    
2591
    if (reverse) {
2592
        /* connect to viewer */
2593
        if (strncmp(display, "unix:", 5) == 0)
2594
            vs->lsock = unix_connect(display+5);
2595
        else
2596
            vs->lsock = inet_connect(display, SOCK_STREAM);
2597
        if (-1 == vs->lsock) {
2598
            free(vs->display);
2599
            vs->display = NULL;
2600
            return -1;
2601
        } else {
2602
            int csock = vs->lsock;
2603
            vs->lsock = -1;
2604
            vnc_connect(vs, csock);
2605
        }
2606
        return 0;
2607

    
2608
    } else {
2609
        /* listen for connects */
2610
        char *dpy;
2611
        dpy = qemu_malloc(256);
2612
        if (strncmp(display, "unix:", 5) == 0) {
2613
            pstrcpy(dpy, 256, "unix:");
2614
            vs->lsock = unix_listen(display+5, dpy+5, 256-5);
2615
        } else {
2616
            vs->lsock = inet_listen(display, dpy, 256, SOCK_STREAM, 5900);
2617
        }
2618
        if (-1 == vs->lsock) {
2619
            free(dpy);
2620
            return -1;
2621
        } else {
2622
            free(vs->display);
2623
            vs->display = dpy;
2624
        }
2625
    }
2626
    return qemu_set_fd_handler2(vs->lsock, NULL, vnc_listen_read, NULL, vs);
2627
}