Statistics
| Branch: | Revision:

root / vnc.c @ 8686c490

History | View | Annotate | Download (58.2 kB)

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

    
26
#include "qemu-common.h"
27
#include "console.h"
28
#include "sysemu.h"
29
#include "qemu_socket.h"
30
#include "qemu-timer.h"
31

    
32
#define VNC_REFRESH_INTERVAL (1000 / 30)
33

    
34
#include "vnc_keysym.h"
35
#include "keymaps.c"
36
#include "d3des.h"
37

    
38
#if CONFIG_VNC_TLS
39
#include <gnutls/gnutls.h>
40
#include <gnutls/x509.h>
41
#endif /* CONFIG_VNC_TLS */
42

    
43
// #define _VNC_DEBUG 1
44

    
45
#if _VNC_DEBUG
46
#define VNC_DEBUG(fmt, ...) do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
47

    
48
#if CONFIG_VNC_TLS && _VNC_DEBUG >= 2
49
/* Very verbose, so only enabled for _VNC_DEBUG >= 2 */
50
static void vnc_debug_gnutls_log(int level, const char* str) {
51
    VNC_DEBUG("%d %s", level, str);
52
}
53
#endif /* CONFIG_VNC_TLS && _VNC_DEBUG */
54
#else
55
#define VNC_DEBUG(fmt, ...) do { } while (0)
56
#endif
57

    
58

    
59
typedef struct Buffer
60
{
61
    size_t capacity;
62
    size_t offset;
63
    uint8_t *buffer;
64
} Buffer;
65

    
66
typedef struct VncState VncState;
67

    
68
typedef int VncReadEvent(VncState *vs, uint8_t *data, size_t len);
69

    
70
typedef void VncWritePixels(VncState *vs, void *data, int size);
71

    
72
typedef void VncSendHextileTile(VncState *vs,
73
                                int x, int y, int w, int h,
74
                                uint32_t *last_bg,
75
                                uint32_t *last_fg,
76
                                int *has_bg, int *has_fg);
77

    
78
#define VNC_MAX_WIDTH 2048
79
#define VNC_MAX_HEIGHT 2048
80
#define VNC_DIRTY_WORDS (VNC_MAX_WIDTH / (16 * 32))
81

    
82
#define VNC_AUTH_CHALLENGE_SIZE 16
83

    
84
enum {
85
    VNC_AUTH_INVALID = 0,
86
    VNC_AUTH_NONE = 1,
87
    VNC_AUTH_VNC = 2,
88
    VNC_AUTH_RA2 = 5,
89
    VNC_AUTH_RA2NE = 6,
90
    VNC_AUTH_TIGHT = 16,
91
    VNC_AUTH_ULTRA = 17,
92
    VNC_AUTH_TLS = 18,
93
    VNC_AUTH_VENCRYPT = 19
94
};
95

    
96
#if CONFIG_VNC_TLS
97
enum {
98
    VNC_WIREMODE_CLEAR,
99
    VNC_WIREMODE_TLS,
100
};
101

    
102
enum {
103
    VNC_AUTH_VENCRYPT_PLAIN = 256,
104
    VNC_AUTH_VENCRYPT_TLSNONE = 257,
105
    VNC_AUTH_VENCRYPT_TLSVNC = 258,
106
    VNC_AUTH_VENCRYPT_TLSPLAIN = 259,
107
    VNC_AUTH_VENCRYPT_X509NONE = 260,
108
    VNC_AUTH_VENCRYPT_X509VNC = 261,
109
    VNC_AUTH_VENCRYPT_X509PLAIN = 262,
110
};
111

    
112
#if CONFIG_VNC_TLS
113
#define X509_CA_CERT_FILE "ca-cert.pem"
114
#define X509_CA_CRL_FILE "ca-crl.pem"
115
#define X509_SERVER_KEY_FILE "server-key.pem"
116
#define X509_SERVER_CERT_FILE "server-cert.pem"
117
#endif
118

    
119
#endif /* CONFIG_VNC_TLS */
120

    
121
struct VncState
122
{
123
    QEMUTimer *timer;
124
    int lsock;
125
    int csock;
126
    DisplayState *ds;
127
    int need_update;
128
    int width;
129
    int height;
130
    uint32_t dirty_row[VNC_MAX_HEIGHT][VNC_DIRTY_WORDS];
131
    char *old_data;
132
    int depth; /* internal VNC frame buffer byte per pixel */
133
    int has_resize;
134
    int has_hextile;
135
    int has_pointer_type_change;
136
    int absolute;
137
    int last_x;
138
    int last_y;
139

    
140
    int major;
141
    int minor;
142

    
143
    char *display;
144
    char *password;
145
    int auth;
146
#if CONFIG_VNC_TLS
147
    int subauth;
148
    int x509verify;
149

    
150
    char *x509cacert;
151
    char *x509cacrl;
152
    char *x509cert;
153
    char *x509key;
154
#endif
155
    char challenge[VNC_AUTH_CHALLENGE_SIZE];
156

    
157
#if CONFIG_VNC_TLS
158
    int wiremode;
159
    gnutls_session_t tls_session;
160
#endif
161

    
162
    Buffer output;
163
    Buffer input;
164
    kbd_layout_t *kbd_layout;
165
    /* current output mode information */
166
    VncWritePixels *write_pixels;
167
    VncSendHextileTile *send_hextile_tile;
168
    int pix_bpp, pix_big_endian;
169
    int red_shift, red_max, red_shift1;
170
    int green_shift, green_max, green_shift1;
171
    int blue_shift, blue_max, blue_shift1;
172

    
173
    VncReadEvent *read_handler;
174
    size_t read_handler_expect;
175
    /* input */
176
    uint8_t modifiers_state[256];
177
};
178

    
179
static VncState *vnc_state; /* needed for info vnc */
180

    
181
void do_info_vnc(void)
182
{
183
    if (vnc_state == NULL)
184
        term_printf("VNC server disabled\n");
185
    else {
186
        term_printf("VNC server active on: ");
187
        term_print_filename(vnc_state->display);
188
        term_printf("\n");
189

    
190
        if (vnc_state->csock == -1)
191
            term_printf("No client connected\n");
192
        else
193
            term_printf("Client connected\n");
194
    }
195
}
196

    
197
/* TODO
198
   1) Get the queue working for IO.
199
   2) there is some weirdness when using the -S option (the screen is grey
200
      and not totally invalidated
201
   3) resolutions > 1024
202
*/
203

    
204
static void vnc_write(VncState *vs, const void *data, size_t len);
205
static void vnc_write_u32(VncState *vs, uint32_t value);
206
static void vnc_write_s32(VncState *vs, int32_t value);
207
static void vnc_write_u16(VncState *vs, uint16_t value);
208
static void vnc_write_u8(VncState *vs, uint8_t value);
209
static void vnc_flush(VncState *vs);
210
static void vnc_update_client(void *opaque);
211
static void vnc_client_read(void *opaque);
212

    
213
static inline void vnc_set_bit(uint32_t *d, int k)
214
{
215
    d[k >> 5] |= 1 << (k & 0x1f);
216
}
217

    
218
static inline void vnc_clear_bit(uint32_t *d, int k)
219
{
220
    d[k >> 5] &= ~(1 << (k & 0x1f));
221
}
222

    
223
static inline void vnc_set_bits(uint32_t *d, int n, int nb_words)
224
{
225
    int j;
226

    
227
    j = 0;
228
    while (n >= 32) {
229
        d[j++] = -1;
230
        n -= 32;
231
    }
232
    if (n > 0)
233
        d[j++] = (1 << n) - 1;
234
    while (j < nb_words)
235
        d[j++] = 0;
236
}
237

    
238
static inline int vnc_get_bit(const uint32_t *d, int k)
239
{
240
    return (d[k >> 5] >> (k & 0x1f)) & 1;
241
}
242

    
243
static inline int vnc_and_bits(const uint32_t *d1, const uint32_t *d2,
244
                               int nb_words)
245
{
246
    int i;
247
    for(i = 0; i < nb_words; i++) {
248
        if ((d1[i] & d2[i]) != 0)
249
            return 1;
250
    }
251
    return 0;
252
}
253

    
254
static void vnc_dpy_update(DisplayState *ds, int x, int y, int w, int h)
255
{
256
    VncState *vs = ds->opaque;
257
    int i;
258

    
259
    h += y;
260

    
261
    /* round x down to ensure the loop only spans one 16-pixel block per,
262
       iteration.  otherwise, if (x % 16) != 0, the last iteration may span
263
       two 16-pixel blocks but we only mark the first as dirty
264
    */
265
    w += (x % 16);
266
    x -= (x % 16);
267

    
268
    for (; y < h; y++)
269
        for (i = 0; i < w; i += 16)
270
            vnc_set_bit(vs->dirty_row[y], (x + i) / 16);
271
}
272

    
273
static void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
274
                                   int32_t encoding)
