Statistics
| Branch: | Revision:

root / vnc.c @ 87ecb68b

History | View | Annotate | Download (57 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
    char *buffer;
64
} Buffer;
65

    
66
typedef struct VncState VncState;
67

    
68
typedef int VncReadEvent(VncState *vs, char *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
    for (; y < h; y++)
262
        for (i = 0; i < w; i += 16)
263
            vnc_set_bit(vs->dirty_row[y], (x + i) / 16);
264
}
265

    
266
static void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
267
                                   int32_t encoding)
268
{
269
    vnc_write_u16(vs, x);
270
    vnc_write_u16(vs, y);
271
    vnc_write_u16(vs, w);
272
    vnc_write_u16(vs, h);
273

    
274
    vnc_write_s32(vs, encoding);
275
}
276

    
277
static void vnc_dpy_resize(DisplayState *ds, int w, int h)
278
{
279
    int size_changed;
280
    VncState *vs = ds->opaque;
281

    
282
    ds->data = realloc(ds->data, w * h * vs->depth);
283
    vs->old_data = realloc(vs->old_data, w * h * vs->depth);
284

    
285
    if (ds->data == NULL || vs->old_data == NULL) {
286
        fprintf(stderr, "vnc: memory allocation failed\n");
287
        exit(1);
288
    }
289

    
290
    if (ds->depth != vs->depth * 8) {
291
        ds->depth = vs->depth * 8;
292
        console_color_init(ds);
293
    }
294
    size_changed = ds->width != w || ds->height != h;
295
    ds->width = w;
296
    ds->height = h;
297
    ds->linesize = w * vs->depth;
298
    if (vs->csock != -1 && vs->has_resize && size_changed) {
299
        vnc_write_u8(vs, 0);  /* msg id */
300
        vnc_write_u8(vs, 0);
301
        vnc_write_u16(vs, 1); /* number of rects */
302
        vnc_framebuffer_update(vs, 0, 0, ds->width, ds->height, -223);
303
        vnc_flush(vs);
304
        vs->width = ds->width;
305
        vs->height = ds->height;
306
    }
307
}
308

    
309
/* fastest code */
310
static void vnc_write_pixels_copy(VncState *vs, void *pixels, int size)
311
{
312
    vnc_write(vs, pixels, size);
313
}
314

    
315
/* slowest but generic code. */
316
static void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
317
{
318
    unsigned int r, g, b;
319

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

    
356
static void vnc_write_pixels_generic(VncState *vs, void *pixels1, int size)
357
{
358
    uint32_t *pixels = pixels1;
359
    uint8_t buf[4];
360
    int n, i;
361

    
362
    n = size >> 2;
363
    for(i = 0; i < n; i++) {
364
        vnc_convert_pixel(vs, buf, pixels[i]);
365
        vnc_write(vs, buf, vs->pix_bpp);
366
    }
367
}
368

    
369
static void send_framebuffer_update_raw(VncState *vs, int x, int y, int w, int h)
370
{
371
    int i;
372
    char *row;
373

    
374
    vnc_framebuffer_update(vs, x, y, w, h, 0);
375

    
376
    row = vs->ds->data + y * vs->ds->linesize + x * vs->depth;
377
    for (i = 0; i < h; i++) {
378
        vs->write_pixels(vs, row, w * vs->depth);
379
        row += vs->ds->linesize;
380
    }
381
}
382

    
383
static void hextile_enc_cord(uint8_t *ptr, int x, int y, int w, int h)
384
{
385
    ptr[0] = ((x & 0x0F) << 4) | (y & 0x0F);
386
    ptr[1] = (((w - 1) & 0x0F) << 4) | ((h - 1) & 0x0F);
387
}
388

    
389
#define BPP 8
390
#include "vnchextile.h"
391
#undef BPP
392

    
393
#define BPP 16
394
#include "vnchextile.h"
395
#undef BPP
396

    
397
#define BPP 32
398
#include "vnchextile.h"
399
#undef BPP
400

    
401
#define GENERIC
402
#define BPP 32
403
#include "vnchextile.h"
404
#undef BPP
405
#undef GENERIC
406

    
407
static void send_framebuffer_update_hextile(VncState *vs, int x, int y, int w, int h)
408
{
409
    int i, j;
410
    int has_fg, has_bg;
411
    uint32_t last_fg32, last_bg32;
412

    
413
    vnc_framebuffer_update(vs, x, y, w, h, 5);
414

    
415
    has_fg = has_bg = 0;
416
    for (j = y; j < (y + h); j += 16) {
417
        for (i = x; i < (x + w); i += 16) {
418
            vs->send_hextile_tile(vs, i, j,
419
                                  MIN(16, x + w - i), MIN(16, y + h - j),
420
                                  &last_bg32, &last_fg32, &has_bg, &has_fg);
421
        }
422
    }
423
}
424

    
425
static void send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
426
{
427
        if (vs->has_hextile)
428
            send_framebuffer_update_hextile(vs, x, y, w, h);
429
        else
430
            send_framebuffer_update_raw(vs, x, y, w, h);
431
}
432

    
433
static void vnc_copy(DisplayState *ds, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
434
{
435
    int src, dst;
436
    char *src_row;
437
    char *dst_row;
438
    char *old_row;
439
    int y = 0;
440
    int pitch = ds->linesize;
441
    VncState *vs = ds->opaque;
442

    
443
    vnc_update_client(vs);
444

    
445
    if (dst_y > src_y) {
446
        y = h - 1;
447
        pitch = -pitch;
448
    }
449

    
450
    src = (ds->linesize * (src_y + y) + vs->depth * src_x);
451
    dst = (ds->linesize * (dst_y + y) + vs->depth * dst_x);
452

    
453
    src_row = ds->data + src;
454
    dst_row = ds->data + dst;
455
    old_row = vs->old_data + dst;
456

    
457
    for (y = 0; y < h; y++) {
458
        memmove(old_row, src_row, w * vs->depth);
459
        memmove(dst_row, src_row, w * vs->depth);
460
        src_row += pitch;
461
        dst_row += pitch;
462
        old_row += pitch;
463
    }
464

    
465
    vnc_write_u8(vs, 0);  /* msg id */
466
    vnc_write_u8(vs, 0);
467
    vnc_write_u16(vs, 1); /* number of rects */
468
    vnc_framebuffer_update(vs, dst_x, dst_y, w, h, 1);
469
    vnc_write_u16(vs, src_x);
470
    vnc_write_u16(vs, src_y);
471
    vnc_flush(vs);
472
}
473

    
474
static int find_dirty_height(VncState *vs, int y, int last_x, int x)
475
{
476
    int h;
477

    
478
    for (h = 1; h < (vs->height - y); h++) {
479
        int tmp_x;
480
        if (!vnc_get_bit(vs->dirty_row[y + h], last_x))
481
            break;
482
        for (tmp_x = last_x; tmp_x < x; tmp_x++)
483
            vnc_clear_bit(vs->dirty_row[y + h], tmp_x);
484
    }
485

    
486
    return h;
487
}
488

    
489
static void vnc_update_client(void *opaque)
490
{
491
    VncState *vs = opaque;
492

    
493
    if (vs->need_update && vs->csock != -1) {
494
        int y;
495
        char *row;
496
        char *old_row;
497
        uint32_t width_mask[VNC_DIRTY_WORDS];
498
        int n_rectangles;
499
        int saved_offset;
500
        int has_dirty = 0;
501

    
502
        vnc_set_bits(width_mask, (vs->width / 16), VNC_DIRTY_WORDS);
503

    
504
        /* Walk through the dirty map and eliminate tiles that
505
           really aren't dirty */
506
        row = vs->ds->data;
507
        old_row = vs->old_data;
508

    
509
        for (y = 0; y < vs->height; y++) {
510
            if (vnc_and_bits(vs->dirty_row[y], width_mask, VNC_DIRTY_WORDS)) {
511
                int x;
512
                char *ptr, *old_ptr;
513

    
514
                ptr = row;
515
                old_ptr = old_row;
516

    
517
                for (x = 0; x < vs->ds->width; x += 16) {
518
                    if (memcmp(old_ptr, ptr, 16 * vs->depth) == 0) {
519
                        vnc_clear_bit(vs->dirty_row[y], (x / 16));
520
                    } else {
521
                        has_dirty = 1;
522
                        memcpy(old_ptr, ptr, 16 * vs->depth);
523
                    }
524

    
525
                    ptr += 16 * vs->depth;
526
                    old_ptr += 16 * vs->depth;
527
                }
528
            }
529

    
530
            row += vs->ds->linesize;
531
            old_row += vs->ds->linesize;
532
        }
533

    
534
        if (!has_dirty) {
535
            qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);
536
            return;
537
        }
538

    
539
        /* Count rectangles */
540
        n_rectangles = 0;
541
        vnc_write_u8(vs, 0);  /* msg id */
542
        vnc_write_u8(vs, 0);
543
        saved_offset = vs->output.offset;
544
        vnc_write_u16(vs, 0);
545

    
546
        for (y = 0; y < vs->height; y++) {
547
            int x;
548
            int last_x = -1;
549
            for (x = 0; x < vs->width / 16; x++) {
550
                if (vnc_get_bit(vs->dirty_row[y], x)) {
551
                    if (last_x == -1) {
552
                        last_x = x;
553
                    }
554
                    vnc_clear_bit(vs->dirty_row[y], x);
555
                } else {
556
                    if (last_x != -1) {
557
                        int h = find_dirty_height(vs, y, last_x, x);
558
                        send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
559
                        n_rectangles++;
560
                    }
561
                    last_x = -1;
562
                }
563
            }
564
            if (last_x != -1) {
565
                int h = find_dirty_height(vs, y, last_x, x);
566
                send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
567
                n_rectangles++;
568
            }
569
        }
570
        vs->output.buffer[saved_offset] = (n_rectangles >> 8) & 0xFF;
571
        vs->output.buffer[saved_offset + 1] = n_rectangles & 0xFF;
572
        vnc_flush(vs);
573

    
574
    }
575
    qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);
576
}
577

    
578
static void vnc_timer_init(VncState *vs)
579
{
580
    if (vs->timer == NULL) {
581
        vs->timer = qemu_new_timer(rt_clock, vnc_update_client, vs);
582
        qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock));
