Statistics
| Branch: | Revision:

root / vnc.c @ bca403c8

History | View | Annotate | Download (78.1 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 char *addr_to_string(const char *format,
53
                            struct sockaddr_storage *sa,
54
                            socklen_t salen) {
55
    char *addr;
56
    char host[NI_MAXHOST];
57
    char serv[NI_MAXSERV];
58
    int err;
59
    size_t addrlen;
60

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

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

    
77
    return addr;
78
}
79

    
80

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

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

    
89
    return addr_to_string(format, &sa, salen);
90
}
91

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

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

    
100
    return addr_to_string(format, &sa, salen);
101
}
102

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

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

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

    
123
    return 0;
124
}
125

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

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

    
136
    return put_addr_qdict(qdict, &sa, salen);
137
}
138

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

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

    
149
    return put_addr_qdict(qdict, &sa, salen);
150
}
151

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

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

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

    
213
static void vnc_client_cache_auth(VncState *client)
214
{
215
    QDict *qdict;
216

    
217
    if (!client->info) {
218
        return;
219
    }
220

    
221
    qdict = qobject_to_qdict(client->info);
222

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

    
238
static void vnc_client_cache_addr(VncState *client)
239
{
240
    QDict *qdict;
241

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

    
249
    client->info = QOBJECT(qdict);
250
}
251

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

    
257
    if (!vs->info) {
258
        return;
259
    }
260

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

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

    
270
    monitor_protocol_event(event, data);
271

    
272
    qobject_incref(vs->info);
273
    qobject_decref(data);
274
}
275

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
455
    h += y;
456

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

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

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

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

    
482
    vnc_write_s32(vs, encoding);
483
}
484

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

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

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

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

    
512
void buffer_append(Buffer *buffer, const void *data, size_t len)
513
{
514
    memcpy(buffer->buffer + buffer->offset, data, len);
515
    buffer->offset += len;
516
}
517

    
518
static void vnc_dpy_resize(DisplayState *ds)
519
{
520
    int size_changed;
521
    VncDisplay *vd = ds->opaque;
522
    VncState *vs = vd->clients;
523

    
524
    /* server surface */
525
    if (!vd->server)
526
        vd->server = qemu_mallocz(sizeof(*vd->server));
527
    if (vd->server->data)
528
        qemu_free(vd->server->data);
529
    *(vd->server) = *(ds->surface);
530
    vd->server->data = qemu_mallocz(vd->server->linesize *
531
                                    vd->server->height);
532

    
533
    /* guest surface */
534
    if (!vd->guest.ds)
535
        vd->guest.ds = qemu_mallocz(sizeof(*vd->guest.ds));
536
    if (ds_get_bytes_per_pixel(ds) != vd->guest.ds->pf.bytes_per_pixel)
537
        console_color_init(ds);
538
    size_changed = ds_get_width(ds) != vd->guest.ds->width ||
539
                   ds_get_height(ds) != vd->guest.ds->height;
540
    *(vd->guest.ds) = *(ds->surface);
541
    memset(vd->guest.dirty, 0xFF, sizeof(vd->guest.dirty));
542

    
543
    while (vs != NULL) {
544
        vnc_colordepth(vs);
545
        if (size_changed) {
546
            if (vs->csock != -1 && vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
547
                vnc_write_u8(vs, 0);  /* msg id */
548
                vnc_write_u8(vs, 0);
549
                vnc_write_u16(vs, 1); /* number of rects */
550
                vnc_framebuffer_update(vs, 0, 0, ds_get_width(ds), ds_get_height(ds),
551
                        VNC_ENCODING_DESKTOPRESIZE);
552
                vnc_flush(vs);
553
            }
554
        }
555
        memset(vs->dirty, 0xFF, sizeof(vs->dirty));
556
        vs = vs->next;
557
    }
558
}
559

    
560
/* fastest code */
561
static void vnc_write_pixels_copy(VncState *vs, void *pixels, int size)
562
{
563
    vnc_write(vs, pixels, size);
564
}
565

    
566
/* slowest but generic code. */
567
static void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
568
{
569
    uint8_t r, g, b;
570
    VncDisplay *vd = vs->vd;
571

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

    
611
static void vnc_write_pixels_generic(VncState *vs, void *pixels1, int size)
612
{
613
    uint8_t buf[4];
614
    VncDisplay *vd = vs->vd;
615

    
616
    if (vd->server->pf.bytes_per_pixel == 4) {
617
        uint32_t *pixels = pixels1;
618
        int n, i;
619
        n = size >> 2;
620
        for(i = 0; i < n; i++) {
621
            vnc_convert_pixel(vs, buf, pixels[i]);
622
            vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
623
        }
624
    } else if (vd->server->pf.bytes_per_pixel == 2) {
625
        uint16_t *pixels = pixels1;
626
        int n, i;
627
        n = size >> 1;
628
        for(i = 0; i < n; i++) {
629
            vnc_convert_pixel(vs, buf, pixels[i]);
630
            vnc_write(vs, buf, vs->clientds.pf.bytes_per_pixel);
631
        }
632
    } else if (vd->server->pf.bytes_per_pixel == 1) {
633
        uint8_t *pixels = pixels1;
634
        int n, i;
635
        n = size;
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 {
641
        fprintf(stderr, "vnc_write_pixels_generic: VncState color depth not supported\n");
642
    }
643
}
644

    
645
static void send_framebuffer_update_raw(VncState *vs, int x, int y, int w, int h)
646
{
647
    int i;
648
    uint8_t *row;
649
    VncDisplay *vd = vs->vd;
650

    
651
    row = vd->server->data + y * ds_get_linesize(vs->ds) + x * ds_get_bytes_per_pixel(vs->ds);
652
    for (i = 0; i < h; i++) {
653
        vs->write_pixels(vs, row, w * ds_get_bytes_per_pixel(vs->ds));
654
        row += ds_get_linesize(vs->ds);
655
    }
656
}
657

    
658
static void hextile_enc_cord(uint8_t *ptr, int x, int y, int w, int h)
659
{
660
    ptr[0] = ((x & 0x0F) << 4) | (y & 0x0F);
661
    ptr[1] = (((w - 1) & 0x0F) << 4) | ((h - 1) & 0x0F);
662
}
663

    
664
#define BPP 8
665
#include "vnchextile.h"
666
#undef BPP
667

    
668
#define BPP 16
669
#include "vnchextile.h"
670
#undef BPP
671

    
672
#define BPP 32
673
#include "vnchextile.h"
674
#undef BPP
675

    
676
#define GENERIC
677
#define BPP 8
678
#include "vnchextile.h"
679
#undef BPP
680
#undef GENERIC
681

    
682
#define GENERIC
683
#define BPP 16
684
#include "vnchextile.h"
685
#undef BPP
686
#undef GENERIC
687

    
688
#define GENERIC
689
#define BPP 32
690
#include "vnchextile.h"
691
#undef BPP
692
#undef GENERIC
693

    
694
static void send_framebuffer_update_hextile(VncState *vs, int x, int y, int w, int h)
695
{
696
    int i, j;
697
    int has_fg, has_bg;
698
    uint8_t *last_fg, *last_bg;
699
    VncDisplay *vd = vs->vd;
700

    
701
    last_fg = (uint8_t *) qemu_malloc(vd->server->pf.bytes_per_pixel);
702
    last_bg = (uint8_t *) qemu_malloc(vd->server->pf.bytes_per_pixel);
703
    has_fg = has_bg = 0;
704
    for (j = y; j < (y + h); j += 16) {
705
        for (i = x; i < (x + w); i += 16) {
706
            vs->send_hextile_tile(vs, i, j,
707
                                  MIN(16, x + w - i), MIN(16, y + h - j),
708
                                  last_bg, last_fg, &has_bg, &has_fg);
709
        }
710
    }
711
    free(last_fg);
712
    free(last_bg);
713

    
714
}
715

    
716
#define ZALLOC_ALIGNMENT 16
717

    
718
static void *zalloc(void *x, unsigned items, unsigned size)
719
{
720
    void *p;
721

    
722
    size *= items;
723
    size = (size + ZALLOC_ALIGNMENT - 1) & ~(ZALLOC_ALIGNMENT - 1);
724

    
725
    p = qemu_mallocz(size);
726

    
727
    return (p);
728
}
729

    
730
static void zfree(void *x, void *addr)
731
{
732
    qemu_free(addr);
733
}
734

    
735
static void vnc_zlib_init(VncState *vs)
736
{
737
    int i;
738
    for (i=0; i<(sizeof(vs->zlib_stream) / sizeof(z_stream)); i++)
739
        vs->zlib_stream[i].opaque = NULL;
740
}
741

    
742
static void vnc_zlib_start(VncState *vs)
743
{
744
    buffer_reset(&vs->zlib);
745

    
746
    // make the output buffer be the zlib buffer, so we can compress it later
747
    vs->zlib_tmp = vs->output;
748
    vs->output = vs->zlib;
749
}
750

    
751
static int vnc_zlib_stop(VncState *vs, int stream_id)
752
{
753
    z_streamp zstream = &vs->zlib_stream[stream_id];
754
    int previous_out;
755

    
756
    // switch back to normal output/zlib buffers
757
    vs->zlib = vs->output;
758
    vs->output = vs->zlib_tmp;
759

    
760
    // compress the zlib buffer
761

    
762
    // initialize the stream
763
    // XXX need one stream per session
764
    if (zstream->opaque != vs) {
765
        int err;
766

    
767
        VNC_DEBUG("VNC: initializing zlib stream %d\n", stream_id);
768
        VNC_DEBUG("VNC: opaque = %p | vs = %p\n", zstream->opaque, vs);
769
        zstream->zalloc = zalloc;
770
        zstream->zfree = zfree;
771

    
772
        err = deflateInit2(zstream, vs->tight_compression, Z_DEFLATED, MAX_WBITS,
773
                           MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY);
774

    
775
        if (err != Z_OK) {
776
            fprintf(stderr, "VNC: error initializing zlib\n");
777
            return -1;
778
        }
779

    
780
        zstream->opaque = vs;
781
    }
782

    
783
    // XXX what to do if tight_compression changed in between?
784

    
785
    // reserve memory in output buffer
786
    buffer_reserve(&vs->output, vs->zlib.offset + 64);
787

    
788
    // set pointers
789
    zstream->next_in = vs->zlib.buffer;
790
    zstream->avail_in = vs->zlib.offset;
791
    zstream->next_out = vs->output.buffer + vs->output.offset;
792
    zstream->avail_out = vs->output.capacity - vs->output.offset;
793
    zstream->data_type = Z_BINARY;
794
    previous_out = zstream->total_out;
795

    
796
    // start encoding
797
    if (deflate(zstream, Z_SYNC_FLUSH) != Z_OK) {
798
        fprintf(stderr, "VNC: error during zlib compression\n");
799
        return -1;
800
    }
801

    
802
    vs->output.offset = vs->output.capacity - zstream->avail_out;
803
    return zstream->total_out - previous_out;
804
}
805

    
806
static void send_framebuffer_update_zlib(VncState *vs, int x, int y, int w, int h)
807
{
808
    int old_offset, new_offset, bytes_written;
809

    
810
    vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_ZLIB);
811

    
812
    // remember where we put in the follow-up size
813
    old_offset = vs->output.offset;
814
    vnc_write_s32(vs, 0);
815

    
816
    // compress the stream
817
    vnc_zlib_start(vs);
818
    send_framebuffer_update_raw(vs, x, y, w, h);
819
    bytes_written = vnc_zlib_stop(vs, 0);
820

    
821
    if (bytes_written == -1)
822
        return;
823

    
824
    // hack in the size
825
    new_offset = vs->output.offset;
826
    vs->output.offset = old_offset;
827
    vnc_write_u32(vs, bytes_written);
828
    vs->output.offset = new_offset;
829
}
830

    
831
static void send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
832
{
833
    switch(vs->vnc_encoding) {
834
        case VNC_ENCODING_ZLIB:
835
            send_framebuffer_update_zlib(vs, x, y, w, h);
836
            break;
837
        case VNC_ENCODING_HEXTILE:
838
            vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
839
            send_framebuffer_update_hextile(vs, x, y, w, h);
840
            break;
841
        default:
842
            vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
843
            send_framebuffer_update_raw(vs, x, y, w, h);
844
            break;
845
    }
846
}
847

    
848
static void vnc_copy(VncState *vs, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
849
{
850
    /* send bitblit op to the vnc client */
851
    vnc_write_u8(vs, 0);  /* msg id */
852
    vnc_write_u8(vs, 0);
853
    vnc_write_u16(vs, 1); /* number of rects */
854
    vnc_framebuffer_update(vs, dst_x, dst_y, w, h, VNC_ENCODING_COPYRECT);
855
    vnc_write_u16(vs, src_x);
856
    vnc_write_u16(vs, src_y);
857
    vnc_flush(vs);
858
}
859

    
860
static void vnc_dpy_copy(DisplayState *ds, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
861
{
862
    VncDisplay *vd = ds->opaque;
863
    VncState *vs, *vn;
864
    uint8_t *src_row;
865
    uint8_t *dst_row;
866
    int i,x,y,pitch,depth,inc,w_lim,s;
867
    int cmp_bytes;
868

    
869
    vnc_refresh_server_surface(vd);
870
    for (vs = vd->clients; vs != NULL; vs = vn) {
871
        vn = vs->next;
872
        if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
873
            vs->force_update = 1;
874
            vnc_update_client(vs, 1);
875
            /* vs might be free()ed here */
876
        }
877
    }
878

    
879
    /* do bitblit op on the local surface too */
880
    pitch = ds_get_linesize(vd->ds);
881
    depth = ds_get_bytes_per_pixel(vd->ds);
882
    src_row = vd->server->data + pitch * src_y + depth * src_x;
883
    dst_row = vd->server->data + pitch * dst_y + depth * dst_x;
884
    y = dst_y;
885
    inc = 1;
886
    if (dst_y > src_y) {
887
        /* copy backwards */
888
        src_row += pitch * (h-1);
889
        dst_row += pitch * (h-1);
890
        pitch = -pitch;
891
        y = dst_y + h - 1;
892
        inc = -1;
893
    }
894
    w_lim = w - (16 - (dst_x % 16));
895
    if (w_lim < 0)
896
        w_lim = w;
897
    else
898
        w_lim = w - (w_lim % 16);
899
    for (i = 0; i < h; i++) {
900
        for (x = 0; x <= w_lim;
901
                x += s, src_row += cmp_bytes, dst_row += cmp_bytes) {
902
            if (x == w_lim) {
903
                if ((s = w - w_lim) == 0)
904
                    break;
905
            } else if (!x) {
906
                s = (16 - (dst_x % 16));
907
                s = MIN(s, w_lim);
908
            } else {
909
                s = 16;
910
            }
911
            cmp_bytes = s * depth;
912
            if (memcmp(src_row, dst_row, cmp_bytes) == 0)
913
                continue;
914
            memmove(dst_row, src_row, cmp_bytes);
915
            vs = vd->clients;
916
            while (vs != NULL) {
917
                if (!vnc_has_feature(vs, VNC_FEATURE_COPYRECT))
918
                    vnc_set_bit(vs->dirty[y], ((x + dst_x) / 16));
919
                vs = vs->next;
920
            }
921
        }
922
        src_row += pitch - w * depth;
923
        dst_row += pitch - w * depth;
924
        y += inc;
925
    }
926

    
927
    for (vs = vd->clients; vs != NULL; vs = vs->next) {
928
        if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT))
929
            vnc_copy(vs, src_x, src_y, dst_x, dst_y, w, h);
930
    }
931
}
932

    
933
static int find_and_clear_dirty_height(struct VncState *vs,
934
                                       int y, int last_x, int x)