275
{
276
    vnc_write_u16(vs, x);
277
    vnc_write_u16(vs, y);
278
    vnc_write_u16(vs, w);
279
    vnc_write_u16(vs, h);
280

    
281
    vnc_write_s32(vs, encoding);
282
}
283

    
284
static void vnc_dpy_resize(DisplayState *ds, int w, int h)
285
{
286
    int size_changed;
287
    VncState *vs = ds->opaque;
288

    
289
    ds->data = realloc(ds->data, w * h * vs->depth);
290
    vs->old_data = realloc(vs->old_data, w * h * vs->depth);
291

    
292
    if (ds->data == NULL || vs->old_data == NULL) {
293
        fprintf(stderr, "vnc: memory allocation failed\n");
294
        exit(1);
295
    }
296

    
297
    if (ds->depth != vs->depth * 8) {
298
        ds->depth = vs->depth * 8;
299
        console_color_init(ds);
300
    }
301
    size_changed = ds->width != w || ds->height != h;
302
    ds->width = w;
303
    ds->height = h;
304
    ds->linesize = w * vs->depth;
305
    if (vs->csock != -1 && vs->has_resize && size_changed) {
306
        vnc_write_u8(vs, 0);  /* msg id */
307
        vnc_write_u8(vs, 0);
308
        vnc_write_u16(vs, 1); /* number of rects */
309
        vnc_framebuffer_update(vs, 0, 0, ds->width, ds->height, -223);
310
        vnc_flush(vs);
311
        vs->width = ds->width;
312
        vs->height = ds->height;
313
    }
314
}
315

    
316
/* fastest code */
317
static void vnc_write_pixels_copy(VncState *vs, void *pixels, int size)
318
{
319
    vnc_write(vs, pixels, size);
320
}
321

    
322
/* slowest but generic code. */
323
static void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
324
{
325
    unsigned int r, g, b;
326

    
327
    r = (v >> vs->red_shift1) & vs->red_max;
328
    g = (v >> vs->green_shift1) & vs->green_max;
329
    b = (v >> vs->blue_shift1) & vs->blue_max;
330
    v = (r << vs->red_shift) |
331
        (g << vs->green_shift) |
332
        (b << vs->blue_shift);
333
    switch(vs->pix_bpp) {
334
    case 1:
335
        buf[0] = v;
336
        break;
337
    case 2:
338
        if (vs->pix_big_endian) {
339
            buf[0] = v >> 8;
340
            buf[1] = v;
341
        } else {
342
            buf[1] = v >> 8;
343
            buf[0] = v;
344
        }
345
        break;
346
    default:
347
    case 4:
348
        if (vs->pix_big_endian) {
349
            buf[0] = v >> 24;
350
            buf[1] = v >> 16;
351
            buf[2] = v >> 8;
352
            buf[3] = v;
353
        } else {
354
            buf[3] = v >> 24;
355
            buf[2] = v >> 16;
356
            buf[1] = v >> 8;
357
            buf[0] = v;
358
        }
359
        break;
360
    }
361
}
362

    
363
static void vnc_write_pixels_generic(VncState *vs, void *pixels1, int size)
364
{
365
    uint32_t *pixels = pixels1;
366
    uint8_t buf[4];
367
    int n, i;
368

    
369
    n = size >> 2;
370
    for(i = 0; i < n; i++) {
371
        vnc_convert_pixel(vs, buf, pixels[i]);
372
        vnc_write(vs, buf, vs->pix_bpp);
373
    }
374
}
375

    
376
static void send_framebuffer_update_raw(VncState *vs, int x, int y, int w, int h)
377
{
378
    int i;
379
    uint8_t *row;
380

    
381
    vnc_framebuffer_update(vs, x, y, w, h, 0);
382

    
383
    row = vs->ds->data + y * vs->ds->linesize + x * vs->depth;
384
    for (i = 0; i < h; i++) {
385
        vs->write_pixels(vs, row, w * vs->depth);
386
        row += vs->ds->linesize;
387
    }
388
}
389

    
390
static void hextile_enc_cord(uint8_t *ptr, int x, int y, int w, int h)
391
{
392
    ptr[0] = ((x & 0x0F) << 4) | (y & 0x0F);
393
    ptr[1] = (((w - 1) & 0x0F) << 4) | ((h - 1) & 0x0F);
394
}
395

    
396
#define BPP 8
397
#include "vnchextile.h"
398
#undef BPP
399

    
400
#define BPP 16
401
#include "vnchextile.h"
402
#undef BPP
403

    
404
#define BPP 32
405
#include "vnchextile.h"
406
#undef BPP
407

    
408
#define GENERIC
409
#define BPP 32
410
#include "vnchextile.h"
411
#undef BPP
412
#undef GENERIC
413

    
414
static void send_framebuffer_update_hextile(VncState *vs, int x, int y, int w, int h)
415
{
416
    int i, j;
417
    int has_fg, has_bg;
418
    uint32_t last_fg32, last_bg32;
419

    
420
    vnc_framebuffer_update(vs, x, y, w, h, 5);
421

    
422
    has_fg = has_bg = 0;
423
    for (j = y; j < (y + h); j += 16) {
424
        for (i = x; i < (x + w); i += 16) {
425
            vs->send_hextile_tile(vs, i, j,
426
                                  MIN(16, x + w - i), MIN(16, y + h - j),
427
                                  &last_bg32, &last_fg32, &has_bg, &has_fg);
428
        }
429
    }
430
}
431

    
432
static void send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
433
{
434
        if (vs->has_hextile)
435
            send_framebuffer_update_hextile(vs, x, y, w, h);
436
        else
437
            send_framebuffer_update_raw(vs, x, y, w, h);
438
}
439

    
440
static void vnc_copy(DisplayState *ds, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
441
{
442
    int src, dst;
443
    uint8_t *src_row;
444
    uint8_t *dst_row;
445
    char *old_row;
446
    int y = 0;
447
    int pitch = ds->linesize;
448
    VncState *vs = ds->opaque;
449

    
450
    vnc_update_client(vs);
451

    
452
    if (dst_y > src_y) {
453
        y = h - 1;
454
        pitch = -pitch;
455
    }
456

    
457
    src = (ds->linesize * (src_y + y) + vs->depth * src_x);
458
    dst = (ds->linesize * (dst_y + y) + vs->depth * dst_x);
459

    
460
    src_row = ds->data + src;
461
    dst_row = ds->data + dst;
462
    old_row = vs->old_data + dst;
463

    
464
    for (y = 0; y < h; y++) {
465
        memmove(old_row, src_row, w * vs->depth);
466
        memmove(dst_row, src_row, w * vs->depth);
467
        src_row += pitch;
468
        dst_row += pitch;
469
        old_row += pitch;
470
    }
471

    
472
    vnc_write_u8(vs, 0);  /* msg id */
473
    vnc_write_u8(vs, 0);
474
    vnc_write_u16(vs, 1); /* number of rects */
475
    vnc_framebuffer_update(vs, dst_x, dst_y, w, h, 1);
476
    vnc_write_u16(vs, src_x);
477
    vnc_write_u16(vs, src_y);
478
    vnc_flush(vs);
479
}
480

    
481
static int find_dirty_height(VncState *vs, int y, int last_x, int x)
482
{
483
    int h;
484

    
485
    for (h = 1; h < (vs->height - y); h++) {
486
        int tmp_x;
487
        if (!vnc_get_bit(vs->dirty_row[y + h], last_x))
488
            break;
489
        for (tmp_x = last_x; tmp_x < x; tmp_x++)
490
            vnc_clear_bit(vs->dirty_row[y + h], tmp_x);
491
    }
492

    
493
    return h;
494
}
495

    
496
static void vnc_update_client(void *opaque)
497
{
498
    VncState *vs = opaque;
499

    
500
    if (vs->need_update && vs->csock != -1) {
501
        int y;
502
        uint8_t *row;
503
        char *old_row;
504
        uint32_t width_mask[VNC_DIRTY_WORDS];
505
        int n_rectangles;
506
        int saved_offset;
507
        int has_dirty = 0;
508

    
509
        vga_hw_update();
510

    
511
        vnc_set_bits(width_mask, (vs->width / 16), VNC_DIRTY_WORDS);
512

    
513
        /* Walk through the dirty map and eliminate tiles that
514
           really aren't dirty */
515
        row = vs->ds->data;
516
        old_row = vs->old_data;
517

    
518
        for (y = 0; y < vs->height; y++) {
519
            if (vnc_and_bits(vs->dirty_row[y], width_mask, VNC_DIRTY_WORDS)) {
520
                int x;
521
                uint8_t *ptr;
522
                char *old_ptr;
523

    
524
                ptr = row;
525
                old_ptr = (char*)old_row;
526

    
527
                for (x = 0; x < vs->ds->width; x += 16) {
528
                    if (memcmp(old_ptr, ptr, 16 * vs->depth) == 0) {
529
                        vnc_clear_bit(vs->dirty_row[y], (x / 16));
530
                    } else {
531
                        has_dirty = 1;
532
                        memcpy(old_ptr, ptr, 16 * vs->depth);
533
                    }
534

    
535
                    ptr += 16 * vs->depth;
536
                    old_ptr += 16 * vs->depth;
537
                }
538
            }
539

    
540
            row += vs->ds->linesize;
541
            old_row += vs->ds->linesize;
542
        }
543

    
544
        if (!has_dirty) {
545
            qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);
546
            return;
547
        }
548

    
549
        /* Count rectangles */
550
        n_rectangles = 0;
551
        vnc_write_u8(vs, 0);  /* msg id */
552
        vnc_write_u8(vs, 0);
553
        saved_offset = vs->output.offset;
554
        vnc_write_u16(vs, 0);
555

    
556
        for (y = 0; y < vs->height; y++) {
557
            int x;
558
            int last_x = -1;
559
            for (x = 0; x < vs->width / 16; x++) {
560
                if (vnc_get_bit(vs->dirty_row[y], x)) {
561
                    if (last_x == -1) {
562
                        last_x = x;
563
                    }
564
                    vnc_clear_bit(vs->dirty_row[y], x);
565
                } else {
566
                    if (last_x != -1) {
567
                        int h = find_dirty_height(vs, y, last_x, x);
568
                        send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
569
                        n_rectangles++;
570
                    }
571
                    last_x = -1;
572
                }
573
            }
574
            if (last_x != -1) {
575
                int h = find_dirty_height(vs, y, last_x, x);
576
                send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
577
                n_rectangles++;
578
            }
579
        }
580
        vs->output.buffer[saved_offset] = (n_rectangles >> 8) & 0xFF;
581
        vs->output.buffer[saved_offset + 1] = n_rectangles & 0xFF;
582
        vnc_flush(vs);
583

    
584
    }
585

    
586
    if (vs->csock != -1) {
587
        qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);
588
    }