583
    }
584
}
585

    
586
static void vnc_dpy_refresh(DisplayState *ds)
587
{
588
    VncState *vs = ds->opaque;
589
    vnc_timer_init(vs);
590
    vga_hw_update();
591
}
592

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

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

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

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

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

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

    
634
static int vnc_client_io_error(VncState *vs, int ret, int last_errno)
635
{
636
    if (ret == 0 || ret == -1) {
637
        if (ret == -1 && (last_errno == EINTR || last_errno == EAGAIN))
638
            return 0;
639

    
640
        VNC_DEBUG("Closing down client sock %d %d\n", ret, ret < 0 ? last_errno : 0);
641
        qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
642
        closesocket(vs->csock);
643
        vs->csock = -1;
644
        buffer_reset(&vs->input);
645
        buffer_reset(&vs->output);
646
        vs->need_update = 0;
647
#if CONFIG_VNC_TLS
648
        if (vs->tls_session) {
649
            gnutls_deinit(vs->tls_session);
650
            vs->tls_session = NULL;
651
        }
652
        vs->wiremode = VNC_WIREMODE_CLEAR;
653
#endif /* CONFIG_VNC_TLS */
654
        return 0;
655
    }
656
    return ret;
657
}
658

    
659
static void vnc_client_error(VncState *vs)
660
{
661
    vnc_client_io_error(vs, -1, EINVAL);
662
}
663

    
664
static void vnc_client_write(void *opaque)
665
{
666
    long ret;
667
    VncState *vs = opaque;
668

    
669
#if CONFIG_VNC_TLS
670
    if (vs->tls_session) {
671
        ret = gnutls_write(vs->tls_session, vs->output.buffer, vs->output.offset);
672
        if (ret < 0) {
673
            if (ret == GNUTLS_E_AGAIN)
674
                errno = EAGAIN;
675
            else
676
                errno = EIO;
677
            ret = -1;
678
        }
679
    } else
680
#endif /* CONFIG_VNC_TLS */
681
        ret = send(vs->csock, vs->output.buffer, vs->output.offset, 0);
682
    ret = vnc_client_io_error(vs, ret, socket_error());
683
    if (!ret)
684
        return;
685

    
686
    memmove(vs->output.buffer, vs->output.buffer + ret, (vs->output.offset - ret));
687
    vs->output.offset -= ret;
688

    
689
    if (vs->output.offset == 0) {
690
        qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
691
    }
692
}
693

    
694
static void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
695
{
696
    vs->read_handler = func;
697
    vs->read_handler_expect = expecting;
698
}
699

    
700
static void vnc_client_read(void *opaque)
701
{
702
    VncState *vs = opaque;
703
    long ret;
704

    
705
    buffer_reserve(&vs->input, 4096);
706

    
707
#if CONFIG_VNC_TLS
708
    if (vs->tls_session) {
709
        ret = gnutls_read(vs->tls_session, buffer_end(&vs->input), 4096);
710
        if (ret < 0) {
711
            if (ret == GNUTLS_E_AGAIN)
712
                errno = EAGAIN;
713
            else
714
                errno = EIO;
715
            ret = -1;
716
        }
717
    } else
718
#endif /* CONFIG_VNC_TLS */
719
        ret = recv(vs->csock, buffer_end(&vs->input), 4096, 0);
720
    ret = vnc_client_io_error(vs, ret, socket_error());
721
    if (!ret)
722
        return;
723

    
724
    vs->input.offset += ret;
725

    
726
    while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
727
        size_t len = vs->read_handler_expect;
728
        int ret;
729

    
730
        ret = vs->read_handler(vs, vs->input.buffer, len);
731
        if (vs->csock == -1)
732
            return;
733

    
734
        if (!ret) {
735
            memmove(vs->input.buffer, vs->input.buffer + len, (vs->input.offset - len));
736
            vs->input.offset -= len;
737
        } else {
738
            vs->read_handler_expect = ret;
739
        }
740
    }
741
}
742

    
743
static void vnc_write(VncState *vs, const void *data, size_t len)
744
{
745
    buffer_reserve(&vs->output, len);
746

    
747
    if (buffer_empty(&vs->output)) {
748
        qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
749
    }
750

    
751
    buffer_append(&vs->output, data, len);
752
}
753

    
754
static void vnc_write_s32(VncState *vs, int32_t value)
755
{
756
    vnc_write_u32(vs, *(uint32_t *)&value);
757
}
758

    
759
static void vnc_write_u32(VncState *vs, uint32_t value)
760
{
761
    uint8_t buf[4];
762

    
763
    buf[0] = (value >> 24) & 0xFF;
764
    buf[1] = (value >> 16) & 0xFF;
765
    buf[2] = (value >>  8) & 0xFF;
766
    buf[3] = value & 0xFF;
767

    
768
    vnc_write(vs, buf, 4);
769
}
770

    
771
static void vnc_write_u16(VncState *vs, uint16_t value)
772
{
773
    uint8_t buf[2];
774

    
775
    buf[0] = (value >> 8) & 0xFF;
776
    buf[1] = value & 0xFF;
777

    
778
    vnc_write(vs, buf, 2);
779
}
780

    
781
static void vnc_write_u8(VncState *vs, uint8_t value)
782
{
783
    vnc_write(vs, (char *)&value, 1);
784
}
785

    
786
static void vnc_flush(VncState *vs)
787
{
788
    if (vs->output.offset)
789
        vnc_client_write(vs);
790
}
791

    
792
static uint8_t read_u8(uint8_t *data, size_t offset)
793
{
794
    return data[offset];
795
}
796

    
797
static uint16_t read_u16(uint8_t *data, size_t offset)
798
{
799
    return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
800
}
801

    
802
static int32_t read_s32(uint8_t *data, size_t offset)
803
{
804
    return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
805
                     (data[offset + 2] << 8) | data[offset + 3]);