935
{
936
    int h;
937
    VncDisplay *vd = vs->vd;
938

    
939
    for (h = 1; h < (vd->server->height - y); h++) {
940
        int tmp_x;
941
        if (!vnc_get_bit(vs->dirty[y + h], last_x))
942
            break;
943
        for (tmp_x = last_x; tmp_x < x; tmp_x++)
944
            vnc_clear_bit(vs->dirty[y + h], tmp_x);
945
    }
946

    
947
    return h;
948
}
949

    
950
static int vnc_update_client(VncState *vs, int has_dirty)
951
{
952
    if (vs->need_update && vs->csock != -1) {
953
        VncDisplay *vd = vs->vd;
954
        int y;
955
        int n_rectangles;
956
        int saved_offset;
957

    
958
        if (vs->output.offset && !vs->audio_cap && !vs->force_update)
959
            /* kernel send buffers are full -> drop frames to throttle */
960
            return 0;
961

    
962
        if (!has_dirty && !vs->audio_cap && !vs->force_update)
963
            return 0;
964

    
965
        /*
966
         * Send screen updates to the vnc client using the server
967
         * surface and server dirty map.  guest surface updates
968
         * happening in parallel don't disturb us, the next pass will
969
         * send them to the client.
970
         */
971
        n_rectangles = 0;
972
        vnc_write_u8(vs, 0);  /* msg id */
973
        vnc_write_u8(vs, 0);
974
        saved_offset = vs->output.offset;
975
        vnc_write_u16(vs, 0);
976

    
977
        for (y = 0; y < vd->server->height; y++) {
978
            int x;
979
            int last_x = -1;
980
            for (x = 0; x < vd->server->width / 16; x++) {
981
                if (vnc_get_bit(vs->dirty[y], x)) {
982
                    if (last_x == -1) {
983
                        last_x = x;
984
                    }
985
                    vnc_clear_bit(vs->dirty[y], x);
986
                } else {
987
                    if (last_x != -1) {
988
                        int h = find_and_clear_dirty_height(vs, y, last_x, x);
989
                        send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
990
                        n_rectangles++;
991
                    }
992
                    last_x = -1;
993
                }
994
            }
995
            if (last_x != -1) {
996
                int h = find_and_clear_dirty_height(vs, y, last_x, x);
997
                send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
998
                n_rectangles++;
999
            }
1000
        }
1001
        vs->output.buffer[saved_offset] = (n_rectangles >> 8) & 0xFF;
1002
        vs->output.buffer[saved_offset + 1] = n_rectangles & 0xFF;
1003
        vnc_flush(vs);
1004
        vs->force_update = 0;
1005
        return n_rectangles;
1006
    }
1007

    
1008
    if (vs->csock == -1)
1009
        vnc_disconnect_finish(vs);
1010

    
1011
    return 0;
1012
}
1013

    
1014
/* audio */
1015
static void audio_capture_notify(void *opaque, audcnotification_e cmd)
1016
{
1017
    VncState *vs = opaque;
1018

    
1019
    switch (cmd) {
1020
    case AUD_CNOTIFY_DISABLE:
1021
        vnc_write_u8(vs, 255);
1022
        vnc_write_u8(vs, 1);
1023
        vnc_write_u16(vs, 0);
1024
        vnc_flush(vs);
1025
        break;
1026

    
1027
    case AUD_CNOTIFY_ENABLE:
1028
        vnc_write_u8(vs, 255);
1029
        vnc_write_u8(vs, 1);
1030
        vnc_write_u16(vs, 1);
1031
        vnc_flush(vs);
1032
        break;
1033
    }
1034
}
1035

    
1036
static void audio_capture_destroy(void *opaque)
1037
{
1038
}
1039

    
1040
static void audio_capture(void *opaque, void *buf, int size)
1041
{
1042
    VncState *vs = opaque;
1043

    
1044
    vnc_write_u8(vs, 255);
1045
    vnc_write_u8(vs, 1);
1046
    vnc_write_u16(vs, 2);
1047
    vnc_write_u32(vs, size);
1048
    vnc_write(vs, buf, size);
1049
    vnc_flush(vs);
1050
}
1051

    
1052
static void audio_add(VncState *vs)
1053
{
1054
    Monitor *mon = cur_mon;
1055
    struct audio_capture_ops ops;
1056

    
1057
    if (vs->audio_cap) {
1058
        monitor_printf(mon, "audio already running\n");
1059
        return;
1060
    }
1061

    
1062
    ops.notify = audio_capture_notify;
1063
    ops.destroy = audio_capture_destroy;
1064
    ops.capture = audio_capture;
1065

    
1066
    vs->audio_cap = AUD_add_capture(&vs->as, &ops, vs);
1067
    if (!vs->audio_cap) {
1068
        monitor_printf(mon, "Failed to add audio capture\n");
1069
    }
1070
}
1071

    
1072
static void audio_del(VncState *vs)
1073
{
1074
    if (vs->audio_cap) {
1075
        AUD_del_capture(vs->audio_cap, vs);
1076
        vs->audio_cap = NULL;
1077
    }
1078
}
1079

    
1080
static void vnc_disconnect_start(VncState *vs)
1081
{
1082
    if (vs->csock == -1)
1083
        return;
1084
    qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
1085
    closesocket(vs->csock);
1086
    vs->csock = -1;
1087
}
1088

    
1089
static void vnc_disconnect_finish(VncState *vs)
1090
{
1091
    vnc_qmp_event(vs, QEVENT_VNC_DISCONNECTED);
1092

    
1093
    if (vs->input.buffer) {
1094
        qemu_free(vs->input.buffer);
1095
        vs->input.buffer = NULL;
1096
    }
1097
    if (vs->output.buffer) {
1098
        qemu_free(vs->output.buffer);
1099
        vs->output.buffer = NULL;
1100
    }
1101

    
1102
    qobject_decref(vs->info);
1103

    
1104
#ifdef CONFIG_VNC_TLS
1105
    vnc_tls_client_cleanup(vs);
1106
#endif /* CONFIG_VNC_TLS */
1107
#ifdef CONFIG_VNC_SASL
1108
    vnc_sasl_client_cleanup(vs);
1109
#endif /* CONFIG_VNC_SASL */
1110
    audio_del(vs);
1111

    
1112
    VncState *p, *parent = NULL;
1113
    for (p = vs->vd->clients; p != NULL; p = p->next) {
1114
        if (p == vs) {
1115
            if (parent)
1116
                parent->next = p->next;
1117
            else
1118
                vs->vd->clients = p->next;
1119
            break;
1120
        }
1121
        parent = p;
1122
    }
1123
    if (!vs->vd->clients)
1124
        dcl->idle = 1;
1125

    
1126
    vnc_remove_timer(vs->vd);
1127
    qemu_free(vs);
1128
}
1129

    
1130
int vnc_client_io_error(VncState *vs, int ret, int last_errno)
1131
{
1132
    if (ret == 0 || ret == -1) {
1133
        if (ret == -1) {
1134
            switch (last_errno) {
1135
                case EINTR:
1136
                case EAGAIN:
1137
#ifdef _WIN32
1138
                case WSAEWOULDBLOCK:
1139
#endif
1140
                    return 0;
1141
                default:
1142
                    break;
1143
            }
1144
        }
1145

    
1146
        VNC_DEBUG("Closing down client sock: ret %d, errno %d\n",
1147
                  ret, ret < 0 ? last_errno : 0);
1148
        vnc_disconnect_start(vs);
1149

    
1150
        return 0;
1151
    }
1152
    return ret;
1153
}
1154

    
1155

    
1156
void vnc_client_error(VncState *vs)
1157
{
1158
    VNC_DEBUG("Closing down client sock: protocol error\n");
1159
    vnc_disconnect_start(vs);
1160
}
1161

    
1162

    
1163
/*
1164
 * Called to write a chunk of data to the client socket. The data may
1165
 * be the raw data, or may have already been encoded by SASL.
1166
 * The data will be written either straight onto the socket, or
1167
 * written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1168
 *
1169
 * NB, it is theoretically possible to have 2 layers of encryption,
1170
 * both SASL, and this TLS layer. It is highly unlikely in practice
1171
 * though, since SASL encryption will typically be a no-op if TLS
1172
 * is active
1173
 *
1174
 * Returns the number of bytes written, which may be less than
1175
 * the requested 'datalen' if the socket would block. Returns
1176
 * -1 on error, and disconnects the client socket.
1177
 */