589

    
590
}
591

    
592
static int vnc_listen_poll(void *opaque)
593
{
594
    VncState *vs = opaque;
595
    if (vs->csock == -1)
596
        return 1;
597
    return 0;
598
}
599

    
600
static void buffer_reserve(Buffer *buffer, size_t len)
601
{
602
    if ((buffer->capacity - buffer->offset) < len) {
603
        buffer->capacity += (len + 1024);
604
        buffer->buffer = realloc(buffer->buffer, buffer->capacity);
605
        if (buffer->buffer == NULL) {
606
            fprintf(stderr, "vnc: out of memory\n");
607
            exit(1);
608
        }
609
    }
610
}
611

    
612
static int buffer_empty(Buffer *buffer)
613
{
614
    return buffer->offset == 0;
615
}
616

    
617
static uint8_t *buffer_end(Buffer *buffer)
618
{
619
    return buffer->buffer + buffer->offset;
620
}
621

    
622
static void buffer_reset(Buffer *buffer)
623
{
624
        buffer->offset = 0;
625
}
626

    
627
static void buffer_append(Buffer *buffer, const void *data, size_t len)
628
{
629
    memcpy(buffer->buffer + buffer->offset, data, len);
630
    buffer->offset += len;
631
}
632

    
633
static int vnc_client_io_error(VncState *vs, int ret, int last_errno)
634
{
635
    if (ret == 0 || ret == -1) {
636
        if (ret == -1) {
637
            switch (last_errno) {
638
                case EINTR:
639
                case EAGAIN:
640
#ifdef _WIN32
641
                case WSAEWOULDBLOCK:
642
#endif
643
                    return 0;
644
                default:
645
                    break;
646
            }
647
        }
648

    
649
        VNC_DEBUG("Closing down client sock %d %d\n", ret, ret < 0 ? last_errno : 0);
650
        qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
651
        closesocket(vs->csock);
652
        vs->csock = -1;
653
        buffer_reset(&vs->input);
654
        buffer_reset(&vs->output);
655
        vs->need_update = 0;
656
#if CONFIG_VNC_TLS
657
        if (vs->tls_session) {
658
            gnutls_deinit(vs->tls_session);
659
            vs->tls_session = NULL;
660
        }
661
        vs->wiremode = VNC_WIREMODE_CLEAR;
662
#endif /* CONFIG_VNC_TLS */
663
        return 0;
664
    }
665
    return ret;
666
}
667

    
668
static void vnc_client_error(VncState *vs)
669
{
670
    vnc_client_io_error(vs, -1, EINVAL);
671
}
672

    
673
static void vnc_client_write(void *opaque)
674
{
675
    long ret;
676
    VncState *vs = opaque;
677

    
678
#if CONFIG_VNC_TLS
679
    if (vs->tls_session) {
680
        ret = gnutls_write(vs->tls_session, vs->output.buffer, vs->output.offset);
681
        if (ret < 0) {
682
            if (ret == GNUTLS_E_AGAIN)
683
                errno = EAGAIN;
684
            else
685
                errno = EIO;
686
            ret = -1;
687
        }
688
    } else
689
#endif /* CONFIG_VNC_TLS */
690
        ret = send(vs->csock, vs->output.buffer, vs->output.offset, 0);
691
    ret = vnc_client_io_error(vs, ret, socket_error());
692
    if (!ret)
693
        return;
694

    
695
    memmove(vs->output.buffer, vs->output.buffer + ret, (vs->output.offset - ret));
696
    vs->output.offset -= ret;
697

    
698
    if (vs->output.offset == 0) {
699
        qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
700
    }
701
}
702

    
703
static void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
704
{
705
    vs->read_handler = func;
706
    vs->read_handler_expect = expecting;
707
}
708

    
709
static void vnc_client_read(void *opaque)
710
{
711
    VncState *vs = opaque;
712
    long ret;
713

    
714
    buffer_reserve(&vs->input, 4096);
715

    
716
#if CONFIG_VNC_TLS
717
    if (vs->tls_session) {
718
        ret = gnutls_read(vs->tls_session, buffer_end(&vs->input), 4096);
719
        if (ret < 0) {
720
            if (ret == GNUTLS_E_AGAIN)
721
                errno = EAGAIN;
722
            else
723
                errno = EIO;
724
            ret = -1;
725
        }
726
    } else
727
#endif /* CONFIG_VNC_TLS */
728
        ret = recv(vs->csock, buffer_end(&vs->input), 4096, 0);
729
    ret = vnc_client_io_error(vs, ret, socket_error());
730
    if (!ret)
731
        return;
732

    
733
    vs->input.offset += ret;
734

    
735
    while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
736
        size_t len = vs->read_handler_expect;
737
        int ret;
738

    
739
        ret = vs->read_handler(vs, vs->input.buffer, len);
740
        if (vs->csock == -1)
741
            return;
742

    
743
        if (!ret) {
744
            memmove(vs->input.buffer, vs->input.buffer + len, (vs->input.offset - len));
745
            vs->input.offset -= len;
746
        } else {
747
            vs->read_handler_expect = ret;
748
        }
749
    }
750
}
751

    
752
static void vnc_write(VncState *vs, const void *data, size_t len)
753
{
754
    buffer_reserve(&vs->output, len);
755

    
756
    if (buffer_empty(&vs->output)) {
757
        qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
758
    }
759

    
760
    buffer_append(&vs->output, data, len);
761
}
762

    
763
static void vnc_write_s32(VncState *vs, int32_t value)
764
{
765
    vnc_write_u32(vs, *(uint32_t *)&value);
766
}
767

    
768
static void vnc_write_u32(VncState *vs, uint32_t value)
769
{
770
    uint8_t buf[4];
771

    
772
    buf[0] = (value >> 24) & 0xFF;
773
    buf[1] = (value >> 16) & 0xFF;
774
    buf[2] = (value >>  8) & 0xFF;
775
    buf[3] = value & 0xFF;
776

    
777
    vnc_write(vs, buf, 4);
778
}
779

    
780
static void vnc_write_u16(VncState *vs, uint16_t value)
781
{
782
    uint8_t buf[2];
783

    
784
    buf[0] = (value >> 8) & 0xFF;
785
    buf[1] = value & 0xFF;
786

    
787
    vnc_write(vs, buf, 2);
788
}
789

    
790
static void vnc_write_u8(VncState *vs, uint8_t value)
791
{
792
    vnc_write(vs, (char *)&value, 1);
793
}
794

    
795
static void vnc_flush(VncState *vs)
796
{
797
    if (vs->output.offset)
798
        vnc_client_write(vs);
799
}
800

    
801
static uint8_t read_u8(uint8_t *data, size_t offset)
802
{
803
    return data[offset];
804
}
805

    
806
static uint16_t read_u16(uint8_t *data, size_t offset)
807
{
808
    return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
809
}
810

    
811
static int32_t read_s32(uint8_t *data, size_t offset)
812
{
813
    return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
814
                     (data[offset + 2] << 8) | data[offset + 3]);
815
}
816

    
817
static uint32_t read_u32(uint8_t *data, size_t offset)
818
{
819
    return ((data[offset] << 24) | (data[offset + 1] << 16) |
820
            (data[offset + 2] << 8) | data[offset + 3]);
821
}
822

    
823
#if CONFIG_VNC_TLS
824
static ssize_t vnc_tls_push(gnutls_transport_ptr_t transport,
825
                            const void *data,
826
                            size_t len) {
827
    struct VncState *vs = (struct VncState *)transport;
828
    int ret;
829

    
830
 retry:
831
    ret = send(vs->csock, data, len, 0);
832
    if (ret < 0) {
833
        if (errno == EINTR)
834
            goto retry;
835
        return -1;
836
    }
837
    return ret;
838
}
839

    
840

    
841
static ssize_t vnc_tls_pull(gnutls_transport_ptr_t transport,
842
                            void *data,
843
                            size_t len) {
844
    struct VncState *vs = (struct VncState *)transport;
845
    int ret;
846

    
847
 retry:
848
    ret = recv(vs->csock, data, len, 0);
849
    if (ret < 0) {
850
        if (errno == EINTR)
851
            goto retry;
852
        return -1;
853
    }
854
    return ret;
855
}
856
#endif /* CONFIG_VNC_TLS */
857

    
858
static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
859
{
860
}
861

    
862
static void check_pointer_type_change(VncState *vs, int absolute)
863
{
864
    if (vs->has_pointer_type_change && vs->absolute != absolute) {
865
        vnc_write_u8(vs, 0);
866
        vnc_write_u8(vs, 0);
867
        vnc_write_u16(vs, 1);
868
        vnc_framebuffer_update(vs, absolute, 0,
869
                               vs->ds->width, vs->ds->height, -257);
870
        vnc_flush(vs);
871
    }
872
    vs->absolute = absolute;
873
}
874

    
875
static void pointer_event(VncState *vs, int button_mask, int x, int y)
876
{
877
    int buttons = 0;
878
    int dz = 0;
879

    
880
    if (button_mask & 0x01)
881
        buttons |= MOUSE_EVENT_LBUTTON;
882
    if (button_mask & 0x02)
883
        buttons |= MOUSE_EVENT_MBUTTON;
884
    if (button_mask & 0x04)
885
        buttons |= MOUSE_EVENT_RBUTTON;
886
    if (button_mask & 0x08)
887
        dz = -1;
888
    if (button_mask & 0x10)
889
        dz = 1;
890

    
891
    if (vs->absolute) {
892
        kbd_mouse_event(x * 0x7FFF / (vs->ds->width - 1),
893
                        y * 0x7FFF / (vs->ds->height - 1),
894
                        dz, buttons);
895
    } else if (vs->has_pointer_type_change) {
896
        x -= 0x7FFF;
897
        y -= 0x7FFF;
898

    
899
        kbd_mouse_event(x, y, dz, buttons);
900
    } else {
901
        if (vs->last_x != -1)
902
            kbd_mouse_event(x - vs->last_x,
903
                            y - vs->last_y,
904
                            dz, buttons);
905
        vs->last_x = x;
906
        vs->last_y = y;
907
    }
908

    
909
    check_pointer_type_change(vs, kbd_mouse_is_absolute());
910
}
911

    
912
static void reset_keys(VncState *vs)
913
{
914
    int i;
915
    for(i = 0; i < 256; i++) {
916
        if (vs->modifiers_state[i]) {
917
            if (i & 0x80)
918
                kbd_put_keycode(0xe0);
919
            kbd_put_keycode(i | 0x80);
920
            vs->modifiers_state[i] = 0;
921
        }
922
    }
923
}
924

    
925
static void press_key(VncState *vs, int keysym)
926
{
927
    kbd_put_keycode(keysym2scancode(vs->kbd_layout, keysym) & 0x7f);
928
    kbd_put_keycode(keysym2scancode(vs->kbd_layout, keysym) | 0x80);
929
}
930

    
931
static void do_key_event(VncState *vs, int down, uint32_t sym)
932
{
933
    int keycode;
934

    
935
    keycode = keysym2scancode(vs->kbd_layout, sym & 0xFFFF);
936

    
937
    /* QEMU console switch */
938
    switch(keycode) {
939
    case 0x2a:                          /* Left Shift */
940
    case 0x36:                          /* Right Shift */
941
    case 0x1d:                          /* Left CTRL */
942
    case 0x9d:                          /* Right CTRL */
943
    case 0x38:                          /* Left ALT */
944
    case 0xb8:                          /* Right ALT */
945
        if (down)
946
            vs->modifiers_state[keycode] = 1;
947
        else
948
            vs->modifiers_state[keycode] = 0;
949
        break;
950
    case 0x02 ... 0x0a: /* '1' to '9' keys */
951
        if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
952
            /* Reset the modifiers sent to the current console */
953
            reset_keys(vs);
954
            console_select(keycode - 0x02);
955
            return;
956
        }
957
        break;
958
    case 0x3a:                        /* CapsLock */
959
    case 0x45:                        /* NumLock */
960
        if (!down)
961
            vs->modifiers_state[keycode] ^= 1;
962
        break;
963
    }