806
}
807

    
808
static uint32_t read_u32(uint8_t *data, size_t offset)
809
{
810
    return ((data[offset] << 24) | (data[offset + 1] << 16) |
811
            (data[offset + 2] << 8) | data[offset + 3]);
812
}
813

    
814
#if CONFIG_VNC_TLS
815
ssize_t vnc_tls_push(gnutls_transport_ptr_t transport,
816
                     const void *data,
817
                     size_t len) {
818
    struct VncState *vs = (struct VncState *)transport;
819
    int ret;
820

    
821
 retry:
822
    ret = send(vs->csock, data, len, 0);
823
    if (ret < 0) {
824
        if (errno == EINTR)
825
            goto retry;
826
        return -1;
827
    }
828
    return ret;
829
}
830

    
831

    
832
ssize_t vnc_tls_pull(gnutls_transport_ptr_t transport,
833
                     void *data,
834
                     size_t len) {
835
    struct VncState *vs = (struct VncState *)transport;
836
    int ret;
837

    
838
 retry:
839
    ret = recv(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
#endif /* CONFIG_VNC_TLS */
848

    
849
static void client_cut_text(VncState *vs, size_t len, char *text)
850
{
851
}
852

    
853
static void check_pointer_type_change(VncState *vs, int absolute)
854
{
855
    if (vs->has_pointer_type_change && vs->absolute != absolute) {
856
        vnc_write_u8(vs, 0);
857
        vnc_write_u8(vs, 0);
858
        vnc_write_u16(vs, 1);
859
        vnc_framebuffer_update(vs, absolute, 0,
860
                               vs->ds->width, vs->ds->height, -257);
861
        vnc_flush(vs);
862
    }
863
    vs->absolute = absolute;
864
}
865

    
866
static void pointer_event(VncState *vs, int button_mask, int x, int y)
867
{
868
    int buttons = 0;
869
    int dz = 0;
870

    
871
    if (button_mask & 0x01)
872
        buttons |= MOUSE_EVENT_LBUTTON;
873
    if (button_mask & 0x02)
874
        buttons |= MOUSE_EVENT_MBUTTON;
875
    if (button_mask & 0x04)
876
        buttons |= MOUSE_EVENT_RBUTTON;
877
    if (button_mask & 0x08)
878
        dz = -1;
879
    if (button_mask & 0x10)
880
        dz = 1;
881

    
882
    if (vs->absolute) {
883
        kbd_mouse_event(x * 0x7FFF / vs->ds->width,
884
                        y * 0x7FFF / vs->ds->height,
885
                        dz, buttons);
886
    } else if (vs->has_pointer_type_change) {
887
        x -= 0x7FFF;
888
        y -= 0x7FFF;
889

    
890
        kbd_mouse_event(x, y, dz, buttons);
891
    } else {
892
        if (vs->last_x != -1)
893
            kbd_mouse_event(x - vs->last_x,
894
                            y - vs->last_y,
895
                            dz, buttons);
896
        vs->last_x = x;
897
        vs->last_y = y;
898
    }
899

    
900
    check_pointer_type_change(vs, kbd_mouse_is_absolute());
901
}
902

    
903
static void reset_keys(VncState *vs)
904
{
905
    int i;
906
    for(i = 0; i < 256; i++) {
907
        if (vs->modifiers_state[i]) {
908
            if (i & 0x80)
909
                kbd_put_keycode(0xe0);
910
            kbd_put_keycode(i | 0x80);
911
            vs->modifiers_state[i] = 0;
912
        }
913
    }
914
}
915

    
916
static void press_key(VncState *vs, int keysym)
917
{
918
    kbd_put_keycode(keysym2scancode(vs->kbd_layout, keysym) & 0x7f);
919
    kbd_put_keycode(keysym2scancode(vs->kbd_layout, keysym) | 0x80);
920
}
921

    
922
static void do_key_event(VncState *vs, int down, uint32_t sym)
923
{
924
    int keycode;
925

    
926
    keycode = keysym2scancode(vs->kbd_layout, sym & 0xFFFF);
927

    
928
    /* QEMU console switch */
929
    switch(keycode) {
930
    case 0x2a:                          /* Left Shift */
931
    case 0x36:                          /* Right Shift */
932
    case 0x1d:                          /* Left CTRL */
933
    case 0x9d:                          /* Right CTRL */
934
    case 0x38:                          /* Left ALT */
935
    case 0xb8:                          /* Right ALT */
936
        if (down)
937
            vs->modifiers_state[keycode] = 1;
938
        else
939
            vs->modifiers_state[keycode] = 0;
940
        break;
941
    case 0x02 ... 0x0a: /* '1' to '9' keys */
942
        if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
943
            /* Reset the modifiers sent to the current console */
944
            reset_keys(vs);
945
            console_select(keycode - 0x02);
946
            return;
947
        }
948
        break;
949
    case 0x45:                        /* NumLock */
950
        if (!down)
951
            vs->modifiers_state[keycode] ^= 1;
952
        break;
953
    }
954

    
955
    if (keycode_is_keypad(vs->kbd_layout, keycode)) {
956
        /* If the numlock state needs to change then simulate an additional
957
           keypress before sending this one.  This will happen if the user
958
           toggles numlock away from the VNC window.
959
        */
960
        if (keysym_is_numlock(vs->kbd_layout, sym & 0xFFFF)) {
961
            if (!vs->modifiers_state[0x45]) {
962
                vs->modifiers_state[0x45] = 1;
963
                press_key(vs, 0xff7f);
964
            }
965
        } else {
966
            if (vs->modifiers_state[0x45]) {
967
                vs->modifiers_state[0x45] = 0;
968
                press_key(vs, 0xff7f);
969
            }
970
        }
971
    }
972

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

    
1026
static void key_event(VncState *vs, int down, uint32_t sym)
1027
{
1028
    if (sym >= 'A' && sym <= 'Z' && is_graphic_console())
1029
        sym = sym - 'A' + 'a';
1030
    do_key_event(vs, down, sym);
1031
}
1032

    
1033
static void framebuffer_update_request(VncState *vs, int incremental,
1034
                                       int x_position, int y_position,
1035
                                       int w, int h)
1036
{
1037
    if (x_position > vs->ds->width)
1038
        x_position = vs->ds->width;
1039
    if (y_position > vs->ds->height)
1040
        y_position = vs->ds->height;
1041
    if (x_position + w >= vs->ds->width)
1042
        w = vs->ds->width  - x_position;
1043
    if (y_position + h >= vs->ds->height)
1044
        h = vs->ds->height - y_position;
1045

    
1046
    int i;
1047
    vs->need_update = 1;
1048
    if (!incremental) {
1049
        char *old_row = vs->old_data + y_position * vs->ds->linesize;
1050

    
1051
        for (i = 0; i < h; i++) {
1052
            vnc_set_bits(vs->dirty_row[y_position + i],
1053
                         (vs->ds->width / 16), VNC_DIRTY_WORDS);
1054
            memset(old_row, 42, vs->ds->width * vs->depth);
1055
            old_row += vs->ds->linesize;
1056
        }
1057
    }
1058
}
1059

    
1060
static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
1061
{
1062
    int i;
1063

    
1064
    vs->has_hextile = 0;
1065
    vs->has_resize = 0;
1066
    vs->has_pointer_type_change = 0;
1067
    vs->absolute = -1;
1068
    vs->ds->dpy_copy = NULL;
1069

    
1070
    for (i = n_encodings - 1; i >= 0; i--) {
1071
        switch (encodings[i]) {
1072
        case 0: /* Raw */
1073
            vs->has_hextile = 0;
1074
            break;
1075
        case 1: /* CopyRect */
1076
            vs->ds->dpy_copy = vnc_copy;
1077
            break;
1078
        case 5: /* Hextile */
1079
            vs->has_hextile = 1;
1080
            break;
1081
        case -223: /* DesktopResize */
1082
            vs->has_resize = 1;
1083
            break;
1084
        case -257:
1085
            vs->has_pointer_type_change = 1;
1086
            break;
1087
        default:
1088
            break;
1089
        }
1090
    }
1091

    
1092
    check_pointer_type_change(vs, kbd_mouse_is_absolute());
1093
}
1094

    
1095
static int compute_nbits(unsigned int val)
1096
{
1097
    int n;
1098
    n = 0;
1099
    while (val != 0) {
1100
        n++;
1101
        val >>= 1;
1102
    }
1103
    return n;
1104
}
1105

    
1106
static void set_pixel_format(VncState *vs,
1107
                             int bits_per_pixel, int depth,
1108
                             int big_endian_flag, int true_color_flag,
1109
                             int red_max, int green_max, int blue_max,
1110
                             int red_shift, int green_shift, int blue_shift)
1111
{
1112
    int host_big_endian_flag;
1113

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

    
1169
    vnc_dpy_resize(vs->ds, vs->ds->width, vs->ds->height);
1170
    memset(vs->dirty_row, 0xFF, sizeof(vs->dirty_row));
1171
    memset(vs->old_data, 42, vs->ds->linesize * vs->ds->height);
1172

    
1173
    vga_hw_invalidate();
1174
    vga_hw_update();
1175
}
1176

    
1177
static int protocol_client_msg(VncState *vs, char *data, size_t len)
1178
{
1179
    int i;
1180
    uint16_t limit;
1181

    
1182
    switch (data[0]) {
1183
    case 0:
1184
        if (len == 1)
1185
            return 20;
1186

    
1187
        set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
1188
                         read_u8(data, 6), read_u8(data, 7),
1189
                         read_u16(data, 8), read_u16(data, 10),
1190
                         read_u16(data, 12), read_u8(data, 14),
1191
                         read_u8(data, 15), read_u8(data, 16));
1192
        break;
1193
    case 2:
1194
        if (len == 1)
1195
            return 4;
1196

    
1197
        if (len == 4)
1198
            return 4 + (read_u16(data, 2) * 4);
1199

    
1200
        limit = read_u16(data, 2);
1201
        for (i = 0; i < limit; i++) {
1202
            int32_t val = read_s32(data, 4 + (i * 4));
1203
            memcpy(data + 4 + (i * 4), &val, sizeof(val));
1204
        }
1205

    
1206
        set_encodings(vs, (int32_t *)(data + 4), limit);
1207
        break;
1208
    case 3:
1209
        if (len == 1)
1210
            return 10;
1211

    
1212
        framebuffer_update_request(vs,
1213
                                   read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
1214
                                   read_u16(data, 6), read_u16(data, 8));
1215
        break;
1216
    case 4:
1217
        if (len == 1)
1218
            return 8;
1219

    
1220
        key_event(vs, read_u8(data, 1), read_u32(data, 4));
1221
        break;
1222
    case 5:
1223
        if (len == 1)
1224
            return 6;
1225

    
1226
        pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
1227
        break;
1228
    case 6:
1229
        if (len == 1)
1230
            return 8;
1231

    
1232
        if (len == 8) {
1233
            uint32_t dlen = read_u32(data, 4);
1234
            if (dlen > 0)
1235
                return 8 + dlen;
1236
        }
1237

    
1238
        client_cut_text(vs, read_u32(data, 4), data + 8);
1239
        break;
1240
    default:
1241
        printf("Msg: %d\n", data[0]);
1242
        vnc_client_error(vs);
1243
        break;
1244
    }
1245

    
1246
    vnc_read_when(vs, protocol_client_msg, 1);
1247
    return 0;
1248
}
1249

    
1250
static int protocol_client_init(VncState *vs, char *data, size_t len)
1251
{
1252
    char pad[3] = { 0, 0, 0 };
1253
    char buf[1024];
1254
    int size;
1255

    
1256
    vs->width = vs->ds->width;
1257
    vs->height = vs->ds->height;
1258
    vnc_write_u16(vs, vs->ds->width);
1259
    vnc_write_u16(vs, vs->ds->height);
1260

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

    
1297
    vnc_write(vs, pad, 3);           /* padding */
1298

    
1299
    if (qemu_name)
1300
        size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
1301
    else
1302
        size = snprintf(buf, sizeof(buf), "QEMU");
1303

    
1304
    vnc_write_u32(vs, size);
1305
    vnc_write(vs, buf, size);
1306
    vnc_flush(vs);
1307

    
1308
    vnc_read_when(vs, protocol_client_msg, 1);
1309

    
1310
    return 0;
1311
}
1312

    
1313
static void make_challenge(VncState *vs)
1314
{
1315
    int i;
1316

    
1317
    srand(time(NULL)+getpid()+getpid()*987654+rand());
1318

    
1319
    for (i = 0 ; i < sizeof(vs->challenge) ; i++)
1320
        vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
1321
}
1322

    
1323
static int protocol_client_auth_vnc(VncState *vs, char *data, size_t len)
1324
{
1325
    char response[VNC_AUTH_CHALLENGE_SIZE];
1326
    int i, j, pwlen;
1327
    char key[8];
1328

    
1329
    if (!vs->password || !vs->password[0]) {
1330
        VNC_DEBUG("No password configured on server");
1331
        vnc_write_u32(vs, 1); /* Reject auth */
1332
        if (vs->minor >= 8) {
1333
            static const char err[] = "Authentication failed";
1334
            vnc_write_u32(vs, sizeof(err));
1335
            vnc_write(vs, err, sizeof(err));
1336
        }
1337
        vnc_flush(vs);
1338
        vnc_client_error(vs);
1339
        return 0;
1340
    }
1341

    
1342
    memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
1343

    
1344
    /* Calculate the expected challenge response */
1345
    pwlen = strlen(vs->password);
1346
    for (i=0; i<sizeof(key); i++)
1347
        key[i] = i<pwlen ? vs->password[i] : 0;
1348
    deskey(key, EN0);
1349
    for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
1350
        des(response+j, response+j);
1351

    
1352
    /* Compare expected vs actual challenge response */
1353
    if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
1354
        VNC_DEBUG("Client challenge reponse did not match\n");
1355
        vnc_write_u32(vs, 1); /* Reject auth */
1356
        if (vs->minor >= 8) {
1357
            static const char err[] = "Authentication failed";
1358
            vnc_write_u32(vs, sizeof(err));
1359
            vnc_write(vs, err, sizeof(err));
1360
        }
1361
        vnc_flush(vs);
1362
        vnc_client_error(vs);
1363
    } else {
1364
        VNC_DEBUG("Accepting VNC challenge response\n");
1365
        vnc_write_u32(vs, 0); /* Accept auth */
1366
        vnc_flush(vs);
1367

    
1368
        vnc_read_when(vs, protocol_client_init, 1);
1369
    }
1370
    return 0;
1371
}
1372

    
1373
static int start_auth_vnc(VncState *vs)
1374
{
1375
    make_challenge(vs);
1376
    /* Send client a 'random' challenge */
1377
    vnc_write(vs, vs->challenge, sizeof(vs->challenge));
1378
    vnc_flush(vs);
1379

    
1380
    vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
1381
    return 0;
1382
}
1383

    
1384

    
1385
#if CONFIG_VNC_TLS
1386
#define DH_BITS 1024
1387
static gnutls_dh_params_t dh_params;
1388

    
1389
static int vnc_tls_initialize(void)
1390
{
1391
    static int tlsinitialized = 0;
1392

    
1393
    if (tlsinitialized)
1394
        return 1;
1395

    
1396
    if (gnutls_global_init () < 0)
1397
        return 0;
1398

    
1399
    /* XXX ought to re-generate diffie-hellmen params periodically */
1400
    if (gnutls_dh_params_init (&dh_params) < 0)
1401
        return 0;
1402
    if (gnutls_dh_params_generate2 (dh_params, DH_BITS) < 0)
1403
        return 0;
1404

    
1405
#if _VNC_DEBUG == 2
1406
    gnutls_global_set_log_level(10);
1407
    gnutls_global_set_log_function(vnc_debug_gnutls_log);
1408
#endif
1409

    
1410
    tlsinitialized = 1;
1411

    
1412
    return 1;
1413
}
1414

    
1415
static gnutls_anon_server_credentials vnc_tls_initialize_anon_cred(void)
1416
{
1417
    gnutls_anon_server_credentials anon_cred;
1418
    int ret;
1419

    
1420
    if ((ret = gnutls_anon_allocate_server_credentials(&anon_cred)) < 0) {
1421
        VNC_DEBUG("Cannot allocate credentials %s\n", gnutls_strerror(ret));
1422
        return NULL;
1423
    }
1424

    
1425
    gnutls_anon_set_server_dh_params(anon_cred, dh_params);
1426

    
1427
    return anon_cred;
1428
}
1429

    
1430

    
1431
static gnutls_certificate_credentials_t vnc_tls_initialize_x509_cred(VncState *vs)
1432
{
1433
    gnutls_certificate_credentials_t x509_cred;
1434
    int ret;
1435

    
1436
    if (!vs->x509cacert) {
1437
        VNC_DEBUG("No CA x509 certificate specified\n");
1438
        return NULL;
1439
    }
1440
    if (!vs->x509cert) {
1441
        VNC_DEBUG("No server x509 certificate specified\n");
1442
        return NULL;
1443
    }
1444
    if (!vs->x509key) {
1445
        VNC_DEBUG("No server private key specified\n");
1446
        return NULL;
1447
    }
1448

    
1449
    if ((ret = gnutls_certificate_allocate_credentials(&x509_cred)) < 0) {
1450
        VNC_DEBUG("Cannot allocate credentials %s\n", gnutls_strerror(ret));
1451
        return NULL;
1452
    }
1453
    if ((ret = gnutls_certificate_set_x509_trust_file(x509_cred,
1454
                                                      vs->x509cacert,
1455
                                                      GNUTLS_X509_FMT_PEM)) < 0) {
1456
        VNC_DEBUG("Cannot load CA certificate %s\n", gnutls_strerror(ret));
1457
        gnutls_certificate_free_credentials(x509_cred);
1458
        return NULL;
1459
    }
1460

    
1461
    if ((ret = gnutls_certificate_set_x509_key_file (x509_cred,
1462
                                                     vs->x509cert,
1463
                                                     vs->x509key,
1464
                                                     GNUTLS_X509_FMT_PEM)) < 0) {
1465
        VNC_DEBUG("Cannot load certificate & key %s\n", gnutls_strerror(ret));
1466
        gnutls_certificate_free_credentials(x509_cred);
1467
        return NULL;
1468
    }
1469

    
1470
    if (vs->x509cacrl) {
1471
        if ((ret = gnutls_certificate_set_x509_crl_file(x509_cred,
1472
                                                        vs->x509cacrl,
1473
                                                        GNUTLS_X509_FMT_PEM)) < 0) {
1474
            VNC_DEBUG("Cannot load CRL %s\n", gnutls_strerror(ret));
1475
            gnutls_certificate_free_credentials(x509_cred);
1476
            return NULL;
1477
        }
1478
    }
1479

    
1480
    gnutls_certificate_set_dh_params (x509_cred, dh_params);
1481

    
1482
    return x509_cred;
1483
}
1484

    
1485
static int vnc_validate_certificate(struct VncState *vs)
1486
{
1487
    int ret;
1488
    unsigned int status;
1489
    const gnutls_datum_t *certs;
1490
    unsigned int nCerts, i;
1491
    time_t now;
1492

    
1493
    VNC_DEBUG("Validating client certificate\n");
1494
    if ((ret = gnutls_certificate_verify_peers2 (vs->tls_session, &status)) < 0) {
1495
        VNC_DEBUG("Verify failed %s\n", gnutls_strerror(ret));
1496
        return -1;
1497
    }
1498

    
1499
    if ((now = time(NULL)) == ((time_t)-1)) {
1500
        return -1;
1501
    }
1502

    
1503
    if (status != 0) {
1504
        if (status & GNUTLS_CERT_INVALID)
1505
            VNC_DEBUG("The certificate is not trusted.\n");
1506

    
1507
        if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
1508
            VNC_DEBUG("The certificate hasn't got a known issuer.\n");
1509

    
1510
        if (status & GNUTLS_CERT_REVOKED)
1511
            VNC_DEBUG("The certificate has been revoked.\n");
1512

    
1513
        if (status & GNUTLS_CERT_INSECURE_ALGORITHM)
1514
            VNC_DEBUG("The certificate uses an insecure algorithm\n");
1515

    
1516
        return -1;
1517
    } else {
1518
        VNC_DEBUG("Certificate is valid!\n");
1519
    }
1520

    
1521
    /* Only support x509 for now */
1522
    if (gnutls_certificate_type_get(vs->tls_session) != GNUTLS_CRT_X509)
1523
        return -1;
1524

    
1525
    if (!(certs = gnutls_certificate_get_peers(vs->tls_session, &nCerts)))
1526
        return -1;
1527

    
1528
    for (i = 0 ; i < nCerts ; i++) {
1529
        gnutls_x509_crt_t cert;
1530
        VNC_DEBUG ("Checking certificate chain %d\n", i);
1531
        if (gnutls_x509_crt_init (&cert) < 0)
1532
            return -1;
1533

    
1534
        if (gnutls_x509_crt_import(cert, &certs[i], GNUTLS_X509_FMT_DER) < 0) {
1535
            gnutls_x509_crt_deinit (cert);
1536
            return -1;
1537
        }
1538

    
1539
        if (gnutls_x509_crt_get_expiration_time (cert) < now) {
1540
            VNC_DEBUG("The certificate has expired\n");
1541
            gnutls_x509_crt_deinit (cert);
1542
            return -1;
1543
        }
1544

    
1545
        if (gnutls_x509_crt_get_activation_time (cert) > now) {
1546
            VNC_DEBUG("The certificate is not yet activated\n");
1547
            gnutls_x509_crt_deinit (cert);
1548
            return -1;
1549
        }
1550

    
1551
        if (gnutls_x509_crt_get_activation_time (cert) > now) {
1552
            VNC_DEBUG("The certificate is not yet activated\n");
1553
            gnutls_x509_crt_deinit (cert);
1554
            return -1;
1555
        }
1556

    
1557
        gnutls_x509_crt_deinit (cert);
1558
    }
1559

    
1560
    return 0;
1561
}
1562

    
1563

    
1564
static int start_auth_vencrypt_subauth(VncState *vs)
1565
{
1566
    switch (vs->subauth) {
1567
    case VNC_AUTH_VENCRYPT_TLSNONE:
1568
    case VNC_AUTH_VENCRYPT_X509NONE:
1569
       VNC_DEBUG("Accept TLS auth none\n");
1570
       vnc_write_u32(vs, 0); /* Accept auth completion */
1571
       vnc_read_when(vs, protocol_client_init, 1);
1572
       break;
1573

    
1574
    case VNC_AUTH_VENCRYPT_TLSVNC:
1575
    case VNC_AUTH_VENCRYPT_X509VNC:
1576
       VNC_DEBUG("Start TLS auth VNC\n");
1577
       return start_auth_vnc(vs);
1578

    
1579
    default: /* Should not be possible, but just in case */
1580
       VNC_DEBUG("Reject auth %d\n", vs->auth);
1581
       vnc_write_u8(vs, 1);
1582
       if (vs->minor >= 8) {
1583
           static const char err[] = "Unsupported authentication type";
1584
           vnc_write_u32(vs, sizeof(err));
1585
           vnc_write(vs, err, sizeof(err));
1586
       }
1587
       vnc_client_error(vs);
1588
    }
1589

    
1590
    return 0;
1591
}
1592

    
1593
static void vnc_handshake_io(void *opaque);
1594

    
1595
static int vnc_continue_handshake(struct VncState *vs) {
1596
    int ret;
1597

    
1598
    if ((ret = gnutls_handshake(vs->tls_session)) < 0) {
1599
       if (!gnutls_error_is_fatal(ret)) {
1600
           VNC_DEBUG("Handshake interrupted (blocking)\n");
1601
           if (!gnutls_record_get_direction(vs->tls_session))
1602
               qemu_set_fd_handler(vs->csock, vnc_handshake_io, NULL, vs);
1603
           else
1604
               qemu_set_fd_handler(vs->csock, NULL, vnc_handshake_io, vs);
1605
           return 0;
1606
       }
1607
       VNC_DEBUG("Handshake failed %s\n", gnutls_strerror(ret));
1608
       vnc_client_error(vs);
1609
       return -1;
1610
    }
1611

    
1612
    if (vs->x509verify) {
1613
        if (vnc_validate_certificate(vs) < 0) {
1614
            VNC_DEBUG("Client verification failed\n");
1615
            vnc_client_error(vs);
1616
            return -1;
1617
        } else {
1618
            VNC_DEBUG("Client verification passed\n");
1619
        }
1620
    }
1621

    
1622
    VNC_DEBUG("Handshake done, switching to TLS data mode\n");
1623
    vs->wiremode = VNC_WIREMODE_TLS;
1624
    qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
1625

    
1626
    return start_auth_vencrypt_subauth(vs);
1627
}
1628

    
1629
static void vnc_handshake_io(void *opaque) {
1630
    struct VncState *vs = (struct VncState *)opaque;
1631

    
1632
    VNC_DEBUG("Handshake IO continue\n");
1633
    vnc_continue_handshake(vs);
1634
}
1635

    
1636
#define NEED_X509_AUTH(vs)                              \
1637
    ((vs)->subauth == VNC_AUTH_VENCRYPT_X509NONE ||   \
1638
     (vs)->subauth == VNC_AUTH_VENCRYPT_X509VNC ||    \
1639
     (vs)->subauth == VNC_AUTH_VENCRYPT_X509PLAIN)
