Statistics
| Branch: | Revision:

root / vnc.c @ 5439779e

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
    x = MIN(x, vs->width);
269
    y = MIN(y, vs->height);
270
    w = MIN(x + w, vs->width) - x;
271
    h = MIN(h, vs->height);
272

    
273
    for (; y < h; y++)
274
        for (i = 0; i < w; i += 16)
275
            vnc_set_bit(vs->dirty_row[y], (x + i) / 16);
276
}
277

    
278
static void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
279
                                   int32_t encoding)
280
{
281
    vnc_write_u16(vs, x);
282
    vnc_write_u16(vs, y);
283
    vnc_write_u16(vs, w);
284
    vnc_write_u16(vs, h);
285

    
286
    vnc_write_s32(vs, encoding);
287
}
288

    
289
static void vnc_dpy_resize(DisplayState *ds, int w, int h)
290
{
291
    int size_changed;
292
    VncState *vs = ds->opaque;
293

    
294
    ds->data = realloc(ds->data, w * h * vs->depth);
295
    vs->old_data = realloc(vs->old_data, w * h * vs->depth);
296

    
297
    if (ds->data == NULL || vs->old_data == NULL) {
298
        fprintf(stderr, "vnc: memory allocation failed\n");
299
        exit(1);
300
    }
301

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

    
320
    memset(vs->dirty_row, 0xFF, sizeof(vs->dirty_row));
321
    memset(vs->old_data, 42, vs->ds->linesize * vs->ds->height);
322
}
323

    
324
/* fastest code */
325
static void vnc_write_pixels_copy(VncState *vs, void *pixels, int size)
326
{
327
    vnc_write(vs, pixels, size);
328
}
329

    
330
/* slowest but generic code. */
331
static void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
332
{
333
    unsigned int r, g, b;
334

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

    
371
static void vnc_write_pixels_generic(VncState *vs, void *pixels1, int size)
372
{
373
    uint32_t *pixels = pixels1;
374
    uint8_t buf[4];
375
    int n, i;
376

    
377
    n = size >> 2;
378
    for(i = 0; i < n; i++) {
379
        vnc_convert_pixel(vs, buf, pixels[i]);
380
        vnc_write(vs, buf, vs->pix_bpp);
381
    }
382
}
383

    
384
static void send_framebuffer_update_raw(VncState *vs, int x, int y, int w, int h)
385
{
386
    int i;
387
    uint8_t *row;
388

    
389
    vnc_framebuffer_update(vs, x, y, w, h, 0);
390

    
391
    row = vs->ds->data + y * vs->ds->linesize + x * vs->depth;
392
    for (i = 0; i < h; i++) {
393
        vs->write_pixels(vs, row, w * vs->depth);
394
        row += vs->ds->linesize;
395
    }
396
}
397

    
398
static void hextile_enc_cord(uint8_t *ptr, int x, int y, int w, int h)
399
{
400
    ptr[0] = ((x & 0x0F) << 4) | (y & 0x0F);
401
    ptr[1] = (((w - 1) & 0x0F) << 4) | ((h - 1) & 0x0F);
402
}
403

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

    
408
#define BPP 16
409
#include "vnchextile.h"
410
#undef BPP
411

    
412
#define BPP 32
413
#include "vnchextile.h"
414
#undef BPP
415

    
416
#define GENERIC
417
#define BPP 32
418
#include "vnchextile.h"
419
#undef BPP
420
#undef GENERIC
421

    
422
static void send_framebuffer_update_hextile(VncState *vs, int x, int y, int w, int h)
423
{
424
    int i, j;
425
    int has_fg, has_bg;
426
    uint32_t last_fg32, last_bg32;
427

    
428
    vnc_framebuffer_update(vs, x, y, w, h, 5);
429

    
430
    has_fg = has_bg = 0;
431
    for (j = y; j < (y + h); j += 16) {
432
        for (i = x; i < (x + w); i += 16) {
433
            vs->send_hextile_tile(vs, i, j,
434
                                  MIN(16, x + w - i), MIN(16, y + h - j),
435
                                  &last_bg32, &last_fg32, &has_bg, &has_fg);
436
        }
437
    }
438
}
439

    
440
static void send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
441
{
442
        if (vs->has_hextile)
443
            send_framebuffer_update_hextile(vs, x, y, w, h);
444
        else
445
            send_framebuffer_update_raw(vs, x, y, w, h);
446
}
447

    
448
static void vnc_copy(DisplayState *ds, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
449
{
450
    int src, dst;
451
    uint8_t *src_row;
452
    uint8_t *dst_row;
453
    char *old_row;
454
    int y = 0;
455
    int pitch = ds->linesize;
456
    VncState *vs = ds->opaque;
457

    
458
    vnc_update_client(vs);
459

    
460
    if (dst_y > src_y) {
461
        y = h - 1;
462
        pitch = -pitch;
463
    }
464

    
465
    src = (ds->linesize * (src_y + y) + vs->depth * src_x);
466
    dst = (ds->linesize * (dst_y + y) + vs->depth * dst_x);
467

    
468
    src_row = ds->data + src;
469
    dst_row = ds->data + dst;
470
    old_row = vs->old_data + dst;
471

    
472
    for (y = 0; y < h; y++) {
473
        memmove(old_row, src_row, w * vs->depth);
474
        memmove(dst_row, src_row, w * vs->depth);
475
        src_row += pitch;
476
        dst_row += pitch;
477
        old_row += pitch;
478
    }
479

    
480
    vnc_write_u8(vs, 0);  /* msg id */
481
    vnc_write_u8(vs, 0);
482
    vnc_write_u16(vs, 1); /* number of rects */
483
    vnc_framebuffer_update(vs, dst_x, dst_y, w, h, 1);
484
    vnc_write_u16(vs, src_x);
485
    vnc_write_u16(vs, src_y);
486
    vnc_flush(vs);
487
}
488

    
489
static int find_dirty_height(VncState *vs, int y, int last_x, int x)
490
{
491
    int h;
492

    
493
    for (h = 1; h < (vs->height - y); h++) {
494
        int tmp_x;
495
        if (!vnc_get_bit(vs->dirty_row[y + h], last_x))
496
            break;
497
        for (tmp_x = last_x; tmp_x < x; tmp_x++)
498
            vnc_clear_bit(vs->dirty_row[y + h], tmp_x);
499
    }
500

    
501
    return h;
502
}
503

    
504
static void vnc_update_client(void *opaque)
505
{
506
    VncState *vs = opaque;
507

    
508
    if (vs->need_update && vs->csock != -1) {
509
        int y;
510
        uint8_t *row;
511
        char *old_row;
512
        uint32_t width_mask[VNC_DIRTY_WORDS];
513
        int n_rectangles;
514
        int saved_offset;
515
        int has_dirty = 0;
516

    
517
        vga_hw_update();
518

    
519
        vnc_set_bits(width_mask, (vs->width / 16), VNC_DIRTY_WORDS);
520

    
521
        /* Walk through the dirty map and eliminate tiles that
522
           really aren't dirty */
523
        row = vs->ds->data;
524
        old_row = vs->old_data;
525

    
526
        for (y = 0; y < vs->height; y++) {
527
            if (vnc_and_bits(vs->dirty_row[y], width_mask, VNC_DIRTY_WORDS)) {
528
                int x;
529
                uint8_t *ptr;
530
                char *old_ptr;
531

    
532
                ptr = row;
533
                old_ptr = (char*)old_row;
534

    
535
                for (x = 0; x < vs->ds->width; x += 16) {
536
                    if (memcmp(old_ptr, ptr, 16 * vs->depth) == 0) {
537
                        vnc_clear_bit(vs->dirty_row[y], (x / 16));
538
                    } else {
539
                        has_dirty = 1;
540
                        memcpy(old_ptr, ptr, 16 * vs->depth);
541
                    }
542

    
543
                    ptr += 16 * vs->depth;
544
                    old_ptr += 16 * vs->depth;
545
                }
546
            }
547

    
548
            row += vs->ds->linesize;
549
            old_row += vs->ds->linesize;
550
        }
551

    
552
        if (!has_dirty) {
553
            qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);
554
            return;
555
        }
556

    
557
        /* Count rectangles */
558
        n_rectangles = 0;
559
        vnc_write_u8(vs, 0);  /* msg id */
560
        vnc_write_u8(vs, 0);
561
        saved_offset = vs->output.offset;
562
        vnc_write_u16(vs, 0);
563

    
564
        for (y = 0; y < vs->height; y++) {
565
            int x;
566
            int last_x = -1;
567
            for (x = 0; x < vs->width / 16; x++) {
568
                if (vnc_get_bit(vs->dirty_row[y], x)) {
569
                    if (last_x == -1) {
570
                        last_x = x;
571
                    }
572
                    vnc_clear_bit(vs->dirty_row[y], x);
573
                } else {
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
                    last_x = -1;
580
                }
581
            }
582
            if (last_x != -1) {
583
                int h = find_dirty_height(vs, y, last_x, x);
584
                send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
585
                n_rectangles++;
586
            }
587
        }
588
        vs->output.buffer[saved_offset] = (n_rectangles >> 8) & 0xFF;
589
        vs->output.buffer[saved_offset + 1] = n_rectangles & 0xFF;
590
        vnc_flush(vs);
591

    
592
    }
593

    
594
    if (vs->csock != -1) {
595
        qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);
596
    }
597

    
598
}
599

    
600
static int vnc_listen_poll(void *opaque)
601
{
602
    VncState *vs = opaque;
603
    if (vs->csock == -1)
604
        return 1;
605
    return 0;
606
}
607

    
608
static void buffer_reserve(Buffer *buffer, size_t len)
609
{
610
    if ((buffer->capacity - buffer->offset) < len) {
611
        buffer->capacity += (len + 1024);
612
        buffer->buffer = realloc(buffer->buffer, buffer->capacity);
613
        if (buffer->buffer == NULL) {
614
            fprintf(stderr, "vnc: out of memory\n");
615
            exit(1);
616
        }
617
    }
618
}
619

    
620
static int buffer_empty(Buffer *buffer)
621
{
622
    return buffer->offset == 0;
623
}
624

    
625
static uint8_t *buffer_end(Buffer *buffer)
626
{
627
    return buffer->buffer + buffer->offset;
628
}
629

    
630
static void buffer_reset(Buffer *buffer)
631
{
632
        buffer->offset = 0;
633
}
634

    
635
static void buffer_append(Buffer *buffer, const void *data, size_t len)
636
{
637
    memcpy(buffer->buffer + buffer->offset, data, len);
638
    buffer->offset += len;
639
}
640

    
641
static int vnc_client_io_error(VncState *vs, int ret, int last_errno)
642
{
643
    if (ret == 0 || ret == -1) {
644
        if (ret == -1) {
645
            switch (last_errno) {
646
                case EINTR:
647
                case EAGAIN:
648
#ifdef _WIN32
649
                case WSAEWOULDBLOCK:
650
#endif
651
                    return 0;
652
                default:
653
                    break;
654
            }
655
        }
656

    
657
        VNC_DEBUG("Closing down client sock %d %d\n", ret, ret < 0 ? last_errno : 0);
658
        qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
659
        closesocket(vs->csock);
660
        vs->csock = -1;
661
        buffer_reset(&vs->input);
662
        buffer_reset(&vs->output);
663
        vs->need_update = 0;
664
#if CONFIG_VNC_TLS
665
        if (vs->tls_session) {
666
            gnutls_deinit(vs->tls_session);
667
            vs->tls_session = NULL;
668
        }
669
        vs->wiremode = VNC_WIREMODE_CLEAR;
670
#endif /* CONFIG_VNC_TLS */
671
        return 0;
672
    }
673
    return ret;
674
}
675

    
676
static void vnc_client_error(VncState *vs)
677
{
678
    vnc_client_io_error(vs, -1, EINVAL);
679
}
680

    
681
static void vnc_client_write(void *opaque)
682
{
683
    long ret;
684
    VncState *vs = opaque;
685

    
686
#if CONFIG_VNC_TLS
687
    if (vs->tls_session) {
688
        ret = gnutls_write(vs->tls_session, vs->output.buffer, vs->output.offset);
689
        if (ret < 0) {
690
            if (ret == GNUTLS_E_AGAIN)
691
                errno = EAGAIN;
692
            else
693
                errno = EIO;
694
            ret = -1;
695
        }
696
    } else
697
#endif /* CONFIG_VNC_TLS */
698
        ret = send(vs->csock, vs->output.buffer, vs->output.offset, 0);
699
    ret = vnc_client_io_error(vs, ret, socket_error());
700
    if (!ret)
701
        return;
702

    
703
    memmove(vs->output.buffer, vs->output.buffer + ret, (vs->output.offset - ret));
704
    vs->output.offset -= ret;
705

    
706
    if (vs->output.offset == 0) {
707
        qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
708
    }
709
}
710

    
711
static void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
712
{
713
    vs->read_handler = func;
714
    vs->read_handler_expect = expecting;
715
}
716

    
717
static void vnc_client_read(void *opaque)
718
{
719
    VncState *vs = opaque;
720
    long ret;
721

    
722
    buffer_reserve(&vs->input, 4096);
723

    
724
#if CONFIG_VNC_TLS
725
    if (vs->tls_session) {
726
        ret = gnutls_read(vs->tls_session, buffer_end(&vs->input), 4096);
727
        if (ret < 0) {
728
            if (ret == GNUTLS_E_AGAIN)
729
                errno = EAGAIN;
730
            else
731
                errno = EIO;
732
            ret = -1;
733
        }
734
    } else
735
#endif /* CONFIG_VNC_TLS */
736
        ret = recv(vs->csock, buffer_end(&vs->input), 4096, 0);
737
    ret = vnc_client_io_error(vs, ret, socket_error());
738
    if (!ret)
739
        return;
740

    
741
    vs->input.offset += ret;
742

    
743
    while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
744
        size_t len = vs->read_handler_expect;
745
        int ret;
746

    
747
        ret = vs->read_handler(vs, vs->input.buffer, len);
748
        if (vs->csock == -1)
749
            return;
750

    
751
        if (!ret) {
752
            memmove(vs->input.buffer, vs->input.buffer + len, (vs->input.offset - len));
753
            vs->input.offset -= len;
754
        } else {
755
            vs->read_handler_expect = ret;
756
        }
757
    }