964

    
965
    if (keycode_is_keypad(vs->kbd_layout, keycode)) {
966
        /* If the numlock state needs to change then simulate an additional
967
           keypress before sending this one.  This will happen if the user
968
           toggles numlock away from the VNC window.
969
        */
970
        if (keysym_is_numlock(vs->kbd_layout, sym & 0xFFFF)) {
971
            if (!vs->modifiers_state[0x45]) {
972
                vs->modifiers_state[0x45] = 1;
973
                press_key(vs, 0xff7f);
974
            }
975
        } else {
976
            if (vs->modifiers_state[0x45]) {
977
                vs->modifiers_state[0x45] = 0;
978
                press_key(vs, 0xff7f);
979
            }
980
        }
981
    }
982

    
983
    if (is_graphic_console()) {
984
        if (keycode & 0x80)
985
            kbd_put_keycode(0xe0);
986
        if (down)
987
            kbd_put_keycode(keycode & 0x7f);
988
        else
989
            kbd_put_keycode(keycode | 0x80);
990
    } else {
991
        /* QEMU console emulation */
992
        if (down) {
993
            switch (keycode) {
994
            case 0x2a:                          /* Left Shift */
995
            case 0x36:                          /* Right Shift */
996
            case 0x1d:                          /* Left CTRL */
997
            case 0x9d:                          /* Right CTRL */
998
            case 0x38:                          /* Left ALT */
999
            case 0xb8:                          /* Right ALT */
1000
                break;
1001
            case 0xc8:
1002
                kbd_put_keysym(QEMU_KEY_UP);
1003
                break;
1004
            case 0xd0:
1005
                kbd_put_keysym(QEMU_KEY_DOWN);
1006
                break;
1007
            case 0xcb:
1008
                kbd_put_keysym(QEMU_KEY_LEFT);
1009
                break;
1010
            case 0xcd:
1011
                kbd_put_keysym(QEMU_KEY_RIGHT);
1012
                break;
1013
            case 0xd3:
1014
                kbd_put_keysym(QEMU_KEY_DELETE);
1015
                break;
1016
            case 0xc7:
1017
                kbd_put_keysym(QEMU_KEY_HOME);
1018
                break;
1019
            case 0xcf:
1020
                kbd_put_keysym(QEMU_KEY_END);
1021
                break;
1022
            case 0xc9:
1023
                kbd_put_keysym(QEMU_KEY_PAGEUP);
1024
                break;
1025
            case 0xd1:
1026
                kbd_put_keysym(QEMU_KEY_PAGEDOWN);
1027
                break;
1028
            default:
1029
                kbd_put_keysym(sym);
1030
                break;
1031
            }
1032
        }
1033
    }
1034
}
1035

    
1036
static void key_event(VncState *vs, int down, uint32_t sym)
1037
{
1038
    if (sym >= 'A' && sym <= 'Z' && is_graphic_console())
1039
        sym = sym - 'A' + 'a';
1040
    do_key_event(vs, down, sym);
1041
}
1042

    
1043
static void framebuffer_update_request(VncState *vs, int incremental,
1044
                                       int x_position, int y_position,
1045
                                       int w, int h)
1046
{
1047
    if (x_position > vs->ds->width)
1048
        x_position = vs->ds->width;
1049
    if (y_position > vs->ds->height)
1050
        y_position = vs->ds->height;
1051
    if (x_position + w >= vs->ds->width)
1052
        w = vs->ds->width  - x_position;
1053
    if (y_position + h >= vs->ds->height)
1054
        h = vs->ds->height - y_position;
1055

    
1056
    int i;
1057
    vs->need_update = 1;
1058
    if (!incremental) {
1059
        char *old_row = vs->old_data + y_position * vs->ds->linesize;
1060

    
1061
        for (i = 0; i < h; i++) {
1062
            vnc_set_bits(vs->dirty_row[y_position + i],
1063
                         (vs->ds->width / 16), VNC_DIRTY_WORDS);
1064
            memset(old_row, 42, vs->ds->width * vs->depth);
1065
            old_row += vs->ds->linesize;
1066
        }
1067
    }
1068
}
1069

    
1070
static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
1071
{
1072
    int i;
1073

    
1074
    vs->has_hextile = 0;
1075
    vs->has_resize = 0;
1076
    vs->has_pointer_type_change = 0;
1077
    vs->absolute = -1;
1078
    vs->ds->dpy_copy = NULL;
1079

    
1080
    for (i = n_encodings - 1; i >= 0; i--) {
1081
        switch (encodings[i]) {
1082
        case 0: /* Raw */
1083
            vs->has_hextile = 0;
1084
            break;
1085
        case 1: /* CopyRect */
1086
            vs->ds->dpy_copy = vnc_copy;
1087
            break;
1088
        case 5: /* Hextile */
1089
            vs->has_hextile = 1;
1090
            break;
1091
        case -223: /* DesktopResize */
1092
            vs->has_resize = 1;
1093
            break;
1094
        case -257:
1095
            vs->has_pointer_type_change = 1;
1096
            break;
1097
        default:
1098
            break;
1099
        }
1100
    }
1101

    
1102
    check_pointer_type_change(vs, kbd_mouse_is_absolute());
1103
}
1104

    
1105
static int compute_nbits(unsigned int val)
1106
{
1107
    int n;
1108
    n = 0;
1109
    while (val != 0) {
1110
        n++;
1111
        val >>= 1;
1112
    }
1113
    return n;
1114
}
1115

    
1116
static void set_pixel_format(VncState *vs,
1117
                             int bits_per_pixel, int depth,
1118
                             int big_endian_flag, int true_color_flag,
1119
                             int red_max, int green_max, int blue_max,
1120
                             int red_shift, int green_shift, int blue_shift)
1121
{
1122
    int host_big_endian_flag;
1123

    
1124
#ifdef WORDS_BIGENDIAN
1125
    host_big_endian_flag = 1;
1126
#else
1127
    host_big_endian_flag = 0;
1128
#endif
1129
    if (!true_color_flag) {
1130
    fail:
1131
        vnc_client_error(vs);
1132
        return;
1133
    }
1134
    if (bits_per_pixel == 32 &&
1135
        host_big_endian_flag == big_endian_flag &&
1136
        red_max == 0xff && green_max == 0xff && blue_max == 0xff &&
1137
        red_shift == 16 && green_shift == 8 && blue_shift == 0) {
1138
        vs->depth = 4;
1139
        vs->write_pixels = vnc_write_pixels_copy;
1140
        vs->send_hextile_tile = send_hextile_tile_32;
1141
    } else
1142
    if (bits_per_pixel == 16 &&
1143
        host_big_endian_flag == big_endian_flag &&
1144
        red_max == 31 && green_max == 63 && blue_max == 31 &&
1145
        red_shift == 11 && green_shift == 5 && blue_shift == 0) {
1146
        vs->depth = 2;
1147
        vs->write_pixels = vnc_write_pixels_copy;
1148
        vs->send_hextile_tile = send_hextile_tile_16;
1149
    } else
1150
    if (bits_per_pixel == 8 &&
1151
        red_max == 7 && green_max == 7 && blue_max == 3 &&
1152
        red_shift == 5 && green_shift == 2 && blue_shift == 0) {
1153
        vs->depth = 1;
1154
        vs->write_pixels = vnc_write_pixels_copy;
1155
        vs->send_hextile_tile = send_hextile_tile_8;
1156
    } else
1157
    {
1158
        /* generic and slower case */
1159
        if (bits_per_pixel != 8 &&
1160
            bits_per_pixel != 16 &&
1161
            bits_per_pixel != 32)
1162
            goto fail;
1163
        vs->depth = 4;
1164
        vs->red_shift = red_shift;
1165
        vs->red_max = red_max;
1166
        vs->red_shift1 = 24 - compute_nbits(red_max);
1167
        vs->green_shift = green_shift;
1168
        vs->green_max = green_max;
1169
        vs->green_shift1 = 16 - compute_nbits(green_max);
1170
        vs->blue_shift = blue_shift;
1171
        vs->blue_max = blue_max;
1172
        vs->blue_shift1 = 8 - compute_nbits(blue_max);
1173
        vs->pix_bpp = bits_per_pixel / 8;
1174
        vs->pix_big_endian = big_endian_flag;
1175
        vs->write_pixels = vnc_write_pixels_generic;
1176
        vs->send_hextile_tile = send_hextile_tile_generic;
1177
    }
1178

    
1179
    vnc_dpy_resize(vs->ds, vs->ds->width, vs->ds->height);
1180
    memset(vs->dirty_row, 0xFF, sizeof(vs->dirty_row));
1181
    memset(vs->old_data, 42, vs->ds->linesize * vs->ds->height);
1182

    
1183
    vga_hw_invalidate();
1184
    vga_hw_update();
1185
}
1186

    
1187
static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
1188
{
1189
    int i;
1190
    uint16_t limit;
1191

    
1192
    switch (data[0]) {
1193
    case 0:
1194
        if (len == 1)
1195
            return 20;
1196

    
1197
        set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
1198
                         read_u8(data, 6), read_u8(data, 7),
1199
                         read_u16(data, 8), read_u16(data, 10),
1200
                         read_u16(data, 12), read_u8(data, 14),
1201
                         read_u8(data, 15), read_u8(data, 16));
1202
        break;
1203
    case 2:
1204
        if (len == 1)
1205
            return 4;
1206

    
1207
        if (len == 4)
1208
            return 4 + (read_u16(data, 2) * 4);
1209

    
1210
        limit = read_u16(data, 2);
1211
        for (i = 0; i < limit; i++) {
1212
            int32_t val = read_s32(data, 4 + (i * 4));
1213
            memcpy(data + 4 + (i * 4), &val, sizeof(val));
1214
        }
1215

    
1216
        set_encodings(vs, (int32_t *)(data + 4), limit);
1217
        break;
1218
    case 3:
1219
        if (len == 1)
1220
            return 10;
1221

    
1222
        framebuffer_update_request(vs,
1223
                                   read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
1224
                                   read_u16(data, 6), read_u16(data, 8));
1225
        break;
1226
    case 4:
1227
        if (len == 1)
1228
            return 8;
1229

    
1230
        key_event(vs, read_u8(data, 1), read_u32(data, 4));
1231
        break;
1232
    case 5:
1233
        if (len == 1)
1234
            return 6;
1235

    
1236
        pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
1237
        break;
1238
    case 6:
1239
        if (len == 1)
1240
            return 8;
1241

    
1242
        if (len == 8) {
1243
            uint32_t dlen = read_u32(data, 4);
1244
            if (dlen > 0)
1245
                return 8 + dlen;
1246
        }
1247

    
1248
        client_cut_text(vs, read_u32(data, 4), data + 8);
1249
        break;
1250
    default:
1251
        printf("Msg: %d\n", data[0]);
1252
        vnc_client_error(vs);
1253
        break;
1254
    }