1178
long vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
1179
{
1180
    long ret;
1181
#ifdef CONFIG_VNC_TLS
1182
    if (vs->tls.session) {
1183
        ret = gnutls_write(vs->tls.session, data, datalen);
1184
        if (ret < 0) {
1185
            if (ret == GNUTLS_E_AGAIN)
1186
                errno = EAGAIN;
1187
            else
1188
                errno = EIO;
1189
            ret = -1;
1190
        }
1191
    } else
1192
#endif /* CONFIG_VNC_TLS */
1193
        ret = send(vs->csock, (const void *)data, datalen, 0);
1194
    VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
1195
    return vnc_client_io_error(vs, ret, socket_error());
1196
}
1197

    
1198

    
1199
/*
1200
 * Called to write buffered data to the client socket, when not
1201
 * using any SASL SSF encryption layers. Will write as much data
1202
 * as possible without blocking. If all buffered data is written,
1203
 * will switch the FD poll() handler back to read monitoring.
1204
 *
1205
 * Returns the number of bytes written, which may be less than
1206
 * the buffered output data if the socket would block. Returns
1207
 * -1 on error, and disconnects the client socket.
1208
 */
1209
static long vnc_client_write_plain(VncState *vs)
1210
{
1211
    long ret;
1212

    
1213
#ifdef CONFIG_VNC_SASL
1214
    VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
1215
              vs->output.buffer, vs->output.capacity, vs->output.offset,
1216
              vs->sasl.waitWriteSSF);
1217

    
1218
    if (vs->sasl.conn &&
1219
        vs->sasl.runSSF &&
1220
        vs->sasl.waitWriteSSF) {
1221
        ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
1222
        if (ret)
1223
            vs->sasl.waitWriteSSF -= ret;
1224
    } else
1225
#endif /* CONFIG_VNC_SASL */
1226
        ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
1227
    if (!ret)
1228
        return 0;
1229

    
1230
    memmove(vs->output.buffer, vs->output.buffer + ret, (vs->output.offset - ret));
1231
    vs->output.offset -= ret;
1232

    
1233
    if (vs->output.offset == 0) {
1234
        qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
1235
    }
1236

    
1237
    return ret;
1238
}
1239

    
1240

    
1241
/*
1242
 * First function called whenever there is data to be written to
1243
 * the client socket. Will delegate actual work according to whether
1244
 * SASL SSF layers are enabled (thus requiring encryption calls)
1245
 */
1246
void vnc_client_write(void *opaque)
1247
{
1248
    long ret;
1249
    VncState *vs = opaque;
1250

    
1251
#ifdef CONFIG_VNC_SASL
1252
    if (vs->sasl.conn &&
1253
        vs->sasl.runSSF &&
1254
        !vs->sasl.waitWriteSSF)
1255
        ret = vnc_client_write_sasl(vs);
1256
    else
1257
#endif /* CONFIG_VNC_SASL */
1258
        ret = vnc_client_write_plain(vs);
1259
}
1260

    
1261
void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
1262
{
1263
    vs->read_handler = func;
1264
    vs->read_handler_expect = expecting;
1265
}
1266

    
1267

    
1268
/*
1269
 * Called to read a chunk of data from the client socket. The data may
1270
 * be the raw data, or may need to be further decoded by SASL.
1271
 * The data will be read either straight from to the socket, or
1272
 * read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
1273
 *
1274
 * NB, it is theoretically possible to have 2 layers of encryption,
1275
 * both SASL, and this TLS layer. It is highly unlikely in practice
1276
 * though, since SASL encryption will typically be a no-op if TLS
1277
 * is active
1278
 *
1279
 * Returns the number of bytes read, which may be less than
1280
 * the requested 'datalen' if the socket would block. Returns
1281
 * -1 on error, and disconnects the client socket.
1282
 */
1283
long vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
1284
{
1285
    long ret;
1286
#ifdef CONFIG_VNC_TLS
1287
    if (vs->tls.session) {
1288
        ret = gnutls_read(vs->tls.session, data, datalen);
1289
        if (ret < 0) {
1290
            if (ret == GNUTLS_E_AGAIN)
1291
                errno = EAGAIN;
1292
            else
1293
                errno = EIO;
1294
            ret = -1;
1295
        }
1296
    } else
1297
#endif /* CONFIG_VNC_TLS */
1298
        ret = recv(vs->csock, (void *)data, datalen, 0);
1299
    VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
1300
    return vnc_client_io_error(vs, ret, socket_error());
1301
}
1302

    
1303

    
1304
/*
1305
 * Called to read data from the client socket to the input buffer,
1306
 * when not using any SASL SSF encryption layers. Will read as much
1307
 * data as possible without blocking.
1308
 *
1309
 * Returns the number of bytes read. Returns -1 on error, and
1310
 * disconnects the client socket.
1311
 */
1312
static long vnc_client_read_plain(VncState *vs)
1313
{
1314
    int ret;
1315
    VNC_DEBUG("Read plain %p size %zd offset %zd\n",
1316
              vs->input.buffer, vs->input.capacity, vs->input.offset);
1317
    buffer_reserve(&vs->input, 4096);
1318
    ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
1319
    if (!ret)
1320
        return 0;
1321
    vs->input.offset += ret;
1322
    return ret;
1323
}
1324

    
1325

    
1326
/*
1327
 * First function called whenever there is more data to be read from
1328
 * the client socket. Will delegate actual work according to whether
1329
 * SASL SSF layers are enabled (thus requiring decryption calls)
1330
 */
1331
void vnc_client_read(void *opaque)
1332
{
1333
    VncState *vs = opaque;
1334
    long ret;
1335

    
1336
#ifdef CONFIG_VNC_SASL
1337
    if (vs->sasl.conn && vs->sasl.runSSF)
1338
        ret = vnc_client_read_sasl(vs);
1339
    else
1340
#endif /* CONFIG_VNC_SASL */
1341
        ret = vnc_client_read_plain(vs);
1342
    if (!ret) {
1343
        if (vs->csock == -1)
1344
            vnc_disconnect_finish(vs);
1345
        return;
1346
    }
1347

    
1348
    while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
1349
        size_t len = vs->read_handler_expect;
1350
        int ret;
1351

    
1352
        ret = vs->read_handler(vs, vs->input.buffer, len);
1353
        if (vs->csock == -1) {
1354
            vnc_disconnect_finish(vs);
1355
            return;
1356
        }
1357

    
1358
        if (!ret) {
1359
            memmove(vs->input.buffer, vs->input.buffer + len, (vs->input.offset - len));
1360
            vs->input.offset -= len;
1361
        } else {
1362
            vs->read_handler_expect = ret;
1363
        }
1364
    }