758
}
759

    
760
static void vnc_write(VncState *vs, const void *data, size_t len)
761
{
762
    buffer_reserve(&vs->output, len);
763

    
764
    if (buffer_empty(&vs->output)) {
765
        qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
766
    }
767

    
768
    buffer_append(&vs->output, data, len);
769
}
770

    
771
static void vnc_write_s32(VncState *vs, int32_t value)
772
{
773
    vnc_write_u32(vs, *(uint32_t *)&value);
774
}
775

    
776
static void vnc_write_u32(VncState *vs, uint32_t value)
777
{
778
    uint8_t buf[4];
779

    
780
    buf[0] = (value >> 24) & 0xFF;
781
    buf[1] = (value >> 16) & 0xFF;
782
    buf[2] = (value >>  8) & 0xFF;
783
    buf[3] = value & 0xFF;
784

    
785
    vnc_write(vs, buf, 4);
786
}
787

    
788
static void vnc_write_u16(VncState *vs, uint16_t value)
789
{
790
    uint8_t buf[2];
791

    
792
    buf[0] = (value >> 8) & 0xFF;
793
    buf[1] = value & 0xFF;
794

    
795
    vnc_write(vs, buf, 2);
796
}
797

    
798
static void vnc_write_u8(VncState *vs, uint8_t value)
799
{
800
    vnc_write(vs, (char *)&value, 1);
801
}
802

    
803
static void vnc_flush(VncState *vs)
804
{
805
    if (vs->output.offset)
806
        vnc_client_write(vs);
807
}
808

    
809
static uint8_t read_u8(uint8_t *data, size_t offset)
810
{
811
    return data[offset];
812
}
813

    
814
static uint16_t read_u16(uint8_t *data, size_t offset)
815
{
816
    return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
817
}
818

    
819
static int32_t read_s32(uint8_t *data, size_t offset)
820
{
821
    return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
822
                     (data[offset + 2] << 8) | data[offset + 3]);