1255

    
1256
    vnc_read_when(vs, protocol_client_msg, 1);
1257
    return 0;
1258
}
1259

    
1260
static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
1261
{
1262
    char pad[3] = { 0, 0, 0 };
1263
    char buf[1024];
1264
    int size;
1265

    
1266
    vs->width = vs->ds->width;
1267
    vs->height = vs->ds->height;
1268
    vnc_write_u16(vs, vs->ds->width);
1269
    vnc_write_u16(vs, vs->ds->height);
1270

    
1271
    vnc_write_u8(vs, vs->depth * 8); /* bits-per-pixel */
1272
    vnc_write_u8(vs, vs->depth * 8); /* depth */
1273
#ifdef WORDS_BIGENDIAN
1274
    vnc_write_u8(vs, 1);             /* big-endian-flag */
1275
#else
1276
    vnc_write_u8(vs, 0);             /* big-endian-flag */
1277
#endif
1278
    vnc_write_u8(vs, 1);             /* true-color-flag */
1279
    if (vs->depth == 4) {
1280
        vnc_write_u16(vs, 0xFF);     /* red-max */
1281
        vnc_write_u16(vs, 0xFF);     /* green-max */
1282
        vnc_write_u16(vs, 0xFF);     /* blue-max */
1283
        vnc_write_u8(vs, 16);        /* red-shift */
1284
        vnc_write_u8(vs, 8);         /* green-shift */
1285
        vnc_write_u8(vs, 0);         /* blue-shift */
1286
        vs->send_hextile_tile = send_hextile_tile_32;
1287
    } else if (vs->depth == 2) {
1288
        vnc_write_u16(vs, 31);       /* red-max */
1289
        vnc_write_u16(vs, 63);       /* green-max */
1290
        vnc_write_u16(vs, 31);       /* blue-max */
1291
        vnc_write_u8(vs, 11);        /* red-shift */
1292
        vnc_write_u8(vs, 5);         /* green-shift */
1293
        vnc_write_u8(vs, 0);         /* blue-shift */
1294
        vs->send_hextile_tile = send_hextile_tile_16;
1295
    } else if (vs->depth == 1) {
1296
        /* XXX: change QEMU pixel 8 bit pixel format to match the VNC one ? */
1297
        vnc_write_u16(vs, 7);        /* red-max */
1298
        vnc_write_u16(vs, 7);        /* green-max */
1299
        vnc_write_u16(vs, 3);        /* blue-max */
1300
        vnc_write_u8(vs, 5);         /* red-shift */
1301
        vnc_write_u8(vs, 2);         /* green-shift */
1302
        vnc_write_u8(vs, 0);         /* blue-shift */
1303
        vs->send_hextile_tile = send_hextile_tile_8;
1304
    }
1305
    vs->write_pixels = vnc_write_pixels_copy;
1306

    
1307
    vnc_write(vs, pad, 3);           /* padding */
1308

    
1309
    if (qemu_name)
1310
        size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
1311
    else
1312
        size = snprintf(buf, sizeof(buf), "QEMU");
1313

    
1314
    vnc_write_u32(vs, size);
1315
    vnc_write(vs, buf, size);
1316
    vnc_flush(vs);
1317

    
1318
    vnc_read_when(vs, protocol_client_msg, 1);
1319

    
1320
    return 0;
1321
}
1322

    
1323
static void make_challenge(VncState *vs)
1324
{
1325
    int i;
1326

    
1327
    srand(time(NULL)+getpid()+getpid()*987654+rand());
1328

    
1329
    for (i = 0 ; i < sizeof(vs->challenge) ; i++)
1330
        vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
1331
}
1332

    
1333
static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
1334
{
1335
    unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
1336
    int i, j, pwlen;
1337
    unsigned char key[8];
1338

    
1339
    if (!vs->password || !vs->password[0]) {
1340
        VNC_DEBUG("No password configured on server");
1341
        vnc_write_u32(vs, 1); /* Reject auth */
1342
        if (vs->minor >= 8) {
1343
            static const char err[] = "Authentication failed";
1344
            vnc_write_u32(vs, sizeof(err));
1345
            vnc_write(vs, err, sizeof(err));
1346
        }
1347
        vnc_flush(vs);
1348
        vnc_client_error(vs);
1349
        return 0;
1350
    }
1351

    
1352
    memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
1353

    
1354
    /* Calculate the expected challenge response */
1355
    pwlen = strlen(vs->password);
1356
    for (i=0; i<sizeof(key); i++)
1357
        key[i] = i<pwlen ? vs->password[i] : 0;
1358
    deskey(key, EN0);
1359
    for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
1360
        des(response+j, response+j);
1361

    
1362
    /* Compare expected vs actual challenge response */
1363
    if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
1364
        VNC_DEBUG("Client challenge reponse did not match\n");
1365
        vnc_write_u32(vs, 1); /* Reject auth */
1366
        if (vs->minor >= 8) {
1367
            static const char err[] = "Authentication failed";
1368
            vnc_write_u32(vs, sizeof(err));
1369
            vnc_write(vs, err, sizeof(err));
1370
        }
1371
        vnc_flush(vs);
1372
        vnc_client_error(vs);
1373
    } else {
1374
        VNC_DEBUG("Accepting VNC challenge response\n");
1375
        vnc_write_u32(vs, 0); /* Accept auth */
1376
        vnc_flush(vs);
1377

    
1378
        vnc_read_when(vs, protocol_client_init, 1);
1379
    }
1380
    return 0;