1365
}
1366

    
1367
void vnc_write(VncState *vs, const void *data, size_t len)
1368
{
1369
    buffer_reserve(&vs->output, len);
1370

    
1371
    if (vs->csock != -1 && buffer_empty(&vs->output)) {
1372
        qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
1373
    }
1374

    
1375
    buffer_append(&vs->output, data, len);
1376
}
1377

    
1378
void vnc_write_s32(VncState *vs, int32_t value)
1379
{
1380
    vnc_write_u32(vs, *(uint32_t *)&value);
1381
}
1382

    
1383
void vnc_write_u32(VncState *vs, uint32_t value)
1384
{
1385
    uint8_t buf[4];
1386

    
1387
    buf[0] = (value >> 24) & 0xFF;
1388
    buf[1] = (value >> 16) & 0xFF;
1389
    buf[2] = (value >>  8) & 0xFF;
1390
    buf[3] = value & 0xFF;
1391

    
1392
    vnc_write(vs, buf, 4);
1393
}
1394

    
1395
void vnc_write_u16(VncState *vs, uint16_t value)
1396
{
1397
    uint8_t buf[2];
1398

    
1399
    buf[0] = (value >> 8) & 0xFF;
1400
    buf[1] = value & 0xFF;
1401

    
1402
    vnc_write(vs, buf, 2);
1403
}
1404

    
1405
void vnc_write_u8(VncState *vs, uint8_t value)
1406
{
1407
    vnc_write(vs, (char *)&value, 1);
1408
}
1409

    
1410
void vnc_flush(VncState *vs)
1411
{
1412
    if (vs->csock != -1 && vs->output.offset)
1413
        vnc_client_write(vs);
1414
}
1415

    
1416
uint8_t read_u8(uint8_t *data, size_t offset)
1417
{
1418
    return data[offset];
1419
}
1420

    
1421
uint16_t read_u16(uint8_t *data, size_t offset)
1422
{
1423
    return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
1424
}
1425

    
1426
int32_t read_s32(uint8_t *data, size_t offset)
1427
{
1428
    return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
1429
                     (data[offset + 2] << 8) | data[offset + 3]);
1430
}
1431

    
1432
uint32_t read_u32(uint8_t *data, size_t offset)
1433
{
1434
    return ((data[offset] << 24) | (data[offset + 1] << 16) |
1435
            (data[offset + 2] << 8) | data[offset + 3]);
1436
}
1437

    
1438
static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
1439
{
1440
}
1441

    
1442
static void check_pointer_type_change(VncState *vs, int absolute)
1443
{
1444
    if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
1445
        vnc_write_u8(vs, 0);
1446
        vnc_write_u8(vs, 0);
1447
        vnc_write_u16(vs, 1);
1448
        vnc_framebuffer_update(vs, absolute, 0,
1449
                               ds_get_width(vs->ds), ds_get_height(vs->ds),
1450
                               VNC_ENCODING_POINTER_TYPE_CHANGE);
1451
        vnc_flush(vs);
1452
    }
1453
    vs->absolute = absolute;
1454
}
1455

    
1456
static void pointer_event(VncState *vs, int button_mask, int x, int y)
1457
{
1458
    int buttons = 0;
1459
    int dz = 0;
1460

    
1461
    if (button_mask & 0x01)
1462
        buttons |= MOUSE_EVENT_LBUTTON;
1463
    if (button_mask & 0x02)
1464
        buttons |= MOUSE_EVENT_MBUTTON;
1465
    if (button_mask & 0x04)
1466
        buttons |= MOUSE_EVENT_RBUTTON;
1467
    if (button_mask & 0x08)
1468
        dz = -1;
1469
    if (button_mask & 0x10)
1470
        dz = 1;
1471

    
1472
    if (vs->absolute) {
1473
        kbd_mouse_event(x * 0x7FFF / (ds_get_width(vs->ds) - 1),
1474
                        y * 0x7FFF / (ds_get_height(vs->ds) - 1),
1475
                        dz, buttons);
1476
    } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
1477
        x -= 0x7FFF;
1478
        y -= 0x7FFF;
1479

    
1480
        kbd_mouse_event(x, y, dz, buttons);
1481
    } else {
1482
        if (vs->last_x != -1)
1483
            kbd_mouse_event(x - vs->last_x,
1484
                            y - vs->last_y,
1485
                            dz, buttons);
1486
        vs->last_x = x;
1487
        vs->last_y = y;
1488
    }
1489

    
1490
    check_pointer_type_change(vs, kbd_mouse_is_absolute());
1491
}
1492

    
1493
static void reset_keys(VncState *vs)
1494
{
1495
    int i;
1496
    for(i = 0; i < 256; i++) {
1497
        if (vs->modifiers_state[i]) {
1498
            if (i & 0x80)
1499
                kbd_put_keycode(0xe0);
1500
            kbd_put_keycode(i | 0x80);
1501
            vs->modifiers_state[i] = 0;
1502
        }
1503
    }
1504
}
1505

    
1506
static void press_key(VncState *vs, int keysym)
1507
{
1508
    kbd_put_keycode(keysym2scancode(vs->vd->kbd_layout, keysym) & 0x7f);
1509
    kbd_put_keycode(keysym2scancode(vs->vd->kbd_layout, keysym) | 0x80);
1510
}
1511

    
1512
static void do_key_event(VncState *vs, int down, int keycode, int sym)
1513
{
1514
    /* QEMU console switch */
1515
    switch(keycode) {
1516
    case 0x2a:                          /* Left Shift */
1517
    case 0x36:                          /* Right Shift */
1518
    case 0x1d:                          /* Left CTRL */
1519
    case 0x9d:                          /* Right CTRL */
1520
    case 0x38:                          /* Left ALT */
1521
    case 0xb8:                          /* Right ALT */
1522
        if (down)
1523
            vs->modifiers_state[keycode] = 1;
1524
        else
1525
            vs->modifiers_state[keycode] = 0;
1526
        break;
1527
    case 0x02 ... 0x0a: /* '1' to '9' keys */
1528
        if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
1529
            /* Reset the modifiers sent to the current console */
1530
            reset_keys(vs);
1531
            console_select(keycode - 0x02);
1532
            return;
1533
        }
1534
        break;
1535
    case 0x3a:                        /* CapsLock */
1536
    case 0x45:                        /* NumLock */
1537
        if (!down)
1538
            vs->modifiers_state[keycode] ^= 1;
1539
        break;
1540
    }
1541

    
1542
    if (keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
1543
        /* If the numlock state needs to change then simulate an additional
1544
           keypress before sending this one.  This will happen if the user
1545
           toggles numlock away from the VNC window.
1546
        */
1547
        if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
1548
            if (!vs->modifiers_state[0x45]) {
1549
                vs->modifiers_state[0x45] = 1;
1550
                press_key(vs, 0xff7f);
1551
            }
1552
        } else {
1553
            if (vs->modifiers_state[0x45]) {
1554
                vs->modifiers_state[0x45] = 0;
1555
                press_key(vs, 0xff7f);
1556
            }
1557
        }
1558
    }
1559

    
1560
    if ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z')) {
1561
        /* If the capslock state needs to change then simulate an additional
1562
           keypress before sending this one.  This will happen if the user
1563
           toggles capslock away from the VNC window.
1564
        */
1565
        int uppercase = !!(sym >= 'A' && sym <= 'Z');
1566
        int shift = !!(vs->modifiers_state[0x2a] | vs->modifiers_state[0x36]);
1567
        int capslock = !!(vs->modifiers_state[0x3a]);
1568
        if (capslock) {
1569
            if (uppercase == shift) {
1570
                vs->modifiers_state[0x3a] = 0;
1571
                press_key(vs, 0xffe5);
1572
            }
1573
        } else {
1574
            if (uppercase != shift) {
1575
                vs->modifiers_state[0x3a] = 1;
1576
                press_key(vs, 0xffe5);
1577
            }
1578
        }
1579
    }
1580

    
1581
    if (is_graphic_console()) {
1582
        if (keycode & 0x80)
1583
            kbd_put_keycode(0xe0);
1584
        if (down)
1585
            kbd_put_keycode(keycode & 0x7f);
1586
        else
1587
            kbd_put_keycode(keycode | 0x80);
1588
    } else {
1589
        /* QEMU console emulation */
1590
        if (down) {
1591
            int numlock = vs->modifiers_state[0x45];
1592
            switch (keycode) {
1593
            case 0x2a:                          /* Left Shift */
1594
            case 0x36:                          /* Right Shift */
1595
            case 0x1d:                          /* Left CTRL */
1596
            case 0x9d:                          /* Right CTRL */
1597
            case 0x38:                          /* Left ALT */
1598
            case 0xb8:                          /* Right ALT */
1599
                break;
1600
            case 0xc8:
1601
                kbd_put_keysym(QEMU_KEY_UP);
1602
                break;
1603
            case 0xd0:
1604
                kbd_put_keysym(QEMU_KEY_DOWN);
1605
                break;
1606
            case 0xcb:
1607
                kbd_put_keysym(QEMU_KEY_LEFT);
1608
                break;
1609
            case 0xcd:
1610
                kbd_put_keysym(QEMU_KEY_RIGHT);
1611
                break;
1612
            case 0xd3:
1613
                kbd_put_keysym(QEMU_KEY_DELETE);
1614
                break;
1615
            case 0xc7:
1616
                kbd_put_keysym(QEMU_KEY_HOME);
1617
                break;
1618
            case 0xcf:
1619
                kbd_put_keysym(QEMU_KEY_END);
1620
                break;
1621
            case 0xc9:
1622
                kbd_put_keysym(QEMU_KEY_PAGEUP);
1623
                break;
1624
            case 0xd1:
1625
                kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1626
                break;
1627

    
1628
            case 0x47:
1629
                kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
1630
                break;
1631
            case 0x48:
1632
                kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
1633
                break;
1634
            case 0x49:
1635
                kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
1636
                break;
1637
            case 0x4b:
1638
                kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
1639
                break;
1640
            case 0x4c:
1641
                kbd_put_keysym('5');
1642
                break;
1643
            case 0x4d:
1644
                kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
1645
                break;
1646
            case 0x4f:
1647
                kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
1648
                break;
1649
            case 0x50:
1650
                kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
1651
                break;
1652
            case 0x51:
1653
                kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
1654
                break;
1655
            case 0x52:
1656
                kbd_put_keysym('0');
1657
                break;
1658
            case 0x53:
1659
                kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
1660
                break;
1661

    
1662
            case 0xb5:
1663
                kbd_put_keysym('/');
1664
                break;
1665
            case 0x37:
1666
                kbd_put_keysym('*');
1667
                break;
1668
            case 0x4a:
1669
                kbd_put_keysym('-');
1670
                break;
1671
            case 0x4e:
1672
                kbd_put_keysym('+');
1673
                break;
1674
            case 0x9c:
1675
                kbd_put_keysym('\n');
1676
                break;
1677

    
1678
            default:
1679
                kbd_put_keysym(sym);
1680
                break;
1681
            }
1682
        }
1683
    }