823
}
824

    
825
static uint32_t read_u32(uint8_t *data, size_t offset)
826
{
827
    return ((data[offset] << 24) | (data[offset + 1] << 16) |
828
            (data[offset + 2] << 8) | data[offset + 3]);
829
}
830

    
831
#if CONFIG_VNC_TLS
832
static ssize_t vnc_tls_push(gnutls_transport_ptr_t transport,
833
                            const void *data,
834
                            size_t len) {
835
    struct VncState *vs = (struct VncState *)transport;
836
    int ret;
837

    
838
 retry:
839
    ret = send(vs->csock, data, len, 0);
840
    if (ret < 0) {
841
        if (errno == EINTR)
842
            goto retry;
843
        return -1;
844
    }
845
    return ret;
846
}
847

    
848

    
849
static ssize_t vnc_tls_pull(gnutls_transport_ptr_t transport,
850
                            void *data,
851
                            size_t len) {
852
    struct VncState *vs = (struct VncState *)transport;
853
    int ret;
854

    
855
 retry:
856
    ret = recv(vs->csock, data, len, 0);
857
    if (ret < 0) {
858
        if (errno == EINTR)
859
            goto retry;
860
        return -1;
861
    }
862
    return ret;
863
}
864
#endif /* CONFIG_VNC_TLS */
865

    
866
static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
867
{
868
}
869

    
870
static void check_pointer_type_change(VncState *vs, int absolute)
871
{
872
    if (vs->has_pointer_type_change && vs->absolute != absolute) {
873
        vnc_write_u8(vs, 0);
874
        vnc_write_u8(vs, 0);
875
        vnc_write_u16(vs, 1);
876
        vnc_framebuffer_update(vs, absolute, 0,
877
                               vs->ds->width, vs->ds->height, -257);
878
        vnc_flush(vs);
879
    }
880
    vs->absolute = absolute;
881
}
882

    
883
static void pointer_event(VncState *vs, int button_mask, int x, int y)
884
{
885
    int buttons = 0;
886
    int dz = 0;
887

    
888
    if (button_mask & 0x01)
889
        buttons |= MOUSE_EVENT_LBUTTON;
890
    if (button_mask & 0x02)
891
        buttons |= MOUSE_EVENT_MBUTTON;
892
    if (button_mask & 0x04)
893
        buttons |= MOUSE_EVENT_RBUTTON;
894
    if (button_mask & 0x08)
895
        dz = -1;
896
    if (button_mask & 0x10)
897
        dz = 1;
898

    
899
    if (vs->absolute) {
900
        kbd_mouse_event(x * 0x7FFF / (vs->ds->width - 1),
901
                        y * 0x7FFF / (vs->ds->height - 1),
902
                        dz, buttons);
903
    } else if (vs->has_pointer_type_change) {
904
        x -= 0x7FFF;
905
        y -= 0x7FFF;
906

    
907
        kbd_mouse_event(x, y, dz, buttons);
908
    } else {
909
        if (vs->last_x != -1)
910
            kbd_mouse_event(x - vs->last_x,
911
                            y - vs->last_y,
912
                            dz, buttons);
913
        vs->last_x = x;
914
        vs->last_y = y;
915
    }
916

    
917
    check_pointer_type_change(vs, kbd_mouse_is_absolute());
918
}
919

    
920
static void reset_keys(VncState *vs)
921
{
922
    int i;
923
    for(i = 0; i < 256; i++) {
924
        if (vs->modifiers_state[i]) {
925
            if (i & 0x80)
926
                kbd_put_keycode(0xe0);
927
            kbd_put_keycode(i | 0x80);
928
            vs->modifiers_state[i] = 0;
929
        }
930
    }
931
}
932

    
933
static void press_key(VncState *vs, int keysym)
934
{
935
    kbd_put_keycode(keysym2scancode(vs->kbd_layout, keysym) & 0x7f);
936
    kbd_put_keycode(keysym2scancode(vs->kbd_layout, keysym) | 0x80);
937
}
938

    
939
static void do_key_event(VncState *vs, int down, uint32_t sym)
940
{
941
    int keycode;
942

    
943
    keycode = keysym2scancode(vs->kbd_layout, sym & 0xFFFF);
944

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

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

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

    
1044
static void key_event(VncState *vs, int down, uint32_t sym)
1045
{
1046
    if (sym >= 'A' && sym <= 'Z' && is_graphic_console())
1047
        sym = sym - 'A' + 'a';
1048
    do_key_event(vs, down, sym);
1049
}
1050

    
1051
static void framebuffer_update_request(VncState *vs, int incremental,
1052
                                       int x_position, int y_position,
1053
                                       int w, int h)
1054
{
1055
    if (x_position > vs->ds->width)
1056
        x_position = vs->ds->width;
1057
    if (y_position > vs->ds->height)
1058
        y_position = vs->ds->height;
1059
    if (x_position + w >= vs->ds->width)
1060
        w = vs->ds->width  - x_position;
1061
    if (y_position + h >= vs->ds->height)
1062
        h = vs->ds->height - y_position;
1063

    
1064
    int i;
1065
    vs->need_update = 1;
1066
    if (!incremental) {
1067
        char *old_row = vs->old_data + y_position * vs->ds->linesize;
1068

    
1069
        for (i = 0; i < h; i++) {
1070
            vnc_set_bits(vs->dirty_row[y_position + i],
1071
                         (vs->ds->width / 16), VNC_DIRTY_WORDS);
1072
            memset(old_row, 42, vs->ds->width * vs->depth);
1073
            old_row += vs->ds->linesize;
1074
        }
1075
    }
1076
}
1077

    
1078
static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
1079
{
1080
    int i;
1081

    
1082
    vs->has_hextile = 0;
1083
    vs->has_resize = 0;
1084
    vs->has_pointer_type_change = 0;
1085
    vs->absolute = -1;
1086
    vs->ds->dpy_copy = NULL;
1087

    
1088
    for (i = n_encodings - 1; i >= 0; i--) {
1089
        switch (encodings[i]) {
1090
        case 0: /* Raw */
1091
            vs->has_hextile = 0;
1092
            break;
1093
        case 1: /* CopyRect */
1094
            vs->ds->dpy_copy = vnc_copy;
1095
            break;
1096
        case 5: /* Hextile */
1097
            vs->has_hextile = 1;
1098
            break;
1099
        case -223: /* DesktopResize */
1100
            vs->has_resize = 1;
1101
            break;
1102
        case -257:
1103
            vs->has_pointer_type_change = 1;
1104
            break;
1105
        default:
1106
            break;
1107
        }
1108
    }
1109

    
1110
    check_pointer_type_change(vs, kbd_mouse_is_absolute());
1111
}
1112

    
1113
static int compute_nbits(unsigned int val)
1114
{
1115
    int n;
1116
    n = 0;
1117
    while (val != 0) {
1118
        n++;
1119
        val >>= 1;
1120
    }
1121
    return n;
1122
}
1123

    
1124
static void set_pixel_format(VncState *vs,
1125
                             int bits_per_pixel, int depth,
1126
                             int big_endian_flag, int true_color_flag,
1127
                             int red_max, int green_max, int blue_max,
1128
                             int red_shift, int green_shift, int blue_shift)
1129
{
1130
    int host_big_endian_flag;
1131

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

    
1187
    vnc_dpy_resize(vs->ds, vs->ds->width, vs->ds->height);
1188

    
1189
    vga_hw_invalidate();
1190
    vga_hw_update();
1191
}
1192

    
1193
static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
1194
{
1195
    int i;
1196
    uint16_t limit;
1197

    
1198
    switch (data[0]) {
1199
    case 0:
1200
        if (len == 1)
1201
            return 20;
1202

    
1203
        set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
1204
                         read_u8(data, 6), read_u8(data, 7),
1205
                         read_u16(data, 8), read_u16(data, 10),
1206
                         read_u16(data, 12), read_u8(data, 14),
1207
                         read_u8(data, 15), read_u8(data, 16));
1208
        break;
1209
    case 2:
1210
        if (len == 1)
1211
            return 4;
1212

    
1213
        if (len == 4)
1214
            return 4 + (read_u16(data, 2) * 4);
1215

    
1216
        limit = read_u16(data, 2);
1217
        for (i = 0; i < limit; i++) {
1218
            int32_t val = read_s32(data, 4 + (i * 4));
1219
            memcpy(data + 4 + (i * 4), &val, sizeof(val));
1220
        }
1221

    
1222
        set_encodings(vs, (int32_t *)(data + 4), limit);
1223
        break;
1224
    case 3:
1225
        if (len == 1)
1226
            return 10;
1227

    
1228
        framebuffer_update_request(vs,
1229
                                   read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
1230
                                   read_u16(data, 6), read_u16(data, 8));
1231
        break;
1232
    case 4:
1233
        if (len == 1)
1234
            return 8;
1235

    
1236
        key_event(vs, read_u8(data, 1), read_u32(data, 4));
1237
        break;
1238
    case 5:
1239
        if (len == 1)
1240
            return 6;
1241

    
1242
        pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
1243
        break;
1244
    case 6:
1245
        if (len == 1)
1246
            return 8;
1247

    
1248
        if (len == 8) {
1249
            uint32_t dlen = read_u32(data, 4);
1250
            if (dlen > 0)
1251
                return 8 + dlen;
1252
        }
1253

    
1254
        client_cut_text(vs, read_u32(data, 4), data + 8);
1255
        break;
1256
    default:
1257
        printf("Msg: %d\n", data[0]);
1258
        vnc_client_error(vs);
1259
        break;
1260
    }
1261

    
1262
    vnc_read_when(vs, protocol_client_msg, 1);
1263
    return 0;
1264
}
1265

    
1266
static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
1267
{
1268
    char pad[3] = { 0, 0, 0 };
1269
    char buf[1024];
1270
    int size;
1271

    
1272
    vs->width = vs->ds->width;
1273
    vs->height = vs->ds->height;
1274
    vnc_write_u16(vs, vs->ds->width);
1275
    vnc_write_u16(vs, vs->ds->height);
1276

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

    
1313
    vnc_write(vs, pad, 3);           /* padding */
1314

    
1315
    if (qemu_name)
1316
        size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
1317
    else
1318
        size = snprintf(buf, sizeof(buf), "QEMU");
1319

    
1320
    vnc_write_u32(vs, size);
1321
    vnc_write(vs, buf, size);
1322
    vnc_flush(vs);
1323

    
1324
    vnc_read_when(vs, protocol_client_msg, 1);
1325

    
1326
    return 0;
1327
}
1328

    
1329
static void make_challenge(VncState *vs)
1330
{
1331
    int i;
1332

    
1333
    srand(time(NULL)+getpid()+getpid()*987654+rand());
1334

    
1335
    for (i = 0 ; i < sizeof(vs->challenge) ; i++)
1336
        vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
1337
}
1338

    
1339
static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
1340
{
1341
    unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
1342
    int i, j, pwlen;
1343
    unsigned char key[8];
1344

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

    
1358
    memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
1359

    
1360
    /* Calculate the expected challenge response */
1361
    pwlen = strlen(vs->password);
1362
    for (i=0; i<sizeof(key); i++)
1363
        key[i] = i<pwlen ? vs->password[i] : 0;
1364
    deskey(key, EN0);
1365
    for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
1366
        des(response+j, response+j);
1367

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

    
1384
        vnc_read_when(vs, protocol_client_init, 1);
1385
    }