1381
}
1382

    
1383
static int start_auth_vnc(VncState *vs)
1384
{
1385
    make_challenge(vs);
1386
    /* Send client a 'random' challenge */
1387
    vnc_write(vs, vs->challenge, sizeof(vs->challenge));
1388
    vnc_flush(vs);
1389

    
1390
    vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
1391
    return 0;
1392
}
1393

    
1394

    
1395
#if CONFIG_VNC_TLS
1396
#define DH_BITS 1024
1397
static gnutls_dh_params_t dh_params;
1398

    
1399
static int vnc_tls_initialize(void)
1400
{
1401
    static int tlsinitialized = 0;
1402

    
1403
    if (tlsinitialized)
1404
        return 1;
1405

    
1406
    if (gnutls_global_init () < 0)
1407
        return 0;
1408

    
1409
    /* XXX ought to re-generate diffie-hellmen params periodically */
1410
    if (gnutls_dh_params_init (&dh_params) < 0)
1411
        return 0;
1412
    if (gnutls_dh_params_generate2 (dh_params, DH_BITS) < 0)
1413
        return 0;
1414

    
1415
#if _VNC_DEBUG == 2
1416
    gnutls_global_set_log_level(10);
1417
    gnutls_global_set_log_function(vnc_debug_gnutls_log);
1418
#endif
1419

    
1420
    tlsinitialized = 1;
1421

    
1422
    return 1;
1423
}
1424

    
1425
static gnutls_anon_server_credentials vnc_tls_initialize_anon_cred(void)
1426
{
1427
    gnutls_anon_server_credentials anon_cred;
1428
    int ret;
1429

    
1430
    if ((ret = gnutls_anon_allocate_server_credentials(&anon_cred)) < 0) {
1431
        VNC_DEBUG("Cannot allocate credentials %s\n", gnutls_strerror(ret));
1432
        return NULL;
1433
    }
1434

    
1435
    gnutls_anon_set_server_dh_params(anon_cred, dh_params);
1436

    
1437
    return anon_cred;
1438
}
1439

    
1440

    
1441
static gnutls_certificate_credentials_t vnc_tls_initialize_x509_cred(VncState *vs)
1442
{
1443
    gnutls_certificate_credentials_t x509_cred;
1444
    int ret;
1445

    
1446
    if (!vs->x509cacert) {
1447
        VNC_DEBUG("No CA x509 certificate specified\n");
1448
        return NULL;
1449
    }
1450
    if (!vs->x509cert) {
1451
        VNC_DEBUG("No server x509 certificate specified\n");
1452
        return NULL;
1453
    }
1454
    if (!vs->x509key) {
1455
        VNC_DEBUG("No server private key specified\n");
1456
        return NULL;
1457
    }
1458

    
1459
    if ((ret = gnutls_certificate_allocate_credentials(&x509_cred)) < 0) {
1460
        VNC_DEBUG("Cannot allocate credentials %s\n", gnutls_strerror(ret));
1461
        return NULL;
1462
    }
1463
    if ((ret = gnutls_certificate_set_x509_trust_file(x509_cred,
1464
                                                      vs->x509cacert,
1465
                                                      GNUTLS_X509_FMT_PEM)) < 0) {
1466
        VNC_DEBUG("Cannot load CA certificate %s\n", gnutls_strerror(ret));
1467
        gnutls_certificate_free_credentials(x509_cred);
1468
        return NULL;
1469
    }
1470

    
1471
    if ((ret = gnutls_certificate_set_x509_key_file (x509_cred,
1472
                                                     vs->x509cert,
1473
                                                     vs->x509key,
1474
                                                     GNUTLS_X509_FMT_PEM)) < 0) {
1475
        VNC_DEBUG("Cannot load certificate & key %s\n", gnutls_strerror(ret));
1476
        gnutls_certificate_free_credentials(x509_cred);
1477
        return NULL;
1478
    }
1479

    
1480
    if (vs->x509cacrl) {
1481
        if ((ret = gnutls_certificate_set_x509_crl_file(x509_cred,
1482
                                                        vs->x509cacrl,
1483
                                                        GNUTLS_X509_FMT_PEM)) < 0) {
1484
            VNC_DEBUG("Cannot load CRL %s\n", gnutls_strerror(ret));
1485
            gnutls_certificate_free_credentials(x509_cred);
1486
            return NULL;
1487
        }
1488
    }
1489

    
1490
    gnutls_certificate_set_dh_params (x509_cred, dh_params);
1491

    
1492
    return x509_cred;
1493
}
1494

    
1495
static int vnc_validate_certificate(struct VncState *vs)
1496
{
1497
    int ret;
1498
    unsigned int status;
1499
    const gnutls_datum_t *certs;
1500
    unsigned int nCerts, i;
1501
    time_t now;
1502

    
1503
    VNC_DEBUG("Validating client certificate\n");
1504
    if ((ret = gnutls_certificate_verify_peers2 (vs->tls_session, &status)) < 0) {
1505
        VNC_DEBUG("Verify failed %s\n", gnutls_strerror(ret));
1506
        return -1;
1507
    }
1508

    
1509
    if ((now = time(NULL)) == ((time_t)-1)) {
1510
        return -1;
1511
    }
1512

    
1513
    if (status != 0) {
1514
        if (status & GNUTLS_CERT_INVALID)
1515
            VNC_DEBUG("The certificate is not trusted.\n");
1516

    
1517
        if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
1518
            VNC_DEBUG("The certificate hasn't got a known issuer.\n");
1519

    
1520
        if (status & GNUTLS_CERT_REVOKED)
1521
            VNC_DEBUG("The certificate has been revoked.\n");
1522

    
1523
        if (status & GNUTLS_CERT_INSECURE_ALGORITHM)
1524
            VNC_DEBUG("The certificate uses an insecure algorithm\n");
1525

    
1526
        return -1;
1527
    } else {
1528
        VNC_DEBUG("Certificate is valid!\n");
1529
    }
1530

    
1531
    /* Only support x509 for now */
1532
    if (gnutls_certificate_type_get(vs->tls_session) != GNUTLS_CRT_X509)
1533
        return -1;
1534

    
1535
    if (!(certs = gnutls_certificate_get_peers(vs->tls_session, &nCerts)))
1536
        return -1;
1537

    
1538
    for (i = 0 ; i < nCerts ; i++) {
1539
        gnutls_x509_crt_t cert;
1540
        VNC_DEBUG ("Checking certificate chain %d\n", i);
1541
        if (gnutls_x509_crt_init (&cert) < 0)
1542
            return -1;
1543

    
1544
        if (gnutls_x509_crt_import(cert, &certs[i], GNUTLS_X509_FMT_DER) < 0) {
1545
            gnutls_x509_crt_deinit (cert);
1546
            return -1;
1547
        }
1548

    
1549
        if (gnutls_x509_crt_get_expiration_time (cert) < now) {
1550
            VNC_DEBUG("The certificate has expired\n");
1551
            gnutls_x509_crt_deinit (cert);
1552
            return -1;
1553
        }
1554

    
1555
        if (gnutls_x509_crt_get_activation_time (cert) > now) {
1556
            VNC_DEBUG("The certificate is not yet activated\n");
1557
            gnutls_x509_crt_deinit (cert);
1558
            return -1;
1559
        }
1560

    
1561
        if (gnutls_x509_crt_get_activation_time (cert) > now) {
1562
            VNC_DEBUG("The certificate is not yet activated\n");
1563
            gnutls_x509_crt_deinit (cert);
1564
            return -1;
1565
        }
1566

    
1567
        gnutls_x509_crt_deinit (cert);
1568
    }
1569

    
1570
    return 0;
1571
}
1572

    
1573

    
1574
static int start_auth_vencrypt_subauth(VncState *vs)
1575
{
1576
    switch (vs->subauth) {
1577
    case VNC_AUTH_VENCRYPT_TLSNONE:
1578
    case VNC_AUTH_VENCRYPT_X509NONE:
1579
       VNC_DEBUG("Accept TLS auth none\n");
1580
       vnc_write_u32(vs, 0); /* Accept auth completion */
1581
       vnc_read_when(vs, protocol_client_init, 1);
1582
       break;
1583

    
1584
    case VNC_AUTH_VENCRYPT_TLSVNC:
1585
    case VNC_AUTH_VENCRYPT_X509VNC:
1586
       VNC_DEBUG("Start TLS auth VNC\n");
1587
       return start_auth_vnc(vs);
1588

    
1589
    default: /* Should not be possible, but just in case */
1590
       VNC_DEBUG("Reject auth %d\n", vs->auth);
1591
       vnc_write_u8(vs, 1);
1592
       if (vs->minor >= 8) {
1593
           static const char err[] = "Unsupported authentication type";
1594
           vnc_write_u32(vs, sizeof(err));
1595
           vnc_write(vs, err, sizeof(err));
1596
       }
1597
       vnc_client_error(vs);
1598
    }
1599

    
1600
    return 0;
1601
}
1602

    
1603
static void vnc_handshake_io(void *opaque);
1604

    
1605
static int vnc_continue_handshake(struct VncState *vs) {
1606
    int ret;
1607

    
1608
    if ((ret = gnutls_handshake(vs->tls_session)) < 0) {
1609
       if (!gnutls_error_is_fatal(ret)) {
1610
           VNC_DEBUG("Handshake interrupted (blocking)\n");
1611
           if (!gnutls_record_get_direction(vs->tls_session))
1612
               qemu_set_fd_handler(vs->csock, vnc_handshake_io, NULL, vs);
1613
           else
1614
               qemu_set_fd_handler(vs->csock, NULL, vnc_handshake_io, vs);
1615
           return 0;
1616
       }
1617
       VNC_DEBUG("Handshake failed %s\n", gnutls_strerror(ret));
1618
       vnc_client_error(vs);
1619
       return -1;
1620
    }
1621

    
1622
    if (vs->x509verify) {
1623
        if (vnc_validate_certificate(vs) < 0) {
1624
            VNC_DEBUG("Client verification failed\n");
1625
            vnc_client_error(vs);
1626
            return -1;
1627
        } else {
1628
            VNC_DEBUG("Client verification passed\n");
1629
        }
1630
    }
1631

    
1632
    VNC_DEBUG("Handshake done, switching to TLS data mode\n");
1633
    vs->wiremode = VNC_WIREMODE_TLS;
1634
    qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
1635

    
1636
    return start_auth_vencrypt_subauth(vs);
1637
}
1638

    
1639
static void vnc_handshake_io(void *opaque) {
1640
    struct VncState *vs = (struct VncState *)opaque;
1641

    
1642
    VNC_DEBUG("Handshake IO continue\n");
1643
    vnc_continue_handshake(vs);
1644
}
1645

    
1646
#define NEED_X509_AUTH(vs)                              \
1647
    ((vs)->subauth == VNC_AUTH_VENCRYPT_X509NONE ||   \
1648
     (vs)->subauth == VNC_AUTH_VENCRYPT_X509VNC ||    \
1649
     (vs)->subauth == VNC_AUTH_VENCRYPT_X509PLAIN)
1650

    
1651

    
1652
static int vnc_start_tls(struct VncState *vs) {
1653
    static const int cert_type_priority[] = { GNUTLS_CRT_X509, 0 };
1654
    static const int protocol_priority[]= { GNUTLS_TLS1_1, GNUTLS_TLS1_0, GNUTLS_SSL3, 0 };
1655
    static const int kx_anon[] = {GNUTLS_KX_ANON_DH, 0};
1656
    static const int kx_x509[] = {GNUTLS_KX_DHE_DSS, GNUTLS_KX_RSA, GNUTLS_KX_DHE_RSA, GNUTLS_KX_SRP, 0};
1657

    
1658
    VNC_DEBUG("Do TLS setup\n");
1659
    if (vnc_tls_initialize() < 0) {
1660
        VNC_DEBUG("Failed to init TLS\n");
1661
        vnc_client_error(vs);
1662
        return -1;
1663
    }
1664
    if (vs->tls_session == NULL) {
1665
        if (gnutls_init(&vs->tls_session, GNUTLS_SERVER) < 0) {
1666
            vnc_client_error(vs);
1667
            return -1;
1668
        }
1669

    
1670
        if (gnutls_set_default_priority(vs->tls_session) < 0) {
1671
            gnutls_deinit(vs->tls_session);
1672
            vs->tls_session = NULL;
1673
            vnc_client_error(vs);
1674
            return -1;
1675
        }
1676

    
1677
        if (gnutls_kx_set_priority(vs->tls_session, NEED_X509_AUTH(vs) ? kx_x509 : kx_anon) < 0) {
1678
            gnutls_deinit(vs->tls_session);
1679
            vs->tls_session = NULL;
1680
            vnc_client_error(vs);
1681
            return -1;
1682
        }
1683

    
1684
        if (gnutls_certificate_type_set_priority(vs->tls_session, cert_type_priority) < 0) {
1685
            gnutls_deinit(vs->tls_session);
1686
            vs->tls_session = NULL;
1687
            vnc_client_error(vs);
1688
            return -1;
1689
        }
1690

    
1691
        if (gnutls_protocol_set_priority(vs->tls_session, protocol_priority) < 0) {
1692
            gnutls_deinit(vs->tls_session);
1693
            vs->tls_session = NULL;
1694
            vnc_client_error(vs);
1695
            return -1;
1696
        }
1697

    
1698
        if (NEED_X509_AUTH(vs)) {
1699
            gnutls_certificate_server_credentials x509_cred = vnc_tls_initialize_x509_cred(vs);
1700
            if (!x509_cred) {
1701
                gnutls_deinit(vs->tls_session);
1702
                vs->tls_session = NULL;
1703
                vnc_client_error(vs);
1704
                return -1;
1705
            }
1706
            if (gnutls_credentials_set(vs->tls_session, GNUTLS_CRD_CERTIFICATE, x509_cred) < 0) {
1707
                gnutls_deinit(vs->tls_session);
1708
                vs->tls_session = NULL;
1709
                gnutls_certificate_free_credentials(x509_cred);
1710
                vnc_client_error(vs);
1711
                return -1;
1712
            }
1713
            if (vs->x509verify) {
1714
                VNC_DEBUG("Requesting a client certificate\n");
1715
                gnutls_certificate_server_set_request (vs->tls_session, GNUTLS_CERT_REQUEST);
1716
            }
1717

    
1718
        } else {
1719
            gnutls_anon_server_credentials anon_cred = vnc_tls_initialize_anon_cred();
1720
            if (!anon_cred) {
1721
                gnutls_deinit(vs->tls_session);
1722
                vs->tls_session = NULL;
1723
                vnc_client_error(vs);
1724
                return -1;
1725
            }
1726
            if (gnutls_credentials_set(vs->tls_session, GNUTLS_CRD_ANON, anon_cred) < 0) {
1727
                gnutls_deinit(vs->tls_session);
1728
                vs->tls_session = NULL;
1729
                gnutls_anon_free_server_credentials(anon_cred);
1730
                vnc_client_error(vs);
1731
                return -1;
1732
            }
1733
        }
1734

    
1735
        gnutls_transport_set_ptr(vs->tls_session, (gnutls_transport_ptr_t)vs);
1736
        gnutls_transport_set_push_function(vs->tls_session, vnc_tls_push);
1737
        gnutls_transport_set_pull_function(vs->tls_session, vnc_tls_pull);
1738
    }
1739

    
1740
    VNC_DEBUG("Start TLS handshake process\n");
1741
    return vnc_continue_handshake(vs);
1742
}
1743

    
1744
static int protocol_client_vencrypt_auth(VncState *vs, uint8_t *data, size_t len)
1745
{
1746
    int auth = read_u32(data, 0);
1747

    
1748
    if (auth != vs->subauth) {
1749
        VNC_DEBUG("Rejecting auth %d\n", auth);
1750
        vnc_write_u8(vs, 0); /* Reject auth */
1751
        vnc_flush(vs);
1752
        vnc_client_error(vs);
1753
    } else {
1754
        VNC_DEBUG("Accepting auth %d, starting handshake\n", auth);
1755
        vnc_write_u8(vs, 1); /* Accept auth */
1756
        vnc_flush(vs);
1757

    
1758
        if (vnc_start_tls(vs) < 0) {
1759
            VNC_DEBUG("Failed to complete TLS\n");
1760
            return 0;
1761
        }
1762

    
1763
        if (vs->wiremode == VNC_WIREMODE_TLS) {
1764
            VNC_DEBUG("Starting VeNCrypt subauth\n");
1765
            return start_auth_vencrypt_subauth(vs);
1766
        } else {
1767
            VNC_DEBUG("TLS handshake blocked\n");
1768
            return 0;
1769
        }
1770
    }
1771
    return 0;
1772
}
1773

    
1774
static int protocol_client_vencrypt_init(VncState *vs, uint8_t *data, size_t len)
1775
{
1776
    if (data[0] != 0 ||
1777
        data[1] != 2) {
1778
        VNC_DEBUG("Unsupported VeNCrypt protocol %d.%d\n", (int)data[0], (int)data[1]);
1779
        vnc_write_u8(vs, 1); /* Reject version */
1780
        vnc_flush(vs);
1781
        vnc_client_error(vs);
1782
    } else {
1783
        VNC_DEBUG("Sending allowed auth %d\n", vs->subauth);
1784
        vnc_write_u8(vs, 0); /* Accept version */
1785
        vnc_write_u8(vs, 1); /* Number of sub-auths */
1786
        vnc_write_u32(vs, vs->subauth); /* The supported auth */
1787
        vnc_flush(vs);
1788
        vnc_read_when(vs, protocol_client_vencrypt_auth, 4);
1789
    }
1790
    return 0;
1791
}
1792

    
1793
static int start_auth_vencrypt(VncState *vs)
1794
{
1795
    /* Send VeNCrypt version 0.2 */
1796
    vnc_write_u8(vs, 0);
1797
    vnc_write_u8(vs, 2);
1798

    
1799
    vnc_read_when(vs, protocol_client_vencrypt_init, 2);
1800
    return 0;
1801
}
1802
#endif /* CONFIG_VNC_TLS */
1803

    
1804
static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
1805
{
1806
    /* We only advertise 1 auth scheme at a time, so client
1807
     * must pick the one we sent. Verify this */
1808
    if (data[0] != vs->auth) { /* Reject auth */
1809
       VNC_DEBUG("Reject auth %d\n", (int)data[0]);
1810
       vnc_write_u32(vs, 1);
1811
       if (vs->minor >= 8) {
1812
           static const char err[] = "Authentication failed";
1813
           vnc_write_u32(vs, sizeof(err));
1814
           vnc_write(vs, err, sizeof(err));
1815
       }
1816
       vnc_client_error(vs);
1817
    } else { /* Accept requested auth */
1818
       VNC_DEBUG("Client requested auth %d\n", (int)data[0]);
1819
       switch (vs->auth) {
1820
       case VNC_AUTH_NONE:
1821
           VNC_DEBUG("Accept auth none\n");
1822
           if (vs->minor >= 8) {
1823
               vnc_write_u32(vs, 0); /* Accept auth completion */
1824
               vnc_flush(vs);
1825
           }
1826
           vnc_read_when(vs, protocol_client_init, 1);
1827
           break;
1828

    
1829
       case VNC_AUTH_VNC:
1830
           VNC_DEBUG("Start VNC auth\n");
1831
           return start_auth_vnc(vs);
1832

    
1833
#if CONFIG_VNC_TLS
1834
       case VNC_AUTH_VENCRYPT:
1835
           VNC_DEBUG("Accept VeNCrypt auth\n");;
1836
           return start_auth_vencrypt(vs);
1837
#endif /* CONFIG_VNC_TLS */
1838

    
1839
       default: /* Should not be possible, but just in case */
1840
           VNC_DEBUG("Reject auth %d\n", vs->auth);
1841
           vnc_write_u8(vs, 1);
1842
           if (vs->minor >= 8) {
1843
               static const char err[] = "Authentication failed";
1844
               vnc_write_u32(vs, sizeof(err));
1845
               vnc_write(vs, err, sizeof(err));
1846
           }
1847
           vnc_client_error(vs);
1848
       }
1849
    }
1850
    return 0;
1851
}
1852

    
1853
static int protocol_version(VncState *vs, uint8_t *version, size_t len)
1854
{
1855
    char local[13];
1856

    
1857
    memcpy(local, version, 12);
1858
    local[12] = 0;
1859

    
1860
    if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
1861
        VNC_DEBUG("Malformed protocol version %s\n", local);
1862
        vnc_client_error(vs);
1863
        return 0;
1864
    }