1684
}
1685

    
1686
static void key_event(VncState *vs, int down, uint32_t sym)
1687
{
1688
    int keycode;
1689
    int lsym = sym;
1690

    
1691
    if (lsym >= 'A' && lsym <= 'Z' && is_graphic_console()) {
1692
        lsym = lsym - 'A' + 'a';
1693
    }
1694

    
1695
    keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF);
1696
    do_key_event(vs, down, keycode, sym);
1697
}
1698

    
1699
static void ext_key_event(VncState *vs, int down,
1700
                          uint32_t sym, uint16_t keycode)
1701
{
1702
    /* if the user specifies a keyboard layout, always use it */
1703
    if (keyboard_layout)
1704
        key_event(vs, down, sym);
1705
    else
1706
        do_key_event(vs, down, keycode, sym);
1707
}
1708

    
1709
static void framebuffer_update_request(VncState *vs, int incremental,
1710
                                       int x_position, int y_position,
1711
                                       int w, int h)
1712
{
1713
    if (x_position > ds_get_width(vs->ds))
1714
        x_position = ds_get_width(vs->ds);
1715
    if (y_position > ds_get_height(vs->ds))
1716
        y_position = ds_get_height(vs->ds);
1717
    if (x_position + w >= ds_get_width(vs->ds))
1718
        w = ds_get_width(vs->ds)  - x_position;
1719
    if (y_position + h >= ds_get_height(vs->ds))
1720
        h = ds_get_height(vs->ds) - y_position;
1721

    
1722
    int i;
1723
    vs->need_update = 1;
1724
    if (!incremental) {
1725
        vs->force_update = 1;
1726
        for (i = 0; i < h; i++) {
1727
            vnc_set_bits(vs->dirty[y_position + i],
1728
                         (ds_get_width(vs->ds) / 16), VNC_DIRTY_WORDS);
1729
        }
1730
    }
1731
}
1732

    
1733
static void send_ext_key_event_ack(VncState *vs)
1734
{
1735
    vnc_write_u8(vs, 0);
1736
    vnc_write_u8(vs, 0);
1737
    vnc_write_u16(vs, 1);
1738
    vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1739
                           VNC_ENCODING_EXT_KEY_EVENT);
1740
    vnc_flush(vs);
1741
}
1742

    
1743
static void send_ext_audio_ack(VncState *vs)
1744
{
1745
    vnc_write_u8(vs, 0);
1746
    vnc_write_u8(vs, 0);
1747
    vnc_write_u16(vs, 1);
1748
    vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), ds_get_height(vs->ds),
1749
                           VNC_ENCODING_AUDIO);
1750
    vnc_flush(vs);
1751
}
1752

    
1753
static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
1754
{
1755
    int i;
1756
    unsigned int enc = 0;
1757

    
1758
    vnc_zlib_init(vs);
1759
    vs->features = 0;
1760
    vs->vnc_encoding = 0;
1761
    vs->tight_compression = 9;
1762
    vs->tight_quality = 9;
1763
    vs->absolute = -1;
1764

    
1765
    for (i = n_encodings - 1; i >= 0; i--) {
1766
        enc = encodings[i];
1767
        switch (enc) {
1768
        case VNC_ENCODING_RAW:
1769
            vs->vnc_encoding = enc;
1770
            break;
1771
        case VNC_ENCODING_COPYRECT:
1772
            vs->features |= VNC_FEATURE_COPYRECT_MASK;
1773
            break;
1774
        case VNC_ENCODING_HEXTILE:
1775
            vs->features |= VNC_FEATURE_HEXTILE_MASK;
1776
            vs->vnc_encoding = enc;
1777
            break;
1778
        case VNC_ENCODING_ZLIB:
1779
            vs->features |= VNC_FEATURE_ZLIB_MASK;
1780
            vs->vnc_encoding = enc;
1781
            break;
1782
        case VNC_ENCODING_DESKTOPRESIZE:
1783
            vs->features |= VNC_FEATURE_RESIZE_MASK;
1784
            break;
1785
        case VNC_ENCODING_POINTER_TYPE_CHANGE:
1786
            vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
1787
            break;
1788
        case VNC_ENCODING_EXT_KEY_EVENT:
1789
            send_ext_key_event_ack(vs);
1790
            break;
1791
        case VNC_ENCODING_AUDIO:
1792
            send_ext_audio_ack(vs);
1793
            break;
1794
        case VNC_ENCODING_WMVi:
1795
            vs->features |= VNC_FEATURE_WMVI_MASK;
1796
            break;
1797
        case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
1798
            vs->tight_compression = (enc & 0x0F);
1799
            break;
1800
        case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
1801
            vs->tight_quality = (enc & 0x0F);
1802
            break;
1803
        default:
1804
            VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
1805
            break;
1806
        }
1807
    }
1808

    
1809
    check_pointer_type_change(vs, kbd_mouse_is_absolute());
1810
}
1811

    
1812
static void set_pixel_conversion(VncState *vs)
1813
{
1814
    if ((vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) ==
1815
        (vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG) && 
1816
        !memcmp(&(vs->clientds.pf), &(vs->ds->surface->pf), sizeof(PixelFormat))) {
1817
        vs->write_pixels = vnc_write_pixels_copy;
1818
        switch (vs->ds->surface->pf.bits_per_pixel) {
1819
            case 8:
1820
                vs->send_hextile_tile = send_hextile_tile_8;
1821
                break;
1822
            case 16:
1823
                vs->send_hextile_tile = send_hextile_tile_16;
1824
                break;
1825
            case 32:
1826
                vs->send_hextile_tile = send_hextile_tile_32;
1827
                break;
1828
        }
1829
    } else {
1830
        vs->write_pixels = vnc_write_pixels_generic;
1831
        switch (vs->ds->surface->pf.bits_per_pixel) {
1832
            case 8:
1833
                vs->send_hextile_tile = send_hextile_tile_generic_8;
1834
                break;
1835
            case 16:
1836
                vs->send_hextile_tile = send_hextile_tile_generic_16;
1837
                break;
1838
            case 32:
1839
                vs->send_hextile_tile = send_hextile_tile_generic_32;
1840
                break;
1841
        }
1842
    }
1843
}
1844

    
1845
static void set_pixel_format(VncState *vs,
1846
                             int bits_per_pixel, int depth,
1847
                             int big_endian_flag, int true_color_flag,
1848
                             int red_max, int green_max, int blue_max,
1849
                             int red_shift, int green_shift, int blue_shift)
1850
{
1851
    if (!true_color_flag) {
1852
        vnc_client_error(vs);
1853
        return;
1854
    }
1855

    
1856
    vs->clientds = *(vs->vd->guest.ds);
1857
    vs->clientds.pf.rmax = red_max;
1858
    count_bits(vs->clientds.pf.rbits, red_max);
1859
    vs->clientds.pf.rshift = red_shift;
1860
    vs->clientds.pf.rmask = red_max << red_shift;
1861
    vs->clientds.pf.gmax = green_max;
1862
    count_bits(vs->clientds.pf.gbits, green_max);
1863
    vs->clientds.pf.gshift = green_shift;
1864
    vs->clientds.pf.gmask = green_max << green_shift;
1865
    vs->clientds.pf.bmax = blue_max;
1866
    count_bits(vs->clientds.pf.bbits, blue_max);
1867
    vs->clientds.pf.bshift = blue_shift;
1868
    vs->clientds.pf.bmask = blue_max << blue_shift;
1869
    vs->clientds.pf.bits_per_pixel = bits_per_pixel;
1870
    vs->clientds.pf.bytes_per_pixel = bits_per_pixel / 8;
1871
    vs->clientds.pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
1872
    vs->clientds.flags = big_endian_flag ? QEMU_BIG_ENDIAN_FLAG : 0x00;
1873

    
1874
    set_pixel_conversion(vs);
1875

    
1876
    vga_hw_invalidate();
1877
    vga_hw_update();
1878
}
1879

    
1880
static void pixel_format_message (VncState *vs) {
1881
    char pad[3] = { 0, 0, 0 };
1882

    
1883
    vnc_write_u8(vs, vs->ds->surface->pf.bits_per_pixel); /* bits-per-pixel */
1884
    vnc_write_u8(vs, vs->ds->surface->pf.depth); /* depth */
1885

    
1886
#ifdef HOST_WORDS_BIGENDIAN
1887
    vnc_write_u8(vs, 1);             /* big-endian-flag */
1888
#else
1889
    vnc_write_u8(vs, 0);             /* big-endian-flag */
1890
#endif
1891
    vnc_write_u8(vs, 1);             /* true-color-flag */
1892
    vnc_write_u16(vs, vs->ds->surface->pf.rmax);     /* red-max */
1893
    vnc_write_u16(vs, vs->ds->surface->pf.gmax);     /* green-max */
1894
    vnc_write_u16(vs, vs->ds->surface->pf.bmax);     /* blue-max */
1895
    vnc_write_u8(vs, vs->ds->surface->pf.rshift);    /* red-shift */
1896
    vnc_write_u8(vs, vs->ds->surface->pf.gshift);    /* green-shift */
1897
    vnc_write_u8(vs, vs->ds->surface->pf.bshift);    /* blue-shift */
1898
    if (vs->ds->surface->pf.bits_per_pixel == 32)
1899
        vs->send_hextile_tile = send_hextile_tile_32;
1900
    else if (vs->ds->surface->pf.bits_per_pixel == 16)
1901
        vs->send_hextile_tile = send_hextile_tile_16;
1902
    else if (vs->ds->surface->pf.bits_per_pixel == 8)
1903
        vs->send_hextile_tile = send_hextile_tile_8;
1904
    vs->clientds = *(vs->ds->surface);
1905
    vs->clientds.flags &= ~QEMU_ALLOCATED_FLAG;
1906
    vs->write_pixels = vnc_write_pixels_copy;
1907

    
1908
    vnc_write(vs, pad, 3);           /* padding */
1909
}
1910

    
1911
static void vnc_dpy_setdata(DisplayState *ds)
1912
{
1913
    /* We don't have to do anything */
1914
}
1915

    
1916
static void vnc_colordepth(VncState *vs)
1917
{
1918
    if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
1919
        /* Sending a WMVi message to notify the client*/
1920
        vnc_write_u8(vs, 0);  /* msg id */
1921
        vnc_write_u8(vs, 0);
1922
        vnc_write_u16(vs, 1); /* number of rects */
1923
        vnc_framebuffer_update(vs, 0, 0, ds_get_width(vs->ds), 
1924
                               ds_get_height(vs->ds), VNC_ENCODING_WMVi);
1925
        pixel_format_message(vs);
1926
        vnc_flush(vs);
1927
    } else {
1928
        set_pixel_conversion(vs);
1929
    }