1386
    return 0;
1387
}
1388

    
1389
static int start_auth_vnc(VncState *vs)
1390
{
1391
    make_challenge(vs);
1392
    /* Send client a 'random' challenge */
1393
    vnc_write(vs, vs->challenge, sizeof(vs->challenge));
1394
    vnc_flush(vs);
1395

    
1396
    vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
1397
    return 0;
1398
}
1399

    
1400

    
1401
#if CONFIG_VNC_TLS
1402
#define DH_BITS 1024
1403
static gnutls_dh_params_t dh_params;
1404

    
1405
static int vnc_tls_initialize(void)
1406
{
1407
    static int tlsinitialized = 0;
1408

    
1409
    if (tlsinitialized)
1410
        return 1;
1411

    
1412
    if (gnutls_global_init () < 0)
1413
        return 0;
1414

    
1415
    /* XXX ought to re-generate diffie-hellmen params periodically */
1416
    if (gnutls_dh_params_init (&dh_params) < 0)
1417
        return 0;
1418
    if (gnutls_dh_params_generate2 (dh_params, DH_BITS) < 0)
1419
        return 0;
1420

    
1421
#if _VNC_DEBUG == 2
1422
    gnutls_global_set_log_level(10);
1423
    gnutls_global_set_log_function(vnc_debug_gnutls_log);
1424
#endif
1425

    
1426
    tlsinitialized = 1;
1427

    
1428
    return 1;
1429
}
1430

    
1431
static gnutls_anon_server_credentials vnc_tls_initialize_anon_cred(void)
1432
{
1433
    gnutls_anon_server_credentials anon_cred;
1434
    int ret;
1435

    
1436
    if ((ret = gnutls_anon_allocate_server_credentials(&anon_cred)) < 0) {
1437
        VNC_DEBUG("Cannot allocate credentials %s\n", gnutls_strerror(ret));
1438
        return NULL;
1439
    }
1440

    
1441
    gnutls_anon_set_server_dh_params(anon_cred, dh_params);
1442

    
1443
    return anon_cred;
1444
}
1445

    
1446

    
1447
static gnutls_certificate_credentials_t vnc_tls_initialize_x509_cred(VncState *vs)
1448
{
1449
    gnutls_certificate_credentials_t x509_cred;
1450
    int ret;
1451

    
1452
    if (!vs->x509cacert) {
1453
        VNC_DEBUG("No CA x509 certificate specified\n");
1454
        return NULL;
1455
    }
1456
    if (!vs->x509cert) {
1457
        VNC_DEBUG("No server x509 certificate specified\n");
1458
        return NULL;
1459
    }
1460
    if (!vs->x509key) {
1461
        VNC_DEBUG("No server private key specified\n");
1462
        return NULL;
1463
    }
1464

    
1465
    if ((ret = gnutls_certificate_allocate_credentials(&x509_cred)) < 0) {
1466
        VNC_DEBUG("Cannot allocate credentials %s\n", gnutls_strerror(ret));
1467
        return NULL;
1468
    }
1469
    if ((ret = gnutls_certificate_set_x509_trust_file(x509_cred,
1470
                                                      vs->x509cacert,
1471
                                                      GNUTLS_X509_FMT_PEM)) < 0) {
1472
        VNC_DEBUG("Cannot load CA certificate %s\n", gnutls_strerror(ret));
1473
        gnutls_certificate_free_credentials(x509_cred);
1474
        return NULL;
1475
    }
1476

    
1477
    if ((ret = gnutls_certificate_set_x509_key_file (x509_cred,
1478
                                                     vs->x509cert,
1479
                                                     vs->x509key,
1480
                                                     GNUTLS_X509_FMT_PEM)) < 0) {
1481
        VNC_DEBUG("Cannot load certificate & key %s\n", gnutls_strerror(ret));
1482
        gnutls_certificate_free_credentials(x509_cred);
1483
        return NULL;
1484
    }
1485

    
1486
    if (vs->x509cacrl) {
1487
        if ((ret = gnutls_certificate_set_x509_crl_file(x509_cred,
1488
                                                        vs->x509cacrl,
1489
                                                        GNUTLS_X509_FMT_PEM)) < 0) {
1490
            VNC_DEBUG("Cannot load CRL %s\n", gnutls_strerror(ret));
1491
            gnutls_certificate_free_credentials(x509_cred);
1492
            return NULL;
1493
        }
1494
    }
1495

    
1496
    gnutls_certificate_set_dh_params (x509_cred, dh_params);
1497

    
1498
    return x509_cred;
1499
}
1500

    
1501
static int vnc_validate_certificate(struct VncState *vs)
1502
{
1503
    int ret;
1504
    unsigned int status;
1505
    const gnutls_datum_t *certs;
1506
    unsigned int nCerts, i;
1507
    time_t now;
1508

    
1509
    VNC_DEBUG("Validating client certificate\n");
1510
    if ((ret = gnutls_certificate_verify_peers2 (vs->tls_session, &status)) < 0) {
1511
        VNC_DEBUG("Verify failed %s\n", gnutls_strerror(ret));
1512
        return -1;
1513
    }
1514

    
1515
    if ((now = time(NULL)) == ((time_t)-1)) {
1516
        return -1;
1517
    }
1518

    
1519
    if (status != 0) {
1520
        if (status & GNUTLS_CERT_INVALID)
1521
            VNC_DEBUG("The certificate is not trusted.\n");
1522

    
1523
        if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
1524
            VNC_DEBUG("The certificate hasn't got a known issuer.\n");
1525

    
1526
        if (status & GNUTLS_CERT_REVOKED)
1527
            VNC_DEBUG("The certificate has been revoked.\n");
1528

    
1529
        if (status & GNUTLS_CERT_INSECURE_ALGORITHM)
1530
            VNC_DEBUG("The certificate uses an insecure algorithm\n");
1531

    
1532
        return -1;
1533
    } else {
1534
        VNC_DEBUG("Certificate is valid!\n");
1535
    }
1536

    
1537
    /* Only support x509 for now */
1538
    if (gnutls_certificate_type_get(vs->tls_session) != GNUTLS_CRT_X509)
1539
        return -1;
1540

    
1541
    if (!(certs = gnutls_certificate_get_peers(vs->tls_session, &nCerts)))
1542
        return -1;
1543

    
1544
    for (i = 0 ; i < nCerts ; i++) {
1545
        gnutls_x509_crt_t cert;
1546
        VNC_DEBUG ("Checking certificate chain %d\n", i);
1547
        if (gnutls_x509_crt_init (&cert) < 0)
1548
            return -1;
1549

    
1550
        if (gnutls_x509_crt_import(cert, &certs[i], GNUTLS_X509_FMT_DER) < 0) {
1551
            gnutls_x509_crt_deinit (cert);
1552
            return -1;
1553
        }
1554

    
1555
        if (gnutls_x509_crt_get_expiration_time (cert) < now) {
1556
            VNC_DEBUG("The certificate has expired\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
        if (gnutls_x509_crt_get_activation_time (cert) > now) {
1568
            VNC_DEBUG("The certificate is not yet activated\n");
1569
            gnutls_x509_crt_deinit (cert);
1570
            return -1;
1571
        }
1572

    
1573
        gnutls_x509_crt_deinit (cert);
1574
    }
1575

    
1576
    return 0;
1577
}
1578

    
1579

    
1580
static int start_auth_vencrypt_subauth(VncState *vs)
1581
{
1582
    switch (vs->subauth) {
1583
    case VNC_AUTH_VENCRYPT_TLSNONE:
1584
    case VNC_AUTH_VENCRYPT_X509NONE:
1585
       VNC_DEBUG("Accept TLS auth none\n");
1586
       vnc_write_u32(vs, 0); /* Accept auth completion */
1587
       vnc_read_when(vs, protocol_client_init, 1);
1588
       break;
1589

    
1590
    case VNC_AUTH_VENCRYPT_TLSVNC:
1591
    case VNC_AUTH_VENCRYPT_X509VNC:
1592
       VNC_DEBUG("Start TLS auth VNC\n");
1593
       return start_auth_vnc(vs);
1594

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

    
1606
    return 0;
1607
}
1608

    
1609
static void vnc_handshake_io(void *opaque);
1610

    
1611
static int vnc_continue_handshake(struct VncState *vs) {
1612
    int ret;
1613

    
1614
    if ((ret = gnutls_handshake(vs->tls_session)) < 0) {
1615
       if (!gnutls_error_is_fatal(ret)) {
1616
           VNC_DEBUG("Handshake interrupted (blocking)\n");
1617
           if (!gnutls_record_get_direction(vs->tls_session))
1618
               qemu_set_fd_handler(vs->csock, vnc_handshake_io, NULL, vs);
1619
           else
1620
               qemu_set_fd_handler(vs->csock, NULL, vnc_handshake_io, vs);
1621
           return 0;
1622
       }
1623
       VNC_DEBUG("Handshake failed %s\n", gnutls_strerror(ret));
1624
       vnc_client_error(vs);
1625
       return -1;
1626
    }
1627

    
1628
    if (vs->x509verify) {
1629
        if (vnc_validate_certificate(vs) < 0) {
1630
            VNC_DEBUG("Client verification failed\n");
1631
            vnc_client_error(vs);
1632
            return -1;
1633
        } else {
1634
            VNC_DEBUG("Client verification passed\n");
1635
        }
1636
    }
1637

    
1638
    VNC_DEBUG("Handshake done, switching to TLS data mode\n");
1639
    vs->wiremode = VNC_WIREMODE_TLS;
1640
    qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
1641

    
1642
    return start_auth_vencrypt_subauth(vs);
1643
}
1644

    
1645
static void vnc_handshake_io(void *opaque) {
1646
    struct VncState *vs = (struct VncState *)opaque;
1647

    
1648
    VNC_DEBUG("Handshake IO continue\n");
1649
    vnc_continue_handshake(vs);
1650
}
1651

    
1652
#define NEED_X509_AUTH(vs)                              \
1653
    ((vs)->subauth == VNC_AUTH_VENCRYPT_X509NONE ||   \
1654
     (vs)->subauth == VNC_AUTH_VENCRYPT_X509VNC ||    \
1655
     (vs)->subauth == VNC_AUTH_VENCRYPT_X509PLAIN)
1656

    
1657

    
1658
static int vnc_start_tls(struct VncState *vs) {
1659
    static const int cert_type_priority[] = { GNUTLS_CRT_X509, 0 };
1660
    static const int protocol_priority[]= { GNUTLS_TLS1_1, GNUTLS_TLS1_0, GNUTLS_SSL3, 0 };
1661
    static const int kx_anon[] = {GNUTLS_KX_ANON_DH, 0};
1662
    static const int kx_x509[] = {GNUTLS_KX_DHE_DSS, GNUTLS_KX_RSA, GNUTLS_KX_DHE_RSA, GNUTLS_KX_SRP, 0};
1663

    
1664
    VNC_DEBUG("Do TLS setup\n");
1665
    if (vnc_tls_initialize() < 0) {
1666
        VNC_DEBUG("Failed to init TLS\n");
1667
        vnc_client_error(vs);
1668
        return -1;
1669
    }
1670
    if (vs->tls_session == NULL) {
1671
        if (gnutls_init(&vs->tls_session, GNUTLS_SERVER) < 0) {
1672
            vnc_client_error(vs);
1673
            return -1;
1674
        }
1675

    
1676
        if (gnutls_set_default_priority(vs->tls_session) < 0) {
1677
            gnutls_deinit(vs->tls_session);
1678
            vs->tls_session = NULL;
1679
            vnc_client_error(vs);
1680
            return -1;
1681
        }
1682

    
1683
        if (gnutls_kx_set_priority(vs->tls_session, NEED_X509_AUTH(vs) ? kx_x509 : kx_anon) < 0) {
1684
            gnutls_deinit(vs->tls_session);
1685
            vs->tls_session = NULL;
1686
            vnc_client_error(vs);
1687
            return -1;
1688
        }
1689

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

    
1697
        if (gnutls_protocol_set_priority(vs->tls_session, protocol_priority) < 0) {
1698
            gnutls_deinit(vs->tls_session);
1699
            vs->tls_session = NULL;
1700
            vnc_client_error(vs);
1701
            return -1;
1702
        }
1703

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

    
1724
        } else {
1725
            gnutls_anon_server_credentials anon_cred = vnc_tls_initialize_anon_cred();
1726
            if (!anon_cred) {
1727
                gnutls_deinit(vs->tls_session);
1728
                vs->tls_session = NULL;
1729
                vnc_client_error(vs);
1730
                return -1;
1731
            }
1732
            if (gnutls_credentials_set(vs->tls_session, GNUTLS_CRD_ANON, anon_cred) < 0) {
1733
                gnutls_deinit(vs->tls_session);
1734
                vs->tls_session = NULL;
1735
                gnutls_anon_free_server_credentials(anon_cred);
1736
                vnc_client_error(vs);
1737
                return -1;
1738
            }
1739
        }
1740

    
1741
        gnutls_transport_set_ptr(vs->tls_session, (gnutls_transport_ptr_t)vs);
1742
        gnutls_transport_set_push_function(vs->tls_session, vnc_tls_push);
1743
        gnutls_transport_set_pull_function(vs->tls_session, vnc_tls_pull);
1744
    }
1745

    
1746
    VNC_DEBUG("Start TLS handshake process\n");
1747
    return vnc_continue_handshake(vs);
1748
}
1749

    
1750
static int protocol_client_vencrypt_auth(VncState *vs, uint8_t *data, size_t len)
1751
{
1752
    int auth = read_u32(data, 0);
1753

    
1754
    if (auth != vs->subauth) {
1755
        VNC_DEBUG("Rejecting auth %d\n", auth);
1756
        vnc_write_u8(vs, 0); /* Reject auth */
1757
        vnc_flush(vs);
1758
        vnc_client_error(vs);
1759
    } else {
1760
        VNC_DEBUG("Accepting auth %d, starting handshake\n", auth);
1761
        vnc_write_u8(vs, 1); /* Accept auth */
1762
        vnc_flush(vs);
1763

    
1764
        if (vnc_start_tls(vs) < 0) {
1765
            VNC_DEBUG("Failed to complete TLS\n");
1766
            return 0;
1767
        }
1768

    
1769
        if (vs->wiremode == VNC_WIREMODE_TLS) {
1770
            VNC_DEBUG("Starting VeNCrypt subauth\n");
1771
            return start_auth_vencrypt_subauth(vs);
1772
        } else {
1773
            VNC_DEBUG("TLS handshake blocked\n");
1774
            return 0;
1775
        }
1776
    }
1777
    return 0;
1778
}
1779

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

    
1799
static int start_auth_vencrypt(VncState *vs)
1800
{
1801
    /* Send VeNCrypt version 0.2 */
1802
    vnc_write_u8(vs, 0);
1803
    vnc_write_u8(vs, 2);
1804

    
1805
    vnc_read_when(vs, protocol_client_vencrypt_init, 2);
1806
    return 0;
1807
}
1808
#endif /* CONFIG_VNC_TLS */
1809

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

    
1835
       case VNC_AUTH_VNC:
1836
           VNC_DEBUG("Start VNC auth\n");
1837
           return start_auth_vnc(vs);
1838

    
1839
#if CONFIG_VNC_TLS
1840
       case VNC_AUTH_VENCRYPT:
1841
           VNC_DEBUG("Accept VeNCrypt auth\n");;
1842
           return start_auth_vencrypt(vs);
1843
#endif /* CONFIG_VNC_TLS */
1844

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

    
1859
static int protocol_version(VncState *vs, uint8_t *version, size_t len)
1860
{
1861
    char local[13];
1862

    
1863
    memcpy(local, version, 12);
1864
    local[12] = 0;
1865

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

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

    
1915
    return 0;
1916
}
1917

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

    
1934
static void vnc_listen_read(void *opaque)
1935
{
1936
    VncState *vs = opaque;
1937
    struct sockaddr_in addr;
1938
    socklen_t addrlen = sizeof(addr);
1939

    
1940
    /* Catch-up */
1941
    vga_hw_update();
1942

    
1943
    vs->csock = accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
1944
    if (vs->csock != -1) {
1945
        vnc_connect(vs);
1946
    }
1947
}
1948

    
1949
extern int parse_host_port(struct sockaddr_in *saddr, const char *str);
1950

    
1951
void vnc_display_init(DisplayState *ds)
1952
{
1953
    VncState *vs;
1954

    
1955
    vs = qemu_mallocz(sizeof(VncState));
1956
    if (!vs)
1957
        exit(1);
1958

    
1959
    ds->opaque = vs;
1960
    vnc_state = vs;
1961
    vs->display = NULL;
1962
    vs->password = NULL;
1963

    
1964
    vs->lsock = -1;
1965
    vs->csock = -1;
1966
    vs->depth = 4;
1967
    vs->last_x = -1;
1968
    vs->last_y = -1;
1969

    
1970
    vs->ds = ds;
1971

    
1972
    if (!keyboard_layout)
1973
        keyboard_layout = "en-us";
1974

    
1975
    vs->kbd_layout = init_keyboard_layout(keyboard_layout);
1976
    if (!vs->kbd_layout)
1977
        exit(1);
1978

    
1979
    vs->timer = qemu_new_timer(rt_clock, vnc_update_client, vs);
1980

    
1981
    vs->ds->data = NULL;
1982
    vs->ds->dpy_update = vnc_dpy_update;
1983
    vs->ds->dpy_resize = vnc_dpy_resize;
1984
    vs->ds->dpy_refresh = NULL;
1985

    
1986
    vnc_dpy_resize(vs->ds, 640, 400);
1987
}
1988

    
1989
#if CONFIG_VNC_TLS
1990
static int vnc_set_x509_credential(VncState *vs,
1991
                                   const char *certdir,
1992
                                   const char *filename,
1993
                                   char **cred,
1994
                                   int ignoreMissing)
1995
{
1996
    struct stat sb;
1997

    
1998
    if (*cred) {
1999
        qemu_free(*cred);
2000
        *cred = NULL;
2001
    }
2002

    
2003
    if (!(*cred = qemu_malloc(strlen(certdir) + strlen(filename) + 2)))
2004
        return -1;
2005

    
2006
    strcpy(*cred, certdir);
2007
    strcat(*cred, "/");
2008
    strcat(*cred, filename);
2009

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

    
2019
    return 0;
2020
}
2021

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

    
2034
    return 0;
2035

    
2036
 cleanup:
2037
    qemu_free(vs->x509cacert);
2038
    qemu_free(vs->x509cacrl);
2039
    qemu_free(vs->x509cert);
2040
    qemu_free(vs->x509key);
2041
    vs->x509cacert = vs->x509cacrl = vs->x509cert = vs->x509key = NULL;
2042
    return -1;
2043
}
2044
#endif /* CONFIG_VNC_TLS */
2045

    
2046
void vnc_display_close(DisplayState *ds)
2047
{
2048
    VncState *vs = ds ? (VncState *)ds->opaque : vnc_state;
2049

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

    
2081
int vnc_display_password(DisplayState *ds, const char *password)
2082
{
2083
    VncState *vs = ds ? (VncState *)ds->opaque : vnc_state;
2084

    
2085
    if (vs->password) {
2086
        qemu_free(vs->password);
2087
        vs->password = NULL;
2088
    }
2089
    if (password && password[0]) {
2090
        if (!(vs->password = qemu_strdup(password)))
2091
            return -1;
2092
    }
2093

    
2094
    return 0;
2095
}
2096

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

    
2115
    vnc_display_close(ds);
2116
    if (strcmp(display, "none") == 0)
2117
        return 0;
2118

    
2119
    if (!(vs->display = strdup(display)))
2120
        return -1;
2121

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

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

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

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

    
2218
        uaddr.sun_family = AF_UNIX;
2219
        memset(uaddr.sun_path, 0, 108);
2220
        snprintf(uaddr.sun_path, 108, "%s", p);
2221

    
2222
        if (!reverse) {
2223
            unlink(uaddr.sun_path);
2224
        }
2225
    } else
2226
#endif
2227
    {
2228
        addr = (struct sockaddr *)&iaddr;
2229
        addrlen = sizeof(iaddr);
2230

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

    
2238
        iaddr.sin_port = htons(ntohs(iaddr.sin_port) + (reverse ? 0 : 5900));
2239

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

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

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

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

    
2286
    if (listen(vs->lsock, 1) == -1) {
2287
        fprintf(stderr, "listen() failed\n");
2288
        close(vs->lsock);
2289
        vs->lsock = -1;
2290
        free(vs->display);
2291
        vs->display = NULL;
2292
        return -1;
2293
    }
2294

    
2295
    return qemu_set_fd_handler2(vs->lsock, vnc_listen_poll, vnc_listen_read, NULL, vs);
2296
}