1865
    VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
1866
    if (vs->major != 3 ||
1867
        (vs->minor != 3 &&
1868
         vs->minor != 4 &&
1869
         vs->minor != 5 &&
1870
         vs->minor != 7 &&
1871
         vs->minor != 8)) {
1872
        VNC_DEBUG("Unsupported client version\n");
1873
        vnc_write_u32(vs, VNC_AUTH_INVALID);
1874
        vnc_flush(vs);
1875
        vnc_client_error(vs);
1876
        return 0;
1877
    }
1878
    /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
1879
     * as equivalent to v3.3 by servers
1880
     */
1881
    if (vs->minor == 4 || vs->minor == 5)
1882
        vs->minor = 3;
1883

    
1884
    if (vs->minor == 3) {
1885
        if (vs->auth == VNC_AUTH_NONE) {
1886
            VNC_DEBUG("Tell client auth none\n");
1887
            vnc_write_u32(vs, vs->auth);
1888
            vnc_flush(vs);
1889
            vnc_read_when(vs, protocol_client_init, 1);
1890
       } else if (vs->auth == VNC_AUTH_VNC) {
1891
            VNC_DEBUG("Tell client VNC auth\n");
1892
            vnc_write_u32(vs, vs->auth);
1893
            vnc_flush(vs);
1894
            start_auth_vnc(vs);
1895
       } else {
1896
            VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->auth);
1897
            vnc_write_u32(vs, VNC_AUTH_INVALID);
1898
            vnc_flush(vs);
1899
            vnc_client_error(vs);
1900
       }
1901
    } else {
1902
        VNC_DEBUG("Telling client we support auth %d\n", vs->auth);
1903
        vnc_write_u8(vs, 1); /* num auth */
1904
        vnc_write_u8(vs, vs->auth);
1905
        vnc_read_when(vs, protocol_client_auth, 1);
1906
        vnc_flush(vs);
1907
    }
1908

    
1909
    return 0;
1910
}
1911

    
1912
static void vnc_connect(VncState *vs)
1913
{
1914
    VNC_DEBUG("New client on socket %d\n", vs->csock);
1915
    socket_set_nonblock(vs->csock);
1916
    qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
1917
    vnc_write(vs, "RFB 003.008\n", 12);
1918
    vnc_flush(vs);
1919
    vnc_read_when(vs, protocol_version, 12);
1920
    memset(vs->old_data, 0, vs->ds->linesize * vs->ds->height);
1921
    memset(vs->dirty_row, 0xFF, sizeof(vs->dirty_row));
1922
    vs->has_resize = 0;
1923
    vs->has_hextile = 0;
1924
    vs->ds->dpy_copy = NULL;
1925
    vnc_update_client(vs);
1926
}
1927

    
1928
static void vnc_listen_read(void *opaque)
1929
{
1930
    VncState *vs = opaque;
1931
    struct sockaddr_in addr;
1932
    socklen_t addrlen = sizeof(addr);
1933

    
1934
    /* Catch-up */
1935
    vga_hw_update();
1936

    
1937
    vs->csock = accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
1938
    if (vs->csock != -1) {
1939
        vnc_connect(vs);
1940
    }
1941
}
1942

    
1943
extern int parse_host_port(struct sockaddr_in *saddr, const char *str);
1944

    
1945
void vnc_display_init(DisplayState *ds)
1946
{
1947
    VncState *vs;
1948

    
1949
    vs = qemu_mallocz(sizeof(VncState));
1950
    if (!vs)
1951
        exit(1);
1952

    
1953
    ds->opaque = vs;
1954
    vnc_state = vs;
1955
    vs->display = NULL;
1956
    vs->password = NULL;
1957

    
1958
    vs->lsock = -1;
1959
    vs->csock = -1;
1960
    vs->depth = 4;
1961
    vs->last_x = -1;
1962
    vs->last_y = -1;
1963

    
1964
    vs->ds = ds;
1965

    
1966
    if (!keyboard_layout)
1967
        keyboard_layout = "en-us";
1968

    
1969
    vs->kbd_layout = init_keyboard_layout(keyboard_layout);
1970
    if (!vs->kbd_layout)
1971
        exit(1);
1972

    
1973
    vs->timer = qemu_new_timer(rt_clock, vnc_update_client, vs);
1974

    
1975
    vs->ds->data = NULL;
1976
    vs->ds->dpy_update = vnc_dpy_update;
1977
    vs->ds->dpy_resize = vnc_dpy_resize;
1978
    vs->ds->dpy_refresh = NULL;
1979

    
1980
    memset(vs->dirty_row, 0xFF, sizeof(vs->dirty_row));
1981

    
1982
    vnc_dpy_resize(vs->ds, 640, 400);
1983
}
1984

    
1985
#if CONFIG_VNC_TLS
1986
static int vnc_set_x509_credential(VncState *vs,
1987
                                   const char *certdir,
1988
                                   const char *filename,
1989
                                   char **cred,
1990
                                   int ignoreMissing)
1991
{
1992
    struct stat sb;
1993

    
1994
    if (*cred) {
1995
        qemu_free(*cred);
1996
        *cred = NULL;
1997
    }
1998

    
1999
    if (!(*cred = qemu_malloc(strlen(certdir) + strlen(filename) + 2)))
2000
        return -1;
2001

    
2002
    strcpy(*cred, certdir);
2003
    strcat(*cred, "/");
2004
    strcat(*cred, filename);
2005

    
2006
    VNC_DEBUG("Check %s\n", *cred);
2007
    if (stat(*cred, &sb) < 0) {
2008
        qemu_free(*cred);
2009
        *cred = NULL;
2010
        if (ignoreMissing && errno == ENOENT)
2011
            return 0;
2012
        return -1;
2013
    }
2014

    
2015
    return 0;
2016
}
2017

    
2018
static int vnc_set_x509_credential_dir(VncState *vs,
2019
                                       const char *certdir)