1640

    
1641

    
1642
static int vnc_start_tls(struct VncState *vs) {
1643
    static const int cert_type_priority[] = { GNUTLS_CRT_X509, 0 };
1644
    static const int protocol_priority[]= { GNUTLS_TLS1_1, GNUTLS_TLS1_0, GNUTLS_SSL3, 0 };
1645
    static const int kx_anon[] = {GNUTLS_KX_ANON_DH, 0};
1646
    static const int kx_x509[] = {GNUTLS_KX_DHE_DSS, GNUTLS_KX_RSA, GNUTLS_KX_DHE_RSA, GNUTLS_KX_SRP, 0};
1647

    
1648
    VNC_DEBUG("Do TLS setup\n");
1649
    if (vnc_tls_initialize() < 0) {
1650
        VNC_DEBUG("Failed to init TLS\n");
1651
        vnc_client_error(vs);
1652
        return -1;
1653
    }
1654
    if (vs->tls_session == NULL) {
1655
        if (gnutls_init(&vs->tls_session, GNUTLS_SERVER) < 0) {
1656
            vnc_client_error(vs);
1657
            return -1;
1658
        }
1659

    
1660
        if (gnutls_set_default_priority(vs->tls_session) < 0) {
1661
            gnutls_deinit(vs->tls_session);
1662
            vs->tls_session = NULL;
1663
            vnc_client_error(vs);
1664
            return -1;
1665
        }
1666

    
1667
        if (gnutls_kx_set_priority(vs->tls_session, NEED_X509_AUTH(vs) ? kx_x509 : kx_anon) < 0) {
1668
            gnutls_deinit(vs->tls_session);
1669
            vs->tls_session = NULL;
1670
            vnc_client_error(vs);
1671
            return -1;
1672
        }
1673

    
1674
        if (gnutls_certificate_type_set_priority(vs->tls_session, cert_type_priority) < 0) {
1675
            gnutls_deinit(vs->tls_session);
1676
            vs->tls_session = NULL;
1677
            vnc_client_error(vs);
1678
            return -1;
1679
        }
1680

    
1681
        if (gnutls_protocol_set_priority(vs->tls_session, protocol_priority) < 0) {
1682
            gnutls_deinit(vs->tls_session);
1683
            vs->tls_session = NULL;
1684
            vnc_client_error(vs);
1685
            return -1;
1686
        }
1687

    
1688
        if (NEED_X509_AUTH(vs)) {
1689
            gnutls_certificate_server_credentials x509_cred = vnc_tls_initialize_x509_cred(vs);
1690
            if (!x509_cred) {
1691
                gnutls_deinit(vs->tls_session);
1692
                vs->tls_session = NULL;
1693
                vnc_client_error(vs);
1694
                return -1;
1695
            }
1696
            if (gnutls_credentials_set(vs->tls_session, GNUTLS_CRD_CERTIFICATE, x509_cred) < 0) {
1697
                gnutls_deinit(vs->tls_session);
1698
                vs->tls_session = NULL;
1699
                gnutls_certificate_free_credentials(x509_cred);
1700
                vnc_client_error(vs);
1701
                return -1;
1702
            }
1703
            if (vs->x509verify) {
1704
                VNC_DEBUG("Requesting a client certificate\n");
1705
                gnutls_certificate_server_set_request (vs->tls_session, GNUTLS_CERT_REQUEST);
1706
            }
1707

    
1708
        } else {
1709
            gnutls_anon_server_credentials anon_cred = vnc_tls_initialize_anon_cred();
1710
            if (!anon_cred) {
1711
                gnutls_deinit(vs->tls_session);
1712
                vs->tls_session = NULL;
1713
                vnc_client_error(vs);
1714
                return -1;
1715
            }
1716
            if (gnutls_credentials_set(vs->tls_session, GNUTLS_CRD_ANON, anon_cred) < 0) {
1717
                gnutls_deinit(vs->tls_session);
1718
                vs->tls_session = NULL;
1719
                gnutls_anon_free_server_credentials(anon_cred);
1720
                vnc_client_error(vs);
1721
                return -1;
1722
            }
1723
        }
1724

    
1725
        gnutls_transport_set_ptr(vs->tls_session, (gnutls_transport_ptr_t)vs);
1726
        gnutls_transport_set_push_function(vs->tls_session, vnc_tls_push);
1727
        gnutls_transport_set_pull_function(vs->tls_session, vnc_tls_pull);
1728
    }
1729

    
1730
    VNC_DEBUG("Start TLS handshake process\n");
1731
    return vnc_continue_handshake(vs);
1732
}
1733

    
1734
static int protocol_client_vencrypt_auth(VncState *vs, char *data, size_t len)
1735
{
1736
    int auth = read_u32(data, 0);
1737

    
1738
    if (auth != vs->subauth) {
1739
        VNC_DEBUG("Rejecting auth %d\n", auth);
1740
        vnc_write_u8(vs, 0); /* Reject auth */
1741
        vnc_flush(vs);
1742
        vnc_client_error(vs);
1743
    } else {
1744
        VNC_DEBUG("Accepting auth %d, starting handshake\n", auth);
1745
        vnc_write_u8(vs, 1); /* Accept auth */
1746
        vnc_flush(vs);
1747

    
1748
        if (vnc_start_tls(vs) < 0) {
1749
            VNC_DEBUG("Failed to complete TLS\n");
1750
            return 0;
1751
        }
1752

    
1753
        if (vs->wiremode == VNC_WIREMODE_TLS) {
1754
            VNC_DEBUG("Starting VeNCrypt subauth\n");
1755
            return start_auth_vencrypt_subauth(vs);
1756
        } else {
1757
            VNC_DEBUG("TLS handshake blocked\n");
1758
            return 0;
1759
        }
1760
    }
1761
    return 0;
1762
}
1763

    
1764
static int protocol_client_vencrypt_init(VncState *vs, char *data, size_t len)
1765
{
1766
    if (data[0] != 0 ||
1767
        data[1] != 2) {
1768
        VNC_DEBUG("Unsupported VeNCrypt protocol %d.%d\n", (int)data[0], (int)data[1]);
1769
        vnc_write_u8(vs, 1); /* Reject version */
1770
        vnc_flush(vs);
1771
        vnc_client_error(vs);
1772
    } else {
1773
        VNC_DEBUG("Sending allowed auth %d\n", vs->subauth);
1774
        vnc_write_u8(vs, 0); /* Accept version */
1775
        vnc_write_u8(vs, 1); /* Number of sub-auths */
1776
        vnc_write_u32(vs, vs->subauth); /* The supported auth */
1777
        vnc_flush(vs);
1778
        vnc_read_when(vs, protocol_client_vencrypt_auth, 4);
1779
    }
1780
    return 0;
1781
}
1782

    
1783
static int start_auth_vencrypt(VncState *vs)
1784
{
1785
    /* Send VeNCrypt version 0.2 */
1786
    vnc_write_u8(vs, 0);
1787
    vnc_write_u8(vs, 2);
1788

    
1789
    vnc_read_when(vs, protocol_client_vencrypt_init, 2);
1790
    return 0;
1791
}
1792
#endif /* CONFIG_VNC_TLS */
1793

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

    
1819
       case VNC_AUTH_VNC:
1820
           VNC_DEBUG("Start VNC auth\n");
1821
           return start_auth_vnc(vs);
1822

    
1823
#if CONFIG_VNC_TLS
1824
       case VNC_AUTH_VENCRYPT:
1825
           VNC_DEBUG("Accept VeNCrypt auth\n");;
1826
           return start_auth_vencrypt(vs);
1827
#endif /* CONFIG_VNC_TLS */
1828

    
1829
       default: /* Should not be possible, but just in case */
1830
           VNC_DEBUG("Reject auth %d\n", vs->auth);
1831
           vnc_write_u8(vs, 1);
1832
           if (vs->minor >= 8) {
1833
               static const char err[] = "Authentication failed";
1834
               vnc_write_u32(vs, sizeof(err));
1835
               vnc_write(vs, err, sizeof(err));
1836
           }
1837
           vnc_client_error(vs);
1838
       }
1839
    }
1840
    return 0;
1841
}
1842

    
1843
static int protocol_version(VncState *vs, char *version, size_t len)
1844
{
1845
    char local[13];
1846

    
1847
    memcpy(local, version, 12);
1848
    local[12] = 0;
1849

    
1850
    if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
1851
        VNC_DEBUG("Malformed protocol version %s\n", local);
1852
        vnc_client_error(vs);
1853
        return 0;
1854
    }