1930
}
1931

    
1932
static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
1933
{
1934
    int i;
1935
    uint16_t limit;
1936
    VncDisplay *vd = vs->vd;
1937

    
1938
    if (data[0] > 3) {
1939
        vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
1940
        if (!qemu_timer_expired(vd->timer, qemu_get_clock(rt_clock) + vd->timer_interval))
1941
            qemu_mod_timer(vd->timer, qemu_get_clock(rt_clock) + vd->timer_interval);
1942
    }
1943

    
1944
    switch (data[0]) {
1945
    case 0:
1946
        if (len == 1)
1947
            return 20;
1948

    
1949
        set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
1950
                         read_u8(data, 6), read_u8(data, 7),
1951
                         read_u16(data, 8), read_u16(data, 10),
1952
                         read_u16(data, 12), read_u8(data, 14),
1953
                         read_u8(data, 15), read_u8(data, 16));
1954
        break;
1955
    case 2:
1956
        if (len == 1)
1957
            return 4;
1958

    
1959
        if (len == 4) {
1960
            limit = read_u16(data, 2);
1961
            if (limit > 0)
1962
                return 4 + (limit * 4);
1963
        } else
1964
            limit = read_u16(data, 2);
1965

    
1966
        for (i = 0; i < limit; i++) {
1967
            int32_t val = read_s32(data, 4 + (i * 4));
1968
            memcpy(data + 4 + (i * 4), &val, sizeof(val));
1969
        }
1970

    
1971
        set_encodings(vs, (int32_t *)(data + 4), limit);
1972
        break;
1973
    case 3:
1974
        if (len == 1)
1975
            return 10;
1976

    
1977
        framebuffer_update_request(vs,
1978
                                   read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
1979
                                   read_u16(data, 6), read_u16(data, 8));
1980
        break;
1981
    case 4:
1982
        if (len == 1)
1983
            return 8;
1984

    
1985
        key_event(vs, read_u8(data, 1), read_u32(data, 4));
1986
        break;
1987
    case 5:
1988
        if (len == 1)
1989
            return 6;
1990

    
1991
        pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
1992
        break;
1993
    case 6:
1994
        if (len == 1)
1995
            return 8;
1996

    
1997
        if (len == 8) {
1998
            uint32_t dlen = read_u32(data, 4);
1999
            if (dlen > 0)
2000
                return 8 + dlen;
2001
        }
2002

    
2003
        client_cut_text(vs, read_u32(data, 4), data + 8);
2004
        break;
2005
    case 255:
2006
        if (len == 1)
2007
            return 2;
2008

    
2009
        switch (read_u8(data, 1)) {
2010
        case 0:
2011
            if (len == 2)
2012
                return 12;
2013

    
2014
            ext_key_event(vs, read_u16(data, 2),
2015
                          read_u32(data, 4), read_u32(data, 8));
2016
            break;
2017
        case 1:
2018
            if (len == 2)
2019
                return 4;
2020

    
2021
            switch (read_u16 (data, 2)) {
2022
            case 0:
2023
                audio_add(vs);
2024
                break;
2025
            case 1:
2026
                audio_del(vs);
2027
                break;
2028
            case 2:
2029
                if (len == 4)
2030
                    return 10;
2031
                switch (read_u8(data, 4)) {
2032
                case 0: vs->as.fmt = AUD_FMT_U8; break;
2033
                case 1: vs->as.fmt = AUD_FMT_S8; break;
2034
                case 2: vs->as.fmt = AUD_FMT_U16; break;
2035
                case 3: vs->as.fmt = AUD_FMT_S16; break;
2036
                case 4: vs->as.fmt = AUD_FMT_U32; break;
2037
                case 5: vs->as.fmt = AUD_FMT_S32; break;
2038
                default:
2039
                    printf("Invalid audio format %d\n", read_u8(data, 4));
2040
                    vnc_client_error(vs);
2041
                    break;
2042
                }
2043
                vs->as.nchannels = read_u8(data, 5);
2044
                if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
2045
                    printf("Invalid audio channel coount %d\n",
2046
                           read_u8(data, 5));
2047
                    vnc_client_error(vs);
2048
                    break;
2049
                }
2050
                vs->as.freq = read_u32(data, 6);
2051
                break;
2052
            default:
2053
                printf ("Invalid audio message %d\n", read_u8(data, 4));
2054
                vnc_client_error(vs);
2055
                break;
2056
            }
2057
            break;
2058

    
2059
        default:
2060
            printf("Msg: %d\n", read_u16(data, 0));
2061
            vnc_client_error(vs);
2062
            break;
2063
        }
2064
        break;
2065
    default:
2066
        printf("Msg: %d\n", data[0]);
2067
        vnc_client_error(vs);
2068
        break;
2069
    }
2070

    
2071
    vnc_read_when(vs, protocol_client_msg, 1);
2072
    return 0;
2073
}
2074

    
2075
static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
2076
{
2077
    char buf[1024];
2078
    int size;
2079

    
2080
    vnc_write_u16(vs, ds_get_width(vs->ds));
2081
    vnc_write_u16(vs, ds_get_height(vs->ds));
2082

    
2083
    pixel_format_message(vs);
2084

    
2085
    if (qemu_name)
2086
        size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
2087
    else
2088
        size = snprintf(buf, sizeof(buf), "QEMU");
2089

    
2090
    vnc_write_u32(vs, size);
2091
    vnc_write(vs, buf, size);
2092
    vnc_flush(vs);
2093

    
2094
    vnc_client_cache_auth(vs);
2095
    vnc_qmp_event(vs, QEVENT_VNC_INITIALIZED);
2096

    
2097
    vnc_read_when(vs, protocol_client_msg, 1);
2098

    
2099
    return 0;
2100
}
2101

    
2102
void start_client_init(VncState *vs)
2103
{
2104
    vnc_read_when(vs, protocol_client_init, 1);
2105
}
2106

    
2107
static void make_challenge(VncState *vs)
2108
{
2109
    int i;
2110

    
2111
    srand(time(NULL)+getpid()+getpid()*987654+rand());
2112

    
2113
    for (i = 0 ; i < sizeof(vs->challenge) ; i++)
2114
        vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
2115
}
2116

    
2117
static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
2118
{
2119
    unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
2120
    int i, j, pwlen;
2121
    unsigned char key[8];
2122

    
2123
    if (!vs->vd->password || !vs->vd->password[0]) {
2124
        VNC_DEBUG("No password configured on server");
2125
        vnc_write_u32(vs, 1); /* Reject auth */
2126
        if (vs->minor >= 8) {
2127
            static const char err[] = "Authentication failed";
2128
            vnc_write_u32(vs, sizeof(err));
2129
            vnc_write(vs, err, sizeof(err));
2130
        }
2131
        vnc_flush(vs);
2132
        vnc_client_error(vs);
2133
        return 0;
2134
    }
2135

    
2136
    memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
2137

    
2138
    /* Calculate the expected challenge response */
2139
    pwlen = strlen(vs->vd->password);
2140
    for (i=0; i<sizeof(key); i++)
2141
        key[i] = i<pwlen ? vs->vd->password[i] : 0;
2142
    deskey(key, EN0);
2143
    for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
2144
        des(response+j, response+j);
2145

    
2146
    /* Compare expected vs actual challenge response */
2147
    if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
2148
        VNC_DEBUG("Client challenge reponse did not match\n");
2149
        vnc_write_u32(vs, 1); /* Reject auth */
2150
        if (vs->minor >= 8) {
2151
            static const char err[] = "Authentication failed";
2152
            vnc_write_u32(vs, sizeof(err));
2153
            vnc_write(vs, err, sizeof(err));
2154
        }
2155
        vnc_flush(vs);
2156
        vnc_client_error(vs);
2157
    } else {
2158
        VNC_DEBUG("Accepting VNC challenge response\n");
2159
        vnc_write_u32(vs, 0); /* Accept auth */
2160
        vnc_flush(vs);
2161

    
2162
        start_client_init(vs);
2163
    }
2164
    return 0;
2165
}
2166

    
2167
void start_auth_vnc(VncState *vs)
2168
{
2169
    make_challenge(vs);
2170
    /* Send client a 'random' challenge */
2171
    vnc_write(vs, vs->challenge, sizeof(vs->challenge));
2172
    vnc_flush(vs);
2173

    
2174
    vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
2175
}
2176

    
2177

    
2178
static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
2179
{
2180
    /* We only advertise 1 auth scheme at a time, so client
2181
     * must pick the one we sent. Verify this */
2182
    if (data[0] != vs->vd->auth) { /* Reject auth */
2183
       VNC_DEBUG("Reject auth %d because it didn't match advertized\n", (int)data[0]);
2184
       vnc_write_u32(vs, 1);
2185
       if (vs->minor >= 8) {
2186
           static const char err[] = "Authentication failed";
2187
           vnc_write_u32(vs, sizeof(err));
2188
           vnc_write(vs, err, sizeof(err));
2189
       }
2190
       vnc_client_error(vs);
2191
    } else { /* Accept requested auth */
2192
       VNC_DEBUG("Client requested auth %d\n", (int)data[0]);
2193
       switch (vs->vd->auth) {
2194
       case VNC_AUTH_NONE:
2195
           VNC_DEBUG("Accept auth none\n");
2196
           if (vs->minor >= 8) {
2197
               vnc_write_u32(vs, 0); /* Accept auth completion */
2198
               vnc_flush(vs);
2199
           }
2200
           start_client_init(vs);
2201
           break;
2202

    
2203
       case VNC_AUTH_VNC:
2204
           VNC_DEBUG("Start VNC auth\n");
2205
           start_auth_vnc(vs);
2206
           break;
2207

    
2208
#ifdef CONFIG_VNC_TLS
2209
       case VNC_AUTH_VENCRYPT:
2210
           VNC_DEBUG("Accept VeNCrypt auth\n");;
2211
           start_auth_vencrypt(vs);
2212
           break;
2213
#endif /* CONFIG_VNC_TLS */
2214

    
2215
#ifdef CONFIG_VNC_SASL
2216
       case VNC_AUTH_SASL:
2217
           VNC_DEBUG("Accept SASL auth\n");
2218
           start_auth_sasl(vs);
2219
           break;
2220
#endif /* CONFIG_VNC_SASL */
2221

    
2222
       default: /* Should not be possible, but just in case */
2223
           VNC_DEBUG("Reject auth %d server code bug\n", vs->vd->auth);
2224
           vnc_write_u8(vs, 1);
2225
           if (vs->minor >= 8) {
2226
               static const char err[] = "Authentication failed";
2227
               vnc_write_u32(vs, sizeof(err));
2228
               vnc_write(vs, err, sizeof(err));
2229
           }
2230
           vnc_client_error(vs);
2231
       }
2232
    }
2233
    return 0;
2234
}
2235

    
2236
static int protocol_version(VncState *vs, uint8_t *version, size_t len)
2237
{
2238
    char local[13];
2239

    
2240
    memcpy(local, version, 12);
2241
    local[12] = 0;
2242

    
2243
    if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
2244
        VNC_DEBUG("Malformed protocol version %s\n", local);
2245
        vnc_client_error(vs);
2246
        return 0;
2247
    }