2020
{
2021
    if (vnc_set_x509_credential(vs, certdir, X509_CA_CERT_FILE, &vs->x509cacert, 0) < 0)
2022
        goto cleanup;
2023
    if (vnc_set_x509_credential(vs, certdir, X509_CA_CRL_FILE, &vs->x509cacrl, 1) < 0)
2024
        goto cleanup;
2025
    if (vnc_set_x509_credential(vs, certdir, X509_SERVER_CERT_FILE, &vs->x509cert, 0) < 0)
2026
        goto cleanup;
2027
    if (vnc_set_x509_credential(vs, certdir, X509_SERVER_KEY_FILE, &vs->x509key, 0) < 0)
2028
        goto cleanup;
2029

    
2030
    return 0;
2031

    
2032
 cleanup:
2033
    qemu_free(vs->x509cacert);
2034
    qemu_free(vs->x509cacrl);
2035
    qemu_free(vs->x509cert);
2036
    qemu_free(vs->x509key);
2037
    vs->x509cacert = vs->x509cacrl = vs->x509cert = vs->x509key = NULL;
2038
    return -1;
2039
}
2040
#endif /* CONFIG_VNC_TLS */
2041

    
2042
void vnc_display_close(DisplayState *ds)
2043
{
2044
    VncState *vs = ds ? (VncState *)ds->opaque : vnc_state;
2045

    
2046
    if (vs->display) {
2047
        qemu_free(vs->display);
2048
        vs->display = NULL;
2049
    }
2050
    if (vs->lsock != -1) {
2051
        qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);
2052
        close(vs->lsock);
2053
        vs->lsock = -1;
2054
    }
2055
    if (vs->csock != -1) {
2056
        qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
2057
        closesocket(vs->csock);
2058
        vs->csock = -1;
2059
        buffer_reset(&vs->input);
2060
        buffer_reset(&vs->output);
2061
        vs->need_update = 0;
2062
#if CONFIG_VNC_TLS
2063
        if (vs->tls_session) {
2064
            gnutls_deinit(vs->tls_session);
2065
            vs->tls_session = NULL;
2066
        }
2067
        vs->wiremode = VNC_WIREMODE_CLEAR;
2068
#endif /* CONFIG_VNC_TLS */
2069
    }
2070
    vs->auth = VNC_AUTH_INVALID;
2071
#if CONFIG_VNC_TLS
2072
    vs->subauth = VNC_AUTH_INVALID;
2073
    vs->x509verify = 0;
2074
#endif
2075
}
2076

    
2077
int vnc_display_password(DisplayState *ds, const char *password)
2078
{
2079
    VncState *vs = ds ? (VncState *)ds->opaque : vnc_state;
2080

    
2081
    if (vs->password) {
2082
        qemu_free(vs->password);
2083
        vs->password = NULL;
2084
    }
2085
    if (password && password[0]) {
2086
        if (!(vs->password = qemu_strdup(password)))
2087
            return -1;
2088
    }
2089

    
2090
    return 0;
2091
}
2092

    
2093
int vnc_display_open(DisplayState *ds, const char *display)
2094
{
2095
    struct sockaddr *addr;
2096
    struct sockaddr_in iaddr;
2097
#ifndef _WIN32
2098
    struct sockaddr_un uaddr;
2099
    const char *p;
2100
#endif
2101
    int reuse_addr, ret;
2102
    socklen_t addrlen;
2103
    VncState *vs = ds ? (VncState *)ds->opaque : vnc_state;
2104
    const char *options;
2105
    int password = 0;
2106
    int reverse = 0;
2107
#if CONFIG_VNC_TLS
2108
    int tls = 0, x509 = 0;
2109
#endif
2110

    
2111
    vnc_display_close(ds);
2112
    if (strcmp(display, "none") == 0)
2113
        return 0;
2114

    
2115
    if (!(vs->display = strdup(display)))
2116
        return -1;
2117

    
2118
    options = display;
2119
    while ((options = strchr(options, ','))) {
2120
        options++;
2121
        if (strncmp(options, "password", 8) == 0) {
2122
            password = 1; /* Require password auth */
2123
        } else if (strncmp(options, "reverse", 7) == 0) {
2124
            reverse = 1;
2125
#if CONFIG_VNC_TLS
2126
        } else if (strncmp(options, "tls", 3) == 0) {
2127
            tls = 1; /* Require TLS */
2128
        } else if (strncmp(options, "x509", 4) == 0) {
2129
            char *start, *end;
2130
            x509 = 1; /* Require x509 certificates */
2131
            if (strncmp(options, "x509verify", 10) == 0)
2132
                vs->x509verify = 1; /* ...and verify client certs */
2133

    
2134
            /* Now check for 'x509=/some/path' postfix
2135
             * and use that to setup x509 certificate/key paths */
2136
            start = strchr(options, '=');
2137
            end = strchr(options, ',');
2138
            if (start && (!end || (start < end))) {
2139
                int len = end ? end-(start+1) : strlen(start+1);
2140
                char *path = qemu_malloc(len+1);
2141
                strncpy(path, start+1, len);
2142
                path[len] = '\0';
2143
                VNC_DEBUG("Trying certificate path '%s'\n", path);
2144
                if (vnc_set_x509_credential_dir(vs, path) < 0) {
2145
                    fprintf(stderr, "Failed to find x509 certificates/keys in %s\n", path);
2146
                    qemu_free(path);
2147
                    qemu_free(vs->display);
2148
                    vs->display = NULL;
2149
                    return -1;
2150
                }
2151
                qemu_free(path);
2152
            } else {
2153
                fprintf(stderr, "No certificate path provided\n");
2154
                qemu_free(vs->display);
2155
                vs->display = NULL;
2156
                return -1;
2157
            }
2158
#endif
2159
        }
2160
    }
2161

    
2162
    if (password) {
2163
#if CONFIG_VNC_TLS
2164
        if (tls) {
2165
            vs->auth = VNC_AUTH_VENCRYPT;
2166
            if (x509) {
2167
                VNC_DEBUG("Initializing VNC server with x509 password auth\n");
2168
                vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;
2169
            } else {
2170
                VNC_DEBUG("Initializing VNC server with TLS password auth\n");
2171
                vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
2172
            }
2173
        } else {
2174
#endif
2175
            VNC_DEBUG("Initializing VNC server with password auth\n");
2176
            vs->auth = VNC_AUTH_VNC;
2177
#if CONFIG_VNC_TLS
2178
            vs->subauth = VNC_AUTH_INVALID;
2179
        }
2180
#endif
2181
    } else {
2182
#if CONFIG_VNC_TLS
2183
        if (tls) {
2184
            vs->auth = VNC_AUTH_VENCRYPT;
2185
            if (x509) {
2186
                VNC_DEBUG("Initializing VNC server with x509 no auth\n");
2187
                vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;
2188
            } else {
2189
                VNC_DEBUG("Initializing VNC server with TLS no auth\n");
2190
                vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
2191
            }
2192
        } else {
2193
#endif
2194
            VNC_DEBUG("Initializing VNC server with no auth\n");
2195
            vs->auth = VNC_AUTH_NONE;
2196
#if CONFIG_VNC_TLS
2197
            vs->subauth = VNC_AUTH_INVALID;
2198
        }
2199
#endif
2200
    }
2201
#ifndef _WIN32
2202
    if (strstart(display, "unix:", &p)) {
2203
        addr = (struct sockaddr *)&uaddr;
2204
        addrlen = sizeof(uaddr);
2205

    
2206
        vs->lsock = socket(PF_UNIX, SOCK_STREAM, 0);
2207
        if (vs->lsock == -1) {
2208
            fprintf(stderr, "Could not create socket\n");
2209
            free(vs->display);
2210
            vs->display = NULL;
2211
            return -1;
2212
        }
2213

    
2214
        uaddr.sun_family = AF_UNIX;
2215
        memset(uaddr.sun_path, 0, 108);
2216
        snprintf(uaddr.sun_path, 108, "%s", p);
2217

    
2218
        if (!reverse) {
2219
            unlink(uaddr.sun_path);
2220
        }
2221
    } else
2222
#endif
2223
    {
2224
        addr = (struct sockaddr *)&iaddr;
2225
        addrlen = sizeof(iaddr);
2226

    
2227
        if (parse_host_port(&iaddr, display) < 0) {
2228
            fprintf(stderr, "Could not parse VNC address\n");
2229
            free(vs->display);
2230
            vs->display = NULL;
2231
            return -1;
2232
        }
2233

    
2234
        iaddr.sin_port = htons(ntohs(iaddr.sin_port) + (reverse ? 0 : 5900));
2235

    
2236
        vs->lsock = socket(PF_INET, SOCK_STREAM, 0);
2237
        if (vs->lsock == -1) {
2238
            fprintf(stderr, "Could not create socket\n");
2239
            free(vs->display);
2240
            vs->display = NULL;
2241
            return -1;
2242
        }
2243

    
2244
        reuse_addr = 1;
2245
        ret = setsockopt(vs->lsock, SOL_SOCKET, SO_REUSEADDR,
2246
                         (const char *)&reuse_addr, sizeof(reuse_addr));
2247
        if (ret == -1) {
2248
            fprintf(stderr, "setsockopt() failed\n");
2249
            close(vs->lsock);
2250
            vs->lsock = -1;
2251
            free(vs->display);
2252
            vs->display = NULL;
2253
            return -1;
2254
        }
2255
    }
2256

    
2257
    if (reverse) {
2258
        if (connect(vs->lsock, addr, addrlen) == -1) {
2259
            fprintf(stderr, "Connection to VNC client failed\n");
2260
            close(vs->lsock);
2261
            vs->lsock = -1;
2262
            free(vs->display);
2263
            vs->display = NULL;
2264
            return -1;
2265
        } else {
2266
            vs->csock = vs->lsock;
2267
            vs->lsock = -1;
2268
            vnc_connect(vs);
2269
            return 0;
2270
        }
2271
    }
2272

    
2273
    if (bind(vs->lsock, addr, addrlen) == -1) {
2274
        fprintf(stderr, "bind() failed\n");
2275
        close(vs->lsock);
2276
        vs->lsock = -1;
2277
        free(vs->display);
2278
        vs->display = NULL;
2279
        return -1;
2280
    }
2281

    
2282
    if (listen(vs->lsock, 1) == -1) {
2283
        fprintf(stderr, "listen() failed\n");
2284
        close(vs->lsock);
2285
        vs->lsock = -1;
2286
        free(vs->display);
2287
        vs->display = NULL;
2288
        return -1;
2289
    }
2290

    
2291
    return qemu_set_fd_handler2(vs->lsock, vnc_listen_poll, vnc_listen_read, NULL, vs);
2292
}