1855
    VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
1856
    if (vs->major != 3 ||
1857
        (vs->minor != 3 &&
1858
         vs->minor != 4 &&
1859
         vs->minor != 5 &&
1860
         vs->minor != 7 &&
1861
         vs->minor != 8)) {
1862
        VNC_DEBUG("Unsupported client version\n");
1863
        vnc_write_u32(vs, VNC_AUTH_INVALID);
1864
        vnc_flush(vs);
1865
        vnc_client_error(vs);
1866
        return 0;
1867
    }
1868
    /* Some broken clients report v3.4 or v3.5, which spec requires to be treated
1869
     * as equivalent to v3.3 by servers
1870
     */
1871
    if (vs->minor == 4 || vs->minor == 5)
1872
        vs->minor = 3;
1873

    
1874
    if (vs->minor == 3) {
1875
        if (vs->auth == VNC_AUTH_NONE) {
1876
            VNC_DEBUG("Tell client auth none\n");
1877
            vnc_write_u32(vs, vs->auth);
1878
            vnc_flush(vs);
1879
            vnc_read_when(vs, protocol_client_init, 1);
1880
       } else if (vs->auth == VNC_AUTH_VNC) {
1881
            VNC_DEBUG("Tell client VNC auth\n");
1882
            vnc_write_u32(vs, vs->auth);
1883
            vnc_flush(vs);
1884
            start_auth_vnc(vs);
1885
       } else {
1886
            VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->auth);
1887
            vnc_write_u32(vs, VNC_AUTH_INVALID);
1888
            vnc_flush(vs);
1889
            vnc_client_error(vs);
1890
       }