2248
    VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
2249
    if (vs->major != 3 ||
2250
        (vs->minor != 3 &&
2251
         vs->minor != 4 &&
2252
         vs->minor != 5 &&
2253
         vs->minor != 7 &&
2254
         vs->minor != 8)) {
2255
        VNC_DEBUG("Unsupported client version\n");
2256
        vnc_write_u32(vs, VNC_AUTH_INVALID);
2257
        vnc_flush(vs);
2258
        vnc_client_error(vs);
2259
        return 0;
2260
    }
2261
    /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
2262
     * as equivalent to v3.3 by servers
2263
     */
2264
    if (vs->minor == 4 || vs->minor == 5)
2265
        vs->minor = 3;
2266

    
2267
    if (vs->minor == 3) {
2268
        if (vs->vd->auth == VNC_AUTH_NONE) {
2269
            VNC_DEBUG("Tell client auth none\n");
2270
            vnc_write_u32(vs, vs->vd->auth);
2271
            vnc_flush(vs);
2272
            start_client_init(vs);
2273
       } else if (vs->vd->auth == VNC_AUTH_VNC) {
2274
            VNC_DEBUG("Tell client VNC auth\n");
2275
            vnc_write_u32(vs, vs->vd->auth);
2276
            vnc_flush(vs);
2277
            start_auth_vnc(vs);
2278
       } else {
2279
            VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->vd->auth);
2280
            vnc_write_u32(vs, VNC_AUTH_INVALID);
2281
            vnc_flush(vs);
2282
            vnc_client_error(vs);
2283
       }
2284
    } else {
2285
        VNC_DEBUG("Telling client we support auth %d\n", vs->vd->auth);
2286
        vnc_write_u8(vs, 1); /* num auth */
2287
        vnc_write_u8(vs, vs->vd->auth);
2288
        vnc_read_when(vs, protocol_client_auth, 1);
2289
        vnc_flush(vs);
2290
    }
2291

    
2292
    return 0;
2293
}
2294

    
2295
static int vnc_refresh_server_surface(VncDisplay *vd)
2296
{
2297
    int y;
2298
    uint8_t *guest_row;
2299
    uint8_t *server_row;
2300
    int cmp_bytes;
2301
    uint32_t width_mask[VNC_DIRTY_WORDS];
2302
    VncState *vs = NULL;
2303
    int has_dirty = 0;
2304

    
2305
    /*
2306
     * Walk through the guest dirty map.
2307
     * Check and copy modified bits from guest to server surface.
2308
     * Update server dirty map.
2309
     */
2310
    vnc_set_bits(width_mask, (ds_get_width(vd->ds) / 16), VNC_DIRTY_WORDS);
2311
    cmp_bytes = 16 * ds_get_bytes_per_pixel(vd->ds);
2312
    guest_row  = vd->guest.ds->data;
2313
    server_row = vd->server->data;
2314
    for (y = 0; y < vd->guest.ds->height; y++) {
2315
        if (vnc_and_bits(vd->guest.dirty[y], width_mask, VNC_DIRTY_WORDS)) {
2316
            int x;
2317
            uint8_t *guest_ptr;
2318
            uint8_t *server_ptr;
2319

    
2320
            guest_ptr  = guest_row;
2321
            server_ptr = server_row;
2322

    
2323
            for (x = 0; x < vd->guest.ds->width;
2324
                    x += 16, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
2325
                if (!vnc_get_bit(vd->guest.dirty[y], (x / 16)))
2326
                    continue;
2327
                vnc_clear_bit(vd->guest.dirty[y], (x / 16));
2328
                if (memcmp(server_ptr, guest_ptr, cmp_bytes) == 0)
2329
                    continue;
2330
                memcpy(server_ptr, guest_ptr, cmp_bytes);
2331
                vs = vd->clients;
2332
                while (vs != NULL) {
2333
                    vnc_set_bit(vs->dirty[y], (x / 16));
2334
                    vs = vs->next;
2335
                }
2336
                has_dirty++;
2337
            }
2338
        }
2339
        guest_row  += ds_get_linesize(vd->ds);
2340
        server_row += ds_get_linesize(vd->ds);
2341
    }
2342
    return has_dirty;
2343
}
2344

    
2345
static void vnc_refresh(void *opaque)
2346
{
2347
    VncDisplay *vd = opaque;
2348
    VncState *vs = NULL, *vn = NULL;
2349
    int has_dirty = 0, rects = 0;
2350

    
2351
    vga_hw_update();
2352

    
2353
    has_dirty = vnc_refresh_server_surface(vd);
2354

    
2355
    vs = vd->clients;
2356
    while (vs != NULL) {
2357
        vn = vs->next;
2358
        rects += vnc_update_client(vs, has_dirty);
2359
        /* vs might be free()ed here */
2360
        vs = vn;
2361
    }
2362
    /* vd->timer could be NULL now if the last client disconnected,
2363
     * in this case don't update the timer */
2364
    if (vd->timer == NULL)
2365
        return;
2366

    
2367
    if (has_dirty && rects) {
2368
        vd->timer_interval /= 2;
2369
        if (vd->timer_interval < VNC_REFRESH_INTERVAL_BASE)
2370
            vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
2371
    } else {
2372
        vd->timer_interval += VNC_REFRESH_INTERVAL_INC;
2373
        if (vd->timer_interval > VNC_REFRESH_INTERVAL_MAX)
2374
            vd->timer_interval = VNC_REFRESH_INTERVAL_MAX;
2375
    }
2376
    qemu_mod_timer(vd->timer, qemu_get_clock(rt_clock) + vd->timer_interval);
2377
}
2378

    
2379
static void vnc_init_timer(VncDisplay *vd)
2380
{
2381
    vd->timer_interval = VNC_REFRESH_INTERVAL_BASE;
2382
    if (vd->timer == NULL && vd->clients != NULL) {
2383
        vd->timer = qemu_new_timer(rt_clock, vnc_refresh, vd);
2384
        vnc_refresh(vd);
2385
    }
2386
}
2387

    
2388
static void vnc_remove_timer(VncDisplay *vd)
2389
{
2390
    if (vd->timer != NULL && vd->clients == NULL) {
2391
        qemu_del_timer(vd->timer);
2392
        qemu_free_timer(vd->timer);
2393
        vd->timer = NULL;
2394
    }
2395
}
2396

    
2397
static void vnc_connect(VncDisplay *vd, int csock)
2398
{
2399
    VncState *vs = qemu_mallocz(sizeof(VncState));
2400
    vs->csock = csock;
2401

    
2402
    VNC_DEBUG("New client on socket %d\n", csock);
2403
    dcl->idle = 0;
2404
    socket_set_nonblock(vs->csock);
2405
    qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
2406

    
2407
    vnc_client_cache_addr(vs);
2408
    vnc_qmp_event(vs, QEVENT_VNC_CONNECTED);
2409

    
2410
    vs->vd = vd;
2411
    vs->ds = vd->ds;
2412
    vs->last_x = -1;
2413
    vs->last_y = -1;
2414

    
2415
    vs->as.freq = 44100;
2416
    vs->as.nchannels = 2;
2417
    vs->as.fmt = AUD_FMT_S16;
2418
    vs->as.endianness = 0;
2419

    
2420
    vs->next = vd->clients;
2421
    vd->clients = vs;
2422

    
2423
    vga_hw_update();
2424

    
2425
    vnc_write(vs, "RFB 003.008\n", 12);
2426
    vnc_flush(vs);
2427
    vnc_read_when(vs, protocol_version, 12);
2428
    reset_keys(vs);
2429

    
2430
    vnc_init_timer(vd);
2431

    
2432
    /* vs might be free()ed here */
2433
}
2434

    
2435
static void vnc_listen_read(void *opaque)
2436
{
2437
    VncDisplay *vs = opaque;
2438
    struct sockaddr_in addr;
2439
    socklen_t addrlen = sizeof(addr);
2440

    
2441
    /* Catch-up */
2442
    vga_hw_update();
2443

    
2444
    int csock = qemu_accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
2445
    if (csock != -1) {
2446
        vnc_connect(vs, csock);
2447
    }
2448
}
2449

    
2450
void vnc_display_init(DisplayState *ds)
2451
{
2452
    VncDisplay *vs = qemu_mallocz(sizeof(*vs));
2453

    
2454
    dcl = qemu_mallocz(sizeof(DisplayChangeListener));
2455

    
2456
    ds->opaque = vs;
2457
    dcl->idle = 1;
2458
    vnc_display = vs;
2459

    
2460
    vs->lsock = -1;
2461

    
2462
    vs->ds = ds;
2463

    
2464
    if (keyboard_layout)
2465
        vs->kbd_layout = init_keyboard_layout(name2keysym, keyboard_layout);
2466
    else
2467
        vs->kbd_layout = init_keyboard_layout(name2keysym, "en-us");
2468

    
2469
    if (!vs->kbd_layout)
2470
        exit(1);
2471

    
2472
    dcl->dpy_copy = vnc_dpy_copy;
2473
    dcl->dpy_update = vnc_dpy_update;
2474
    dcl->dpy_resize = vnc_dpy_resize;
2475
    dcl->dpy_setdata = vnc_dpy_setdata;
2476
    register_displaychangelistener(ds, dcl);
2477
}
2478

    
2479

    
2480
void vnc_display_close(DisplayState *ds)
2481
{
2482
    VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2483

    
2484
    if (!vs)
2485
        return;
2486
    if (vs->display) {
2487
        qemu_free(vs->display);
2488
        vs->display = NULL;
2489
    }
2490
    if (vs->lsock != -1) {
2491
        qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);
2492
        close(vs->lsock);
2493
        vs->lsock = -1;
2494
    }