1891
    } else {
1892
        VNC_DEBUG("Telling client we support auth %d\n", vs->auth);
1893
        vnc_write_u8(vs, 1); /* num auth */
1894
        vnc_write_u8(vs, vs->auth);
1895
        vnc_read_when(vs, protocol_client_auth, 1);
1896
        vnc_flush(vs);
1897
    }
1898

    
1899
    return 0;
1900
}
1901

    
1902
static void vnc_listen_read(void *opaque)
1903
{
1904
    VncState *vs = opaque;
1905
    struct sockaddr_in addr;
1906
    socklen_t addrlen = sizeof(addr);
1907

    
1908
    vs->csock = accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
1909
    if (vs->csock != -1) {
1910
        VNC_DEBUG("New client on socket %d\n", vs->csock);
1911
        socket_set_nonblock(vs->csock);
1912
        qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, opaque);
1913
        vnc_write(vs, "RFB 003.008\n", 12);
1914
        vnc_flush(vs);
1915
        vnc_read_when(vs, protocol_version, 12);
1916
        memset(vs->old_data, 0, vs->ds->linesize * vs->ds->height);
1917
        memset(vs->dirty_row, 0xFF, sizeof(vs->dirty_row));
1918
        vs->has_resize = 0;
1919
        vs->has_hextile = 0;
1920
        vs->ds->dpy_copy = NULL;
1921
    }
1922
}
1923

    
1924
extern int parse_host_port(struct sockaddr_in *saddr, const char *str);
1925

    
1926
void vnc_display_init(DisplayState *ds)
1927
{
1928
    VncState *vs;
1929

    
1930
    vs = qemu_mallocz(sizeof(VncState));
1931
    if (!vs)
1932
        exit(1);
1933

    
1934
    ds->opaque = vs;
1935
    vnc_state = vs;
1936
    vs->display = NULL;
1937
    vs->password = NULL;
1938

    
1939
    vs->lsock = -1;
1940
    vs->csock = -1;
1941
    vs->depth = 4;
1942
    vs->last_x = -1;
1943
    vs->last_y = -1;
1944

    
1945
    vs->ds = ds;
1946

    
1947
    if (!keyboard_layout)
1948
        keyboard_layout = "en-us";
1949

    
1950
    vs->kbd_layout = init_keyboard_layout(keyboard_layout);
1951
    if (!vs->kbd_layout)
1952
        exit(1);
1953

    
1954
    vs->ds->data = NULL;
1955
    vs->ds->dpy_update = vnc_dpy_update;
1956
    vs->ds->dpy_resize = vnc_dpy_resize;
1957
    vs->ds->dpy_refresh = vnc_dpy_refresh;
1958

    
1959
    memset(vs->dirty_row, 0xFF, sizeof(vs->dirty_row));
1960

    
1961
    vnc_dpy_resize(vs->ds, 640, 400);
1962
}
1963

    
1964
#if CONFIG_VNC_TLS
1965
static int vnc_set_x509_credential(VncState *vs,
1966
                                   const char *certdir,
1967
                                   const char *filename,
1968
                                   char **cred,
1969
                                   int ignoreMissing)
1970
{
1971
    struct stat sb;
1972

    
1973
    if (*cred) {
1974
        qemu_free(*cred);
1975
        *cred = NULL;
1976
    }
1977

    
1978
    if (!(*cred = qemu_malloc(strlen(certdir) + strlen(filename) + 2)))
1979
        return -1;
1980

    
1981
    strcpy(*cred, certdir);
1982
    strcat(*cred, "/");
1983
    strcat(*cred, filename);
1984

    
1985
    VNC_DEBUG("Check %s\n", *cred);
1986
    if (stat(*cred, &sb) < 0) {
1987
        qemu_free(*cred);
1988
        *cred = NULL;
1989
        if (ignoreMissing && errno == ENOENT)
1990
            return 0;
1991
        return -1;
1992
    }
1993

    
1994
    return 0;
1995
}
1996

    
1997
static int vnc_set_x509_credential_dir(VncState *vs,
1998
                                       const char *certdir)
1999
{
2000
    if (vnc_set_x509_credential(vs, certdir, X509_CA_CERT_FILE, &vs->x509cacert, 0) < 0)
2001
        goto cleanup;
2002
    if (vnc_set_x509_credential(vs, certdir, X509_CA_CRL_FILE, &vs->x509cacrl, 1) < 0)
2003
        goto cleanup;
2004
    if (vnc_set_x509_credential(vs, certdir, X509_SERVER_CERT_FILE, &vs->x509cert, 0) < 0)
2005
        goto cleanup;
2006
    if (vnc_set_x509_credential(vs, certdir, X509_SERVER_KEY_FILE, &vs->x509key, 0) < 0)
2007
        goto cleanup;
2008

    
2009
    return 0;
2010

    
2011
 cleanup:
2012
    qemu_free(vs->x509cacert);
2013
    qemu_free(vs->x509cacrl);
2014
    qemu_free(vs->x509cert);
2015
    qemu_free(vs->x509key);
2016
    vs->x509cacert = vs->x509cacrl = vs->x509cert = vs->x509key = NULL;
2017
    return -1;
2018
}
2019
#endif /* CONFIG_VNC_TLS */
2020

    
2021
void vnc_display_close(DisplayState *ds)
2022
{
2023
    VncState *vs = ds ? (VncState *)ds->opaque : vnc_state;
2024

    
2025
    if (vs->display) {
2026
        qemu_free(vs->display);
2027
        vs->display = NULL;
2028
    }
2029
    if (vs->lsock != -1) {
2030
        qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);
2031
        close(vs->lsock);
2032
        vs->lsock = -1;
2033
    }