2495
    vs->auth = VNC_AUTH_INVALID;
2496
#ifdef CONFIG_VNC_TLS
2497
    vs->subauth = VNC_AUTH_INVALID;
2498
    vs->tls.x509verify = 0;
2499
#endif
2500
}
2501

    
2502
int vnc_display_password(DisplayState *ds, const char *password)
2503
{
2504
    VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2505

    
2506
    if (!vs) {
2507
        return -1;
2508
    }
2509

    
2510
    if (vs->password) {
2511
        qemu_free(vs->password);
2512
        vs->password = NULL;
2513
    }
2514
    if (password && password[0]) {
2515
        if (!(vs->password = qemu_strdup(password)))
2516
            return -1;
2517
        if (vs->auth == VNC_AUTH_NONE) {
2518
            vs->auth = VNC_AUTH_VNC;
2519
        }
2520
    } else {
2521
        vs->auth = VNC_AUTH_NONE;
2522
    }
2523

    
2524
    return 0;
2525
}
2526

    
2527
char *vnc_display_local_addr(DisplayState *ds)
2528
{
2529
    VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2530
    
2531
    return vnc_socket_local_addr("%s:%s", vs->lsock);
2532
}
2533

    
2534
int vnc_display_open(DisplayState *ds, const char *display)
2535
{
2536
    VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
2537
    const char *options;
2538
    int password = 0;
2539
    int reverse = 0;
2540
#ifdef CONFIG_VNC_TLS
2541
    int tls = 0, x509 = 0;
2542
#endif
2543
#ifdef CONFIG_VNC_SASL
2544
    int sasl = 0;
2545
    int saslErr;
2546
#endif
2547
    int acl = 0;
2548

    
2549
    if (!vnc_display)
2550
        return -1;
2551
    vnc_display_close(ds);
2552
    if (strcmp(display, "none") == 0)
2553
        return 0;
2554

    
2555
    if (!(vs->display = strdup(display)))
2556
        return -1;
2557

    
2558
    options = display;
2559
    while ((options = strchr(options, ','))) {
2560
        options++;
2561
        if (strncmp(options, "password", 8) == 0) {
2562
            password = 1; /* Require password auth */
2563
        } else if (strncmp(options, "reverse", 7) == 0) {
2564
            reverse = 1;
2565
#ifdef CONFIG_VNC_SASL
2566
        } else if (strncmp(options, "sasl", 4) == 0) {
2567
            sasl = 1; /* Require SASL auth */
2568
#endif
2569
#ifdef CONFIG_VNC_TLS
2570
        } else if (strncmp(options, "tls", 3) == 0) {
2571
            tls = 1; /* Require TLS */
2572
        } else if (strncmp(options, "x509", 4) == 0) {
2573
            char *start, *end;
2574
            x509 = 1; /* Require x509 certificates */
2575
            if (strncmp(options, "x509verify", 10) == 0)
2576
                vs->tls.x509verify = 1; /* ...and verify client certs */
2577

    
2578
            /* Now check for 'x509=/some/path' postfix
2579
             * and use that to setup x509 certificate/key paths */
2580
            start = strchr(options, '=');
2581
            end = strchr(options, ',');
2582
            if (start && (!end || (start < end))) {
2583
                int len = end ? end-(start+1) : strlen(start+1);
2584
                char *path = qemu_strndup(start + 1, len);
2585

    
2586
                VNC_DEBUG("Trying certificate path '%s'\n", path);
2587
                if (vnc_tls_set_x509_creds_dir(vs, path) < 0) {
2588
                    fprintf(stderr, "Failed to find x509 certificates/keys in %s\n", path);
2589
                    qemu_free(path);
2590
                    qemu_free(vs->display);
2591
                    vs->display = NULL;
2592
                    return -1;
2593
                }
2594
                qemu_free(path);
2595
            } else {
2596
                fprintf(stderr, "No certificate path provided\n");
2597
                qemu_free(vs->display);
2598
                vs->display = NULL;
2599
                return -1;
2600
            }
2601
#endif
2602
        } else if (strncmp(options, "acl", 3) == 0) {
2603
            acl = 1;
2604
        }
2605
    }
2606

    
2607
#ifdef CONFIG_VNC_TLS
2608
    if (acl && x509 && vs->tls.x509verify) {
2609
        if (!(vs->tls.acl = qemu_acl_init("vnc.x509dname"))) {
2610
            fprintf(stderr, "Failed to create x509 dname ACL\n");
2611
            exit(1);
2612
        }
2613
    }
2614
#endif
2615
#ifdef CONFIG_VNC_SASL
2616
    if (acl && sasl) {
2617
        if (!(vs->sasl.acl = qemu_acl_init("vnc.username"))) {
2618
            fprintf(stderr, "Failed to create username ACL\n");
2619
            exit(1);
2620
        }
2621
    }
2622
#endif
2623

    
2624
    /*
2625
     * Combinations we support here:
2626
     *
2627
     *  - no-auth                (clear text, no auth)
2628
     *  - password               (clear text, weak auth)
2629
     *  - sasl                   (encrypt, good auth *IF* using Kerberos via GSSAPI)
2630
     *  - tls                    (encrypt, weak anonymous creds, no auth)
2631
     *  - tls + password         (encrypt, weak anonymous creds, weak auth)
2632
     *  - tls + sasl             (encrypt, weak anonymous creds, good auth)
2633
     *  - tls + x509             (encrypt, good x509 creds, no auth)
2634
     *  - tls + x509 + password  (encrypt, good x509 creds, weak auth)
2635
     *  - tls + x509 + sasl      (encrypt, good x509 creds, good auth)
2636
     *
2637
     * NB1. TLS is a stackable auth scheme.
2638
     * NB2. the x509 schemes have option to validate a client cert dname
2639
     */
2640
    if (password) {
2641
#ifdef CONFIG_VNC_TLS
2642
        if (tls) {
2643
            vs->auth = VNC_AUTH_VENCRYPT;
2644
            if (x509) {
2645
                VNC_DEBUG("Initializing VNC server with x509 password auth\n");
2646
                vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;
2647
            } else {
2648
                VNC_DEBUG("Initializing VNC server with TLS password auth\n");
2649
                vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
2650
            }
2651
        } else {
2652
#endif /* CONFIG_VNC_TLS */
2653
            VNC_DEBUG("Initializing VNC server with password auth\n");
2654
            vs->auth = VNC_AUTH_VNC;
2655
#ifdef CONFIG_VNC_TLS
2656
            vs->subauth = VNC_AUTH_INVALID;
2657
        }
2658
#endif /* CONFIG_VNC_TLS */
2659
#ifdef CONFIG_VNC_SASL
2660
    } else if (sasl) {
2661
#ifdef CONFIG_VNC_TLS
2662
        if (tls) {
2663
            vs->auth = VNC_AUTH_VENCRYPT;
2664
            if (x509) {
2665
                VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
2666
                vs->subauth = VNC_AUTH_VENCRYPT_X509SASL;
2667
            } else {
2668
                VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
2669
                vs->subauth = VNC_AUTH_VENCRYPT_TLSSASL;
2670
            }
2671
        } else {
2672
#endif /* CONFIG_VNC_TLS */
2673
            VNC_DEBUG("Initializing VNC server with SASL auth\n");
2674
            vs->auth = VNC_AUTH_SASL;
2675
#ifdef CONFIG_VNC_TLS
2676
            vs->subauth = VNC_AUTH_INVALID;
2677
        }
2678
#endif /* CONFIG_VNC_TLS */
2679
#endif /* CONFIG_VNC_SASL */
2680
    } else {
2681
#ifdef CONFIG_VNC_TLS
2682
        if (tls) {
2683
            vs->auth = VNC_AUTH_VENCRYPT;
2684
            if (x509) {
2685
                VNC_DEBUG("Initializing VNC server with x509 no auth\n");
2686
                vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;
2687
            } else {
2688
                VNC_DEBUG("Initializing VNC server with TLS no auth\n");
2689
                vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
2690
            }
2691
        } else {
2692
#endif
2693
            VNC_DEBUG("Initializing VNC server with no auth\n");
2694
            vs->auth = VNC_AUTH_NONE;
2695
#ifdef CONFIG_VNC_TLS
2696
            vs->subauth = VNC_AUTH_INVALID;
2697
        }
2698
#endif
2699
    }
2700

    
2701
#ifdef CONFIG_VNC_SASL
2702
    if ((saslErr = sasl_server_init(NULL, "qemu")) != SASL_OK) {
2703
        fprintf(stderr, "Failed to initialize SASL auth %s",
2704
                sasl_errstring(saslErr, NULL, NULL));
2705
        free(vs->display);
2706
        vs->display = NULL;
2707
        return -1;
2708
    }
2709
#endif
2710

    
2711
    if (reverse) {
2712
        /* connect to viewer */
2713
        if (strncmp(display, "unix:", 5) == 0)
2714
            vs->lsock = unix_connect(display+5);
2715
        else
2716
            vs->lsock = inet_connect(display, SOCK_STREAM);
2717
        if (-1 == vs->lsock) {
2718
            free(vs->display);
2719
            vs->display = NULL;
2720
            return -1;
2721
        } else {
2722
            int csock = vs->lsock;
2723
            vs->lsock = -1;
2724
            vnc_connect(vs, csock);
2725
        }
2726
        return 0;
2727

    
2728
    } else {
2729
        /* listen for connects */
2730
        char *dpy;
2731
        dpy = qemu_malloc(256);
2732
        if (strncmp(display, "unix:", 5) == 0) {
2733
            pstrcpy(dpy, 256, "unix:");
2734
            vs->lsock = unix_listen(display+5, dpy+5, 256-5);
2735
        } else {
2736
            vs->lsock = inet_listen(display, dpy, 256, SOCK_STREAM, 5900);
2737
        }
2738
        if (-1 == vs->lsock) {
2739
            free(dpy);
2740
            return -1;
2741
        } else {
2742
            free(vs->display);
2743
            vs->display = dpy;
2744
        }
2745
    }
2746
    return qemu_set_fd_handler2(vs->lsock, NULL, vnc_listen_read, NULL, vs);
2747
}