2034
    if (vs->csock != -1) {
2035
        qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
2036
        closesocket(vs->csock);
2037
        vs->csock = -1;
2038
        buffer_reset(&vs->input);
2039
        buffer_reset(&vs->output);
2040
        vs->need_update = 0;
2041
#if CONFIG_VNC_TLS
2042
        if (vs->tls_session) {
2043
            gnutls_deinit(vs->tls_session);
2044
            vs->tls_session = NULL;
2045
        }
2046
        vs->wiremode = VNC_WIREMODE_CLEAR;
2047
#endif /* CONFIG_VNC_TLS */
2048
    }
2049
    vs->auth = VNC_AUTH_INVALID;
2050
#if CONFIG_VNC_TLS
2051
    vs->subauth = VNC_AUTH_INVALID;
2052
    vs->x509verify = 0;
2053
#endif
2054
}
2055

    
2056
int vnc_display_password(DisplayState *ds, const char *password)
2057
{
2058
    VncState *vs = ds ? (VncState *)ds->opaque : vnc_state;
2059

    
2060
    if (vs->password) {
2061
        qemu_free(vs->password);
2062
        vs->password = NULL;
2063
    }
2064
    if (password && password[0]) {
2065
        if (!(vs->password = qemu_strdup(password)))
2066
            return -1;
2067
    }
2068

    
2069
    return 0;
2070
}
2071

    
2072
int vnc_display_open(DisplayState *ds, const char *display)
2073
{
2074
    struct sockaddr *addr;
2075
    struct sockaddr_in iaddr;
2076
#ifndef _WIN32
2077
    struct sockaddr_un uaddr;
2078
#endif
2079
    int reuse_addr, ret;
2080
    socklen_t addrlen;
2081
    const char *p;
2082
    VncState *vs = ds ? (VncState *)ds->opaque : vnc_state;
2083
    const char *options;
2084
    int password = 0;
2085
#if CONFIG_VNC_TLS
2086
    int tls = 0, x509 = 0;
2087
#endif
2088

    
2089
    vnc_display_close(ds);
2090
    if (strcmp(display, "none") == 0)
2091
        return 0;
2092

    
2093
    if (!(vs->display = strdup(display)))
2094
        return -1;
2095

    
2096
    options = display;
2097
    while ((options = strchr(options, ','))) {
2098
        options++;
2099
        if (strncmp(options, "password", 8) == 0) {
2100
            password = 1; /* Require password auth */
2101
#if CONFIG_VNC_TLS
2102
        } else if (strncmp(options, "tls", 3) == 0) {
2103
            tls = 1; /* Require TLS */
2104
        } else if (strncmp(options, "x509", 4) == 0) {
2105
            char *start, *end;
2106
            x509 = 1; /* Require x509 certificates */
2107
            if (strncmp(options, "x509verify", 10) == 0)
2108
                vs->x509verify = 1; /* ...and verify client certs */
2109

    
2110
            /* Now check for 'x509=/some/path' postfix
2111
             * and use that to setup x509 certificate/key paths */
2112
            start = strchr(options, '=');
2113
            end = strchr(options, ',');
2114
            if (start && (!end || (start < end))) {
2115
                int len = end ? end-(start+1) : strlen(start+1);
2116
                char *path = qemu_malloc(len+1);
2117
                strncpy(path, start+1, len);
2118
                path[len] = '\0';
2119
                VNC_DEBUG("Trying certificate path '%s'\n", path);
2120
                if (vnc_set_x509_credential_dir(vs, path) < 0) {
2121
                    fprintf(stderr, "Failed to find x509 certificates/keys in %s\n", path);
2122
                    qemu_free(path);
2123
                    qemu_free(vs->display);
2124
                    vs->display = NULL;
2125
                    return -1;
2126
                }
2127
                qemu_free(path);
2128
            } else {
2129
                fprintf(stderr, "No certificate path provided\n");
2130
                qemu_free(vs->display);
2131
                vs->display = NULL;
2132
                return -1;
2133
            }
2134
#endif
2135
        }
2136
    }
2137

    
2138
    if (password) {
2139
#if CONFIG_VNC_TLS
2140
        if (tls) {
2141
            vs->auth = VNC_AUTH_VENCRYPT;
2142
            if (x509) {
2143
                VNC_DEBUG("Initializing VNC server with x509 password auth\n");
2144
                vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;
2145
            } else {
2146
                VNC_DEBUG("Initializing VNC server with TLS password auth\n");
2147
                vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
2148
            }
2149
        } else {
2150
#endif
2151
            VNC_DEBUG("Initializing VNC server with password auth\n");
2152
            vs->auth = VNC_AUTH_VNC;
2153
#if CONFIG_VNC_TLS
2154
            vs->subauth = VNC_AUTH_INVALID;
2155
        }
2156
#endif
2157
    } else {
2158
#if CONFIG_VNC_TLS
2159
        if (tls) {
2160
            vs->auth = VNC_AUTH_VENCRYPT;
2161
            if (x509) {
2162
                VNC_DEBUG("Initializing VNC server with x509 no auth\n");
2163
                vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;
2164
            } else {
2165
                VNC_DEBUG("Initializing VNC server with TLS no auth\n");
2166
                vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
2167
            }
2168
        } else {
2169
#endif
2170
            VNC_DEBUG("Initializing VNC server with no auth\n");
2171
            vs->auth = VNC_AUTH_NONE;
2172
#if CONFIG_VNC_TLS
2173
            vs->subauth = VNC_AUTH_INVALID;
2174
        }
2175
#endif
2176
    }
2177
#ifndef _WIN32
2178
    if (strstart(display, "unix:", &p)) {
2179
        addr = (struct sockaddr *)&uaddr;
2180
        addrlen = sizeof(uaddr);
2181

    
2182
        vs->lsock = socket(PF_UNIX, SOCK_STREAM, 0);
2183
        if (vs->lsock == -1) {
2184
            fprintf(stderr, "Could not create socket\n");
2185
            free(vs->display);
2186
            vs->display = NULL;
2187
            return -1;
2188
        }
2189

    
2190
        uaddr.sun_family = AF_UNIX;
2191
        memset(uaddr.sun_path, 0, 108);
2192
        snprintf(uaddr.sun_path, 108, "%s", p);
2193

    
2194
        unlink(uaddr.sun_path);
2195
    } else
2196
#endif
2197
    {
2198
        addr = (struct sockaddr *)&iaddr;
2199
        addrlen = sizeof(iaddr);
2200

    
2201
        if (parse_host_port(&iaddr, display) < 0) {
2202
            fprintf(stderr, "Could not parse VNC address\n");
2203
            free(vs->display);
2204
            vs->display = NULL;
2205
            return -1;
2206
        }
2207

    
2208
        iaddr.sin_port = htons(ntohs(iaddr.sin_port) + 5900);
2209

    
2210
        vs->lsock = socket(PF_INET, 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
        reuse_addr = 1;
2219
        ret = setsockopt(vs->lsock, SOL_SOCKET, SO_REUSEADDR,
2220
                         (const char *)&reuse_addr, sizeof(reuse_addr));
2221
        if (ret == -1) {
2222
            fprintf(stderr, "setsockopt() failed\n");
2223
            close(vs->lsock);
2224
            vs->lsock = -1;
2225
            free(vs->display);
2226
            vs->display = NULL;
2227
            return -1;
2228
        }
2229
    }
2230

    
2231
    if (bind(vs->lsock, addr, addrlen) == -1) {
2232
        fprintf(stderr, "bind() failed\n");
2233
        close(vs->lsock);
2234
        vs->lsock = -1;
2235
        free(vs->display);
2236
        vs->display = NULL;
2237
        return -1;
2238
    }
2239

    
2240
    if (listen(vs->lsock, 1) == -1) {
2241
        fprintf(stderr, "listen() failed\n");
2242
        close(vs->lsock);
2243
        vs->lsock = -1;
2244
        free(vs->display);
2245
        vs->display = NULL;
2246
        return -1;
2247
    }
2248

    
2249
    return qemu_set_fd_handler2(vs->lsock, vnc_listen_poll, vnc_listen_read, NULL, vs);
2250
}