VNC password authentication, by Daniel P. Berrange.
[qemu] / vnc.c
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 "vl.h"
27 #include "qemu_socket.h"
28
29 #define VNC_REFRESH_INTERVAL (1000 / 30)
30
31 #include "vnc_keysym.h"
32 #include "keymaps.c"
33 #include "d3des.h"
34
35 // #define _VNC_DEBUG
36
37 #ifdef _VNC_DEBUG
38 #define VNC_DEBUG(fmt, ...) do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
39 #else
40 #define VNC_DEBUG(fmt, ...) do { } while (0)
41 #endif
42
43 typedef struct Buffer
44 {
45     size_t capacity;
46     size_t offset;
47     char *buffer;
48 } Buffer;
49
50 typedef struct VncState VncState;
51
52 typedef int VncReadEvent(VncState *vs, char *data, size_t len);
53
54 typedef void VncWritePixels(VncState *vs, void *data, int size);
55
56 typedef void VncSendHextileTile(VncState *vs,
57                                 int x, int y, int w, int h,
58                                 uint32_t *last_bg, 
59                                 uint32_t *last_fg,
60                                 int *has_bg, int *has_fg);
61
62 #define VNC_MAX_WIDTH 2048
63 #define VNC_MAX_HEIGHT 2048
64 #define VNC_DIRTY_WORDS (VNC_MAX_WIDTH / (16 * 32))
65
66 #define VNC_AUTH_CHALLENGE_SIZE 16
67
68 enum {
69     VNC_AUTH_INVALID = 0,
70     VNC_AUTH_NONE = 1,
71     VNC_AUTH_VNC = 2,
72     VNC_AUTH_RA2 = 5,
73     VNC_AUTH_RA2NE = 6,
74     VNC_AUTH_TIGHT = 16,
75     VNC_AUTH_ULTRA = 17,
76     VNC_AUTH_TLS = 18,
77     VNC_AUTH_VENCRYPT = 19
78 };
79
80 struct VncState
81 {
82     QEMUTimer *timer;
83     int lsock;
84     int csock;
85     DisplayState *ds;
86     int need_update;
87     int width;
88     int height;
89     uint32_t dirty_row[VNC_MAX_HEIGHT][VNC_DIRTY_WORDS];
90     char *old_data;
91     int depth; /* internal VNC frame buffer byte per pixel */
92     int has_resize;
93     int has_hextile;
94     int has_pointer_type_change;
95     int absolute;
96     int last_x;
97     int last_y;
98
99     int major;
100     int minor;
101
102     char *display;
103     char *password;
104     int auth;
105     char challenge[VNC_AUTH_CHALLENGE_SIZE];
106
107     Buffer output;
108     Buffer input;
109     kbd_layout_t *kbd_layout;
110     /* current output mode information */
111     VncWritePixels *write_pixels;
112     VncSendHextileTile *send_hextile_tile;
113     int pix_bpp, pix_big_endian;
114     int red_shift, red_max, red_shift1;
115     int green_shift, green_max, green_shift1;
116     int blue_shift, blue_max, blue_shift1;
117
118     VncReadEvent *read_handler;
119     size_t read_handler_expect;
120     /* input */
121     uint8_t modifiers_state[256];
122 };
123
124 static VncState *vnc_state; /* needed for info vnc */
125
126 void do_info_vnc(void)
127 {
128     if (vnc_state == NULL)
129         term_printf("VNC server disabled\n");
130     else {
131         term_printf("VNC server active on: ");
132         term_print_filename(vnc_state->display);
133         term_printf("\n");
134
135         if (vnc_state->csock == -1)
136             term_printf("No client connected\n");
137         else
138             term_printf("Client connected\n");
139     }
140 }
141
142 /* TODO
143    1) Get the queue working for IO.
144    2) there is some weirdness when using the -S option (the screen is grey
145       and not totally invalidated
146    3) resolutions > 1024
147 */
148
149 static void vnc_write(VncState *vs, const void *data, size_t len);
150 static void vnc_write_u32(VncState *vs, uint32_t value);
151 static void vnc_write_s32(VncState *vs, int32_t value);
152 static void vnc_write_u16(VncState *vs, uint16_t value);
153 static void vnc_write_u8(VncState *vs, uint8_t value);
154 static void vnc_flush(VncState *vs);
155 static void vnc_update_client(void *opaque);
156 static void vnc_client_read(void *opaque);
157
158 static inline void vnc_set_bit(uint32_t *d, int k)
159 {
160     d[k >> 5] |= 1 << (k & 0x1f);
161 }
162
163 static inline void vnc_clear_bit(uint32_t *d, int k)
164 {
165     d[k >> 5] &= ~(1 << (k & 0x1f));
166 }
167
168 static inline void vnc_set_bits(uint32_t *d, int n, int nb_words)
169 {
170     int j;
171
172     j = 0;
173     while (n >= 32) {
174         d[j++] = -1;
175         n -= 32;
176     }
177     if (n > 0) 
178         d[j++] = (1 << n) - 1;
179     while (j < nb_words)
180         d[j++] = 0;
181 }
182
183 static inline int vnc_get_bit(const uint32_t *d, int k)
184 {
185     return (d[k >> 5] >> (k & 0x1f)) & 1;
186 }
187
188 static inline int vnc_and_bits(const uint32_t *d1, const uint32_t *d2, 
189                                int nb_words)
190 {
191     int i;
192     for(i = 0; i < nb_words; i++) {
193         if ((d1[i] & d2[i]) != 0)
194             return 1;
195     }
196     return 0;
197 }
198
199 static void vnc_dpy_update(DisplayState *ds, int x, int y, int w, int h)
200 {
201     VncState *vs = ds->opaque;
202     int i;
203
204     h += y;
205
206     for (; y < h; y++)
207         for (i = 0; i < w; i += 16)
208             vnc_set_bit(vs->dirty_row[y], (x + i) / 16);
209 }
210
211 static void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
212                                    int32_t encoding)
213 {
214     vnc_write_u16(vs, x);
215     vnc_write_u16(vs, y);
216     vnc_write_u16(vs, w);
217     vnc_write_u16(vs, h);
218
219     vnc_write_s32(vs, encoding);
220 }
221
222 static void vnc_dpy_resize(DisplayState *ds, int w, int h)
223 {
224     int size_changed;
225     VncState *vs = ds->opaque;
226
227     ds->data = realloc(ds->data, w * h * vs->depth);
228     vs->old_data = realloc(vs->old_data, w * h * vs->depth);
229
230     if (ds->data == NULL || vs->old_data == NULL) {
231         fprintf(stderr, "vnc: memory allocation failed\n");
232         exit(1);
233     }
234
235     ds->depth = vs->depth * 8;
236     size_changed = ds->width != w || ds->height != h;
237     ds->width = w;
238     ds->height = h;
239     ds->linesize = w * vs->depth;
240     if (vs->csock != -1 && vs->has_resize && size_changed) {
241         vnc_write_u8(vs, 0);  /* msg id */
242         vnc_write_u8(vs, 0);
243         vnc_write_u16(vs, 1); /* number of rects */
244         vnc_framebuffer_update(vs, 0, 0, ds->width, ds->height, -223);
245         vnc_flush(vs);
246         vs->width = ds->width;
247         vs->height = ds->height;
248     }
249 }
250
251 /* fastest code */
252 static void vnc_write_pixels_copy(VncState *vs, void *pixels, int size)
253 {
254     vnc_write(vs, pixels, size);
255 }
256
257 /* slowest but generic code. */
258 static void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
259 {
260     unsigned int r, g, b;
261
262     r = (v >> vs->red_shift1) & vs->red_max;
263     g = (v >> vs->green_shift1) & vs->green_max;
264     b = (v >> vs->blue_shift1) & vs->blue_max;
265     v = (r << vs->red_shift) | 
266         (g << vs->green_shift) | 
267         (b << vs->blue_shift);
268     switch(vs->pix_bpp) {
269     case 1:
270         buf[0] = v;
271         break;
272     case 2:
273         if (vs->pix_big_endian) {
274             buf[0] = v >> 8;
275             buf[1] = v;
276         } else {
277             buf[1] = v >> 8;
278             buf[0] = v;
279         }
280         break;
281     default:
282     case 4:
283         if (vs->pix_big_endian) {
284             buf[0] = v >> 24;
285             buf[1] = v >> 16;
286             buf[2] = v >> 8;
287             buf[3] = v;
288         } else {
289             buf[3] = v >> 24;
290             buf[2] = v >> 16;
291             buf[1] = v >> 8;
292             buf[0] = v;
293         }
294         break;
295     }
296 }
297
298 static void vnc_write_pixels_generic(VncState *vs, void *pixels1, int size)
299 {
300     uint32_t *pixels = pixels1;
301     uint8_t buf[4];
302     int n, i;
303
304     n = size >> 2;
305     for(i = 0; i < n; i++) {
306         vnc_convert_pixel(vs, buf, pixels[i]);
307         vnc_write(vs, buf, vs->pix_bpp);
308     }
309 }
310
311 static void send_framebuffer_update_raw(VncState *vs, int x, int y, int w, int h)
312 {
313     int i;
314     char *row;
315
316     vnc_framebuffer_update(vs, x, y, w, h, 0);
317
318     row = vs->ds->data + y * vs->ds->linesize + x * vs->depth;
319     for (i = 0; i < h; i++) {
320         vs->write_pixels(vs, row, w * vs->depth);
321         row += vs->ds->linesize;
322     }
323 }
324
325 static void hextile_enc_cord(uint8_t *ptr, int x, int y, int w, int h)
326 {
327     ptr[0] = ((x & 0x0F) << 4) | (y & 0x0F);
328     ptr[1] = (((w - 1) & 0x0F) << 4) | ((h - 1) & 0x0F);
329 }
330
331 #define BPP 8
332 #include "vnchextile.h"
333 #undef BPP
334
335 #define BPP 16
336 #include "vnchextile.h"
337 #undef BPP
338
339 #define BPP 32
340 #include "vnchextile.h"
341 #undef BPP
342
343 #define GENERIC
344 #define BPP 32
345 #include "vnchextile.h"
346 #undef BPP
347 #undef GENERIC
348
349 static void send_framebuffer_update_hextile(VncState *vs, int x, int y, int w, int h)
350 {
351     int i, j;
352     int has_fg, has_bg;
353     uint32_t last_fg32, last_bg32;
354
355     vnc_framebuffer_update(vs, x, y, w, h, 5);
356
357     has_fg = has_bg = 0;
358     for (j = y; j < (y + h); j += 16) {
359         for (i = x; i < (x + w); i += 16) {
360             vs->send_hextile_tile(vs, i, j, 
361                                   MIN(16, x + w - i), MIN(16, y + h - j),
362                                   &last_bg32, &last_fg32, &has_bg, &has_fg);
363         }
364     }
365 }
366
367 static void send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
368 {
369         if (vs->has_hextile)
370             send_framebuffer_update_hextile(vs, x, y, w, h);
371         else
372             send_framebuffer_update_raw(vs, x, y, w, h);
373 }
374
375 static void vnc_copy(DisplayState *ds, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
376 {
377     int src, dst;
378     char *src_row;
379     char *dst_row;
380     char *old_row;
381     int y = 0;
382     int pitch = ds->linesize;
383     VncState *vs = ds->opaque;
384
385     vnc_update_client(vs);
386
387     if (dst_y > src_y) {
388         y = h - 1;
389         pitch = -pitch;
390     }
391
392     src = (ds->linesize * (src_y + y) + vs->depth * src_x);
393     dst = (ds->linesize * (dst_y + y) + vs->depth * dst_x);
394
395     src_row = ds->data + src;
396     dst_row = ds->data + dst;
397     old_row = vs->old_data + dst;
398
399     for (y = 0; y < h; y++) {
400         memmove(old_row, src_row, w * vs->depth);
401         memmove(dst_row, src_row, w * vs->depth);
402         src_row += pitch;
403         dst_row += pitch;
404         old_row += pitch;
405     }
406
407     vnc_write_u8(vs, 0);  /* msg id */
408     vnc_write_u8(vs, 0);
409     vnc_write_u16(vs, 1); /* number of rects */
410     vnc_framebuffer_update(vs, dst_x, dst_y, w, h, 1);
411     vnc_write_u16(vs, src_x);
412     vnc_write_u16(vs, src_y);
413     vnc_flush(vs);
414 }
415
416 static int find_dirty_height(VncState *vs, int y, int last_x, int x)
417 {
418     int h;
419
420     for (h = 1; h < (vs->height - y); h++) {
421         int tmp_x;
422         if (!vnc_get_bit(vs->dirty_row[y + h], last_x))
423             break;
424         for (tmp_x = last_x; tmp_x < x; tmp_x++)
425             vnc_clear_bit(vs->dirty_row[y + h], tmp_x);
426     }
427
428     return h;
429 }
430
431 static void vnc_update_client(void *opaque)
432 {
433     VncState *vs = opaque;
434
435     if (vs->need_update && vs->csock != -1) {
436         int y;
437         char *row;
438         char *old_row;
439         uint32_t width_mask[VNC_DIRTY_WORDS];
440         int n_rectangles;
441         int saved_offset;
442         int has_dirty = 0;
443
444         vnc_set_bits(width_mask, (vs->width / 16), VNC_DIRTY_WORDS);
445
446         /* Walk through the dirty map and eliminate tiles that
447            really aren't dirty */
448         row = vs->ds->data;
449         old_row = vs->old_data;
450
451         for (y = 0; y < vs->height; y++) {
452             if (vnc_and_bits(vs->dirty_row[y], width_mask, VNC_DIRTY_WORDS)) {
453                 int x;
454                 char *ptr, *old_ptr;
455
456                 ptr = row;
457                 old_ptr = old_row;
458
459                 for (x = 0; x < vs->ds->width; x += 16) {
460                     if (memcmp(old_ptr, ptr, 16 * vs->depth) == 0) {
461                         vnc_clear_bit(vs->dirty_row[y], (x / 16));
462                     } else {
463                         has_dirty = 1;
464                         memcpy(old_ptr, ptr, 16 * vs->depth);
465                     }
466
467                     ptr += 16 * vs->depth;
468                     old_ptr += 16 * vs->depth;
469                 }
470             }
471
472             row += vs->ds->linesize;
473             old_row += vs->ds->linesize;
474         }
475
476         if (!has_dirty) {
477             qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);
478             return;
479         }
480
481         /* Count rectangles */
482         n_rectangles = 0;
483         vnc_write_u8(vs, 0);  /* msg id */
484         vnc_write_u8(vs, 0);
485         saved_offset = vs->output.offset;
486         vnc_write_u16(vs, 0);
487
488         for (y = 0; y < vs->height; y++) {
489             int x;
490             int last_x = -1;
491             for (x = 0; x < vs->width / 16; x++) {
492                 if (vnc_get_bit(vs->dirty_row[y], x)) {
493                     if (last_x == -1) {
494                         last_x = x;
495                     }
496                     vnc_clear_bit(vs->dirty_row[y], x);
497                 } else {
498                     if (last_x != -1) {
499                         int h = find_dirty_height(vs, y, last_x, x);
500                         send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
501                         n_rectangles++;
502                     }
503                     last_x = -1;
504                 }
505             }
506             if (last_x != -1) {
507                 int h = find_dirty_height(vs, y, last_x, x);
508                 send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
509                 n_rectangles++;
510             }
511         }
512         vs->output.buffer[saved_offset] = (n_rectangles >> 8) & 0xFF;
513         vs->output.buffer[saved_offset + 1] = n_rectangles & 0xFF;
514         vnc_flush(vs);
515
516     }
517     qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);
518 }
519
520 static void vnc_timer_init(VncState *vs)
521 {
522     if (vs->timer == NULL) {
523         vs->timer = qemu_new_timer(rt_clock, vnc_update_client, vs);
524         qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock));
525     }
526 }
527
528 static void vnc_dpy_refresh(DisplayState *ds)
529 {
530     VncState *vs = ds->opaque;
531     vnc_timer_init(vs);
532     vga_hw_update();
533 }
534
535 static int vnc_listen_poll(void *opaque)
536 {
537     VncState *vs = opaque;
538     if (vs->csock == -1)
539         return 1;
540     return 0;
541 }
542
543 static void buffer_reserve(Buffer *buffer, size_t len)
544 {
545     if ((buffer->capacity - buffer->offset) < len) {
546         buffer->capacity += (len + 1024);
547         buffer->buffer = realloc(buffer->buffer, buffer->capacity);
548         if (buffer->buffer == NULL) {
549             fprintf(stderr, "vnc: out of memory\n");
550             exit(1);
551         }
552     }
553 }
554
555 static int buffer_empty(Buffer *buffer)
556 {
557     return buffer->offset == 0;
558 }
559
560 static char *buffer_end(Buffer *buffer)
561 {
562     return buffer->buffer + buffer->offset;
563 }
564
565 static void buffer_reset(Buffer *buffer)
566 {
567         buffer->offset = 0;
568 }
569
570 static void buffer_append(Buffer *buffer, const void *data, size_t len)
571 {
572     memcpy(buffer->buffer + buffer->offset, data, len);
573     buffer->offset += len;
574 }
575
576 static int vnc_client_io_error(VncState *vs, int ret, int last_errno)
577 {
578     if (ret == 0 || ret == -1) {
579         if (ret == -1 && (last_errno == EINTR || last_errno == EAGAIN))
580             return 0;
581
582         qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
583         closesocket(vs->csock);
584         vs->csock = -1;
585         buffer_reset(&vs->input);
586         buffer_reset(&vs->output);
587         vs->need_update = 0;
588         return 0;
589     }
590     return ret;
591 }
592
593 static void vnc_client_error(VncState *vs)
594 {
595     vnc_client_io_error(vs, -1, EINVAL);
596 }
597
598 static void vnc_client_write(void *opaque)
599 {
600     long ret;
601     VncState *vs = opaque;
602
603     ret = send(vs->csock, vs->output.buffer, vs->output.offset, 0);
604     ret = vnc_client_io_error(vs, ret, socket_error());
605     if (!ret)
606         return;
607
608     memmove(vs->output.buffer, vs->output.buffer + ret, (vs->output.offset - ret));
609     vs->output.offset -= ret;
610
611     if (vs->output.offset == 0) {
612         qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
613     }
614 }
615
616 static void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
617 {
618     vs->read_handler = func;
619     vs->read_handler_expect = expecting;
620 }
621
622 static void vnc_client_read(void *opaque)
623 {
624     VncState *vs = opaque;
625     long ret;
626
627     buffer_reserve(&vs->input, 4096);
628
629     ret = recv(vs->csock, buffer_end(&vs->input), 4096, 0);
630     ret = vnc_client_io_error(vs, ret, socket_error());
631     if (!ret)
632         return;
633
634     vs->input.offset += ret;
635
636     while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
637         size_t len = vs->read_handler_expect;
638         int ret;
639
640         ret = vs->read_handler(vs, vs->input.buffer, len);
641         if (vs->csock == -1)
642             return;
643
644         if (!ret) {
645             memmove(vs->input.buffer, vs->input.buffer + len, (vs->input.offset - len));
646             vs->input.offset -= len;
647         } else {
648             vs->read_handler_expect = ret;
649         }
650     }
651 }
652
653 static void vnc_write(VncState *vs, const void *data, size_t len)
654 {
655     buffer_reserve(&vs->output, len);
656
657     if (buffer_empty(&vs->output)) {
658         qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
659     }
660
661     buffer_append(&vs->output, data, len);
662 }
663
664 static void vnc_write_s32(VncState *vs, int32_t value)
665 {
666     vnc_write_u32(vs, *(uint32_t *)&value);
667 }
668
669 static void vnc_write_u32(VncState *vs, uint32_t value)
670 {
671     uint8_t buf[4];
672
673     buf[0] = (value >> 24) & 0xFF;
674     buf[1] = (value >> 16) & 0xFF;
675     buf[2] = (value >>  8) & 0xFF;
676     buf[3] = value & 0xFF;
677
678     vnc_write(vs, buf, 4);
679 }
680
681 static void vnc_write_u16(VncState *vs, uint16_t value)
682 {
683     uint8_t buf[2];
684
685     buf[0] = (value >> 8) & 0xFF;
686     buf[1] = value & 0xFF;
687
688     vnc_write(vs, buf, 2);
689 }
690
691 static void vnc_write_u8(VncState *vs, uint8_t value)
692 {
693     vnc_write(vs, (char *)&value, 1);
694 }
695
696 static void vnc_flush(VncState *vs)
697 {
698     if (vs->output.offset)
699         vnc_client_write(vs);
700 }
701
702 static uint8_t read_u8(uint8_t *data, size_t offset)
703 {
704     return data[offset];
705 }
706
707 static uint16_t read_u16(uint8_t *data, size_t offset)
708 {
709     return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
710 }
711
712 static int32_t read_s32(uint8_t *data, size_t offset)
713 {
714     return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
715                      (data[offset + 2] << 8) | data[offset + 3]);
716 }
717
718 static uint32_t read_u32(uint8_t *data, size_t offset)
719 {
720     return ((data[offset] << 24) | (data[offset + 1] << 16) |
721             (data[offset + 2] << 8) | data[offset + 3]);
722 }
723
724 static void client_cut_text(VncState *vs, size_t len, char *text)
725 {
726 }
727
728 static void check_pointer_type_change(VncState *vs, int absolute)
729 {
730     if (vs->has_pointer_type_change && vs->absolute != absolute) {
731         vnc_write_u8(vs, 0);
732         vnc_write_u8(vs, 0);
733         vnc_write_u16(vs, 1);
734         vnc_framebuffer_update(vs, absolute, 0,
735                                vs->ds->width, vs->ds->height, -257);
736         vnc_flush(vs);
737     }
738     vs->absolute = absolute;
739 }
740
741 static void pointer_event(VncState *vs, int button_mask, int x, int y)
742 {
743     int buttons = 0;
744     int dz = 0;
745
746     if (button_mask & 0x01)
747         buttons |= MOUSE_EVENT_LBUTTON;
748     if (button_mask & 0x02)
749         buttons |= MOUSE_EVENT_MBUTTON;
750     if (button_mask & 0x04)
751         buttons |= MOUSE_EVENT_RBUTTON;
752     if (button_mask & 0x08)
753         dz = -1;
754     if (button_mask & 0x10)
755         dz = 1;
756
757     if (vs->absolute) {
758         kbd_mouse_event(x * 0x7FFF / vs->ds->width,
759                         y * 0x7FFF / vs->ds->height,
760                         dz, buttons);
761     } else if (vs->has_pointer_type_change) {
762         x -= 0x7FFF;
763         y -= 0x7FFF;
764
765         kbd_mouse_event(x, y, dz, buttons);
766     } else {
767         if (vs->last_x != -1)
768             kbd_mouse_event(x - vs->last_x,
769                             y - vs->last_y,
770                             dz, buttons);
771         vs->last_x = x;
772         vs->last_y = y;
773     }
774
775     check_pointer_type_change(vs, kbd_mouse_is_absolute());
776 }
777
778 static void reset_keys(VncState *vs)
779 {
780     int i;
781     for(i = 0; i < 256; i++) {
782         if (vs->modifiers_state[i]) {
783             if (i & 0x80)
784                 kbd_put_keycode(0xe0);
785             kbd_put_keycode(i | 0x80);
786             vs->modifiers_state[i] = 0;
787         }
788     }
789 }
790
791 static void do_key_event(VncState *vs, int down, uint32_t sym)
792 {
793     int keycode;
794
795     keycode = keysym2scancode(vs->kbd_layout, sym & 0xFFFF);
796     
797     /* QEMU console switch */
798     switch(keycode) {
799     case 0x2a:                          /* Left Shift */
800     case 0x36:                          /* Right Shift */
801     case 0x1d:                          /* Left CTRL */
802     case 0x9d:                          /* Right CTRL */
803     case 0x38:                          /* Left ALT */
804     case 0xb8:                          /* Right ALT */
805         if (down)
806             vs->modifiers_state[keycode] = 1;
807         else
808             vs->modifiers_state[keycode] = 0;
809         break;
810     case 0x02 ... 0x0a: /* '1' to '9' keys */ 
811         if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
812             /* Reset the modifiers sent to the current console */
813             reset_keys(vs);
814             console_select(keycode - 0x02);
815             return;
816         }
817         break;
818     }
819
820     if (is_graphic_console()) {
821         if (keycode & 0x80)
822             kbd_put_keycode(0xe0);
823         if (down)
824             kbd_put_keycode(keycode & 0x7f);
825         else
826             kbd_put_keycode(keycode | 0x80);
827     } else {
828         /* QEMU console emulation */
829         if (down) {
830             switch (keycode) {
831             case 0x2a:                          /* Left Shift */
832             case 0x36:                          /* Right Shift */
833             case 0x1d:                          /* Left CTRL */
834             case 0x9d:                          /* Right CTRL */
835             case 0x38:                          /* Left ALT */
836             case 0xb8:                          /* Right ALT */
837                 break;
838             case 0xc8:
839                 kbd_put_keysym(QEMU_KEY_UP);
840                 break;
841             case 0xd0:
842                 kbd_put_keysym(QEMU_KEY_DOWN);
843                 break;
844             case 0xcb:
845                 kbd_put_keysym(QEMU_KEY_LEFT);
846                 break;
847             case 0xcd:
848                 kbd_put_keysym(QEMU_KEY_RIGHT);
849                 break;
850             case 0xd3:
851                 kbd_put_keysym(QEMU_KEY_DELETE);
852                 break;
853             case 0xc7:
854                 kbd_put_keysym(QEMU_KEY_HOME);
855                 break;
856             case 0xcf:
857                 kbd_put_keysym(QEMU_KEY_END);
858                 break;
859             case 0xc9:
860                 kbd_put_keysym(QEMU_KEY_PAGEUP);
861                 break;
862             case 0xd1:
863                 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
864                 break;
865             default:
866                 kbd_put_keysym(sym);
867                 break;
868             }
869         }
870     }
871 }
872
873 static void key_event(VncState *vs, int down, uint32_t sym)
874 {
875     if (sym >= 'A' && sym <= 'Z')
876         sym = sym - 'A' + 'a';
877     do_key_event(vs, down, sym);
878 }
879
880 static void framebuffer_update_request(VncState *vs, int incremental,
881                                        int x_position, int y_position,
882                                        int w, int h)
883 {
884     if (x_position > vs->ds->width)
885         x_position = vs->ds->width;
886     if (y_position > vs->ds->height)
887         y_position = vs->ds->height;
888     if (x_position + w >= vs->ds->width)
889         w = vs->ds->width  - x_position;
890     if (y_position + h >= vs->ds->height)
891         h = vs->ds->height - y_position;
892
893     int i;
894     vs->need_update = 1;
895     if (!incremental) {
896         char *old_row = vs->old_data + y_position * vs->ds->linesize;
897
898         for (i = 0; i < h; i++) {
899             vnc_set_bits(vs->dirty_row[y_position + i], 
900                          (vs->ds->width / 16), VNC_DIRTY_WORDS);
901             memset(old_row, 42, vs->ds->width * vs->depth);
902             old_row += vs->ds->linesize;
903         }
904     }
905 }
906
907 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
908 {
909     int i;
910
911     vs->has_hextile = 0;
912     vs->has_resize = 0;
913     vs->has_pointer_type_change = 0;
914     vs->absolute = -1;
915     vs->ds->dpy_copy = NULL;
916
917     for (i = n_encodings - 1; i >= 0; i--) {
918         switch (encodings[i]) {
919         case 0: /* Raw */
920             vs->has_hextile = 0;
921             break;
922         case 1: /* CopyRect */
923             vs->ds->dpy_copy = vnc_copy;
924             break;
925         case 5: /* Hextile */
926             vs->has_hextile = 1;
927             break;
928         case -223: /* DesktopResize */
929             vs->has_resize = 1;
930             break;
931         case -257:
932             vs->has_pointer_type_change = 1;
933             break;
934         default:
935             break;
936         }
937     }
938
939     check_pointer_type_change(vs, kbd_mouse_is_absolute());
940 }
941
942 static int compute_nbits(unsigned int val)
943 {
944     int n;
945     n = 0;
946     while (val != 0) {
947         n++;
948         val >>= 1;
949     }
950     return n;
951 }
952
953 static void set_pixel_format(VncState *vs,
954                              int bits_per_pixel, int depth,
955                              int big_endian_flag, int true_color_flag,
956                              int red_max, int green_max, int blue_max,
957                              int red_shift, int green_shift, int blue_shift)
958 {
959     int host_big_endian_flag;
960
961 #ifdef WORDS_BIGENDIAN
962     host_big_endian_flag = 1;
963 #else
964     host_big_endian_flag = 0;
965 #endif
966     if (!true_color_flag) {
967     fail:
968         vnc_client_error(vs);
969         return;
970     }
971     if (bits_per_pixel == 32 && 
972         host_big_endian_flag == big_endian_flag &&
973         red_max == 0xff && green_max == 0xff && blue_max == 0xff &&
974         red_shift == 16 && green_shift == 8 && blue_shift == 0) {
975         vs->depth = 4;
976         vs->write_pixels = vnc_write_pixels_copy;
977         vs->send_hextile_tile = send_hextile_tile_32;
978     } else 
979     if (bits_per_pixel == 16 && 
980         host_big_endian_flag == big_endian_flag &&
981         red_max == 31 && green_max == 63 && blue_max == 31 &&
982         red_shift == 11 && green_shift == 5 && blue_shift == 0) {
983         vs->depth = 2;
984         vs->write_pixels = vnc_write_pixels_copy;
985         vs->send_hextile_tile = send_hextile_tile_16;
986     } else 
987     if (bits_per_pixel == 8 && 
988         red_max == 7 && green_max == 7 && blue_max == 3 &&
989         red_shift == 5 && green_shift == 2 && blue_shift == 0) {
990         vs->depth = 1;
991         vs->write_pixels = vnc_write_pixels_copy;
992         vs->send_hextile_tile = send_hextile_tile_8;
993     } else 
994     {
995         /* generic and slower case */
996         if (bits_per_pixel != 8 &&
997             bits_per_pixel != 16 &&
998             bits_per_pixel != 32)
999             goto fail;
1000         vs->depth = 4;
1001         vs->red_shift = red_shift;
1002         vs->red_max = red_max;
1003         vs->red_shift1 = 24 - compute_nbits(red_max);
1004         vs->green_shift = green_shift;
1005         vs->green_max = green_max;
1006         vs->green_shift1 = 16 - compute_nbits(green_max);
1007         vs->blue_shift = blue_shift;
1008         vs->blue_max = blue_max;
1009         vs->blue_shift1 = 8 - compute_nbits(blue_max);
1010         vs->pix_bpp = bits_per_pixel / 8;
1011         vs->pix_big_endian = big_endian_flag;
1012         vs->write_pixels = vnc_write_pixels_generic;
1013         vs->send_hextile_tile = send_hextile_tile_generic;
1014     }
1015
1016     vnc_dpy_resize(vs->ds, vs->ds->width, vs->ds->height);
1017     memset(vs->dirty_row, 0xFF, sizeof(vs->dirty_row));
1018     memset(vs->old_data, 42, vs->ds->linesize * vs->ds->height);
1019
1020     vga_hw_invalidate();
1021     vga_hw_update();
1022 }
1023
1024 static int protocol_client_msg(VncState *vs, char *data, size_t len)
1025 {
1026     int i;
1027     uint16_t limit;
1028
1029     switch (data[0]) {
1030     case 0:
1031         if (len == 1)
1032             return 20;
1033
1034         set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
1035                          read_u8(data, 6), read_u8(data, 7),
1036                          read_u16(data, 8), read_u16(data, 10),
1037                          read_u16(data, 12), read_u8(data, 14),
1038                          read_u8(data, 15), read_u8(data, 16));
1039         break;
1040     case 2:
1041         if (len == 1)
1042             return 4;
1043
1044         if (len == 4)
1045             return 4 + (read_u16(data, 2) * 4);
1046
1047         limit = read_u16(data, 2);
1048         for (i = 0; i < limit; i++) {
1049             int32_t val = read_s32(data, 4 + (i * 4));
1050             memcpy(data + 4 + (i * 4), &val, sizeof(val));
1051         }
1052
1053         set_encodings(vs, (int32_t *)(data + 4), limit);
1054         break;
1055     case 3:
1056         if (len == 1)
1057             return 10;
1058
1059         framebuffer_update_request(vs,
1060                                    read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
1061                                    read_u16(data, 6), read_u16(data, 8));
1062         break;
1063     case 4:
1064         if (len == 1)
1065             return 8;
1066
1067         key_event(vs, read_u8(data, 1), read_u32(data, 4));
1068         break;
1069     case 5:
1070         if (len == 1)
1071             return 6;
1072
1073         pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
1074         break;
1075     case 6:
1076         if (len == 1)
1077             return 8;
1078
1079         if (len == 8)
1080             return 8 + read_u32(data, 4);
1081
1082         client_cut_text(vs, read_u32(data, 4), data + 8);
1083         break;
1084     default:
1085         printf("Msg: %d\n", data[0]);
1086         vnc_client_error(vs);
1087         break;
1088     }
1089         
1090     vnc_read_when(vs, protocol_client_msg, 1);
1091     return 0;
1092 }
1093
1094 static int protocol_client_init(VncState *vs, char *data, size_t len)
1095 {
1096     char pad[3] = { 0, 0, 0 };
1097     char buf[1024];
1098     int size;
1099
1100     vs->width = vs->ds->width;
1101     vs->height = vs->ds->height;
1102     vnc_write_u16(vs, vs->ds->width);
1103     vnc_write_u16(vs, vs->ds->height);
1104
1105     vnc_write_u8(vs, vs->depth * 8); /* bits-per-pixel */
1106     vnc_write_u8(vs, vs->depth * 8); /* depth */
1107 #ifdef WORDS_BIGENDIAN
1108     vnc_write_u8(vs, 1);             /* big-endian-flag */
1109 #else
1110     vnc_write_u8(vs, 0);             /* big-endian-flag */
1111 #endif
1112     vnc_write_u8(vs, 1);             /* true-color-flag */
1113     if (vs->depth == 4) {
1114         vnc_write_u16(vs, 0xFF);     /* red-max */
1115         vnc_write_u16(vs, 0xFF);     /* green-max */
1116         vnc_write_u16(vs, 0xFF);     /* blue-max */
1117         vnc_write_u8(vs, 16);        /* red-shift */
1118         vnc_write_u8(vs, 8);         /* green-shift */
1119         vnc_write_u8(vs, 0);         /* blue-shift */
1120         vs->send_hextile_tile = send_hextile_tile_32;
1121     } else if (vs->depth == 2) {
1122         vnc_write_u16(vs, 31);       /* red-max */
1123         vnc_write_u16(vs, 63);       /* green-max */
1124         vnc_write_u16(vs, 31);       /* blue-max */
1125         vnc_write_u8(vs, 11);        /* red-shift */
1126         vnc_write_u8(vs, 5);         /* green-shift */
1127         vnc_write_u8(vs, 0);         /* blue-shift */
1128         vs->send_hextile_tile = send_hextile_tile_16;
1129     } else if (vs->depth == 1) {
1130         /* XXX: change QEMU pixel 8 bit pixel format to match the VNC one ? */
1131         vnc_write_u16(vs, 7);        /* red-max */
1132         vnc_write_u16(vs, 7);        /* green-max */
1133         vnc_write_u16(vs, 3);        /* blue-max */
1134         vnc_write_u8(vs, 5);         /* red-shift */
1135         vnc_write_u8(vs, 2);         /* green-shift */
1136         vnc_write_u8(vs, 0);         /* blue-shift */
1137         vs->send_hextile_tile = send_hextile_tile_8;
1138     }
1139     vs->write_pixels = vnc_write_pixels_copy;
1140         
1141     vnc_write(vs, pad, 3);           /* padding */
1142
1143     if (qemu_name)
1144         size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
1145     else
1146         size = snprintf(buf, sizeof(buf), "QEMU");
1147
1148     vnc_write_u32(vs, size);
1149     vnc_write(vs, buf, size);
1150     vnc_flush(vs);
1151
1152     vnc_read_when(vs, protocol_client_msg, 1);
1153
1154     return 0;
1155 }
1156
1157 static void make_challenge(VncState *vs)
1158 {
1159     int i;
1160
1161     srand(time(NULL)+getpid()+getpid()*987654+rand());
1162
1163     for (i = 0 ; i < sizeof(vs->challenge) ; i++)
1164         vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
1165 }
1166
1167 static int protocol_client_auth_vnc(VncState *vs, char *data, size_t len)
1168 {
1169     char response[VNC_AUTH_CHALLENGE_SIZE];
1170     int i, j, pwlen;
1171     char key[8];
1172
1173     if (!vs->password || !vs->password[0]) {
1174         VNC_DEBUG("No password configured on server");
1175         vnc_write_u32(vs, 1); /* Reject auth */
1176         if (vs->minor >= 8) {
1177             static const char err[] = "Authentication failed";
1178             vnc_write_u32(vs, sizeof(err));
1179             vnc_write(vs, err, sizeof(err));
1180         }
1181         vnc_flush(vs);
1182         vnc_client_error(vs);
1183         return 0;
1184     }
1185
1186     memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
1187
1188     /* Calculate the expected challenge response */
1189     pwlen = strlen(vs->password);
1190     for (i=0; i<sizeof(key); i++)
1191         key[i] = i<pwlen ? vs->password[i] : 0;
1192     deskey(key, EN0);
1193     for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
1194         des(response+j, response+j);
1195
1196     /* Compare expected vs actual challenge response */
1197     if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
1198         VNC_DEBUG("Client challenge reponse did not match\n");
1199         vnc_write_u32(vs, 1); /* Reject auth */
1200         if (vs->minor >= 8) {
1201             static const char err[] = "Authentication failed";
1202             vnc_write_u32(vs, sizeof(err));
1203             vnc_write(vs, err, sizeof(err));
1204         }
1205         vnc_flush(vs);
1206         vnc_client_error(vs);
1207     } else {
1208         VNC_DEBUG("Accepting VNC challenge response\n");
1209         vnc_write_u32(vs, 0); /* Accept auth */
1210         vnc_flush(vs);
1211
1212         vnc_read_when(vs, protocol_client_init, 1);
1213     }
1214     return 0;
1215 }
1216
1217 static int start_auth_vnc(VncState *vs)
1218 {
1219     make_challenge(vs);
1220     /* Send client a 'random' challenge */
1221     vnc_write(vs, vs->challenge, sizeof(vs->challenge));
1222     vnc_flush(vs);
1223
1224     vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
1225     return 0;
1226 }
1227
1228 static int protocol_client_auth(VncState *vs, char *data, size_t len)
1229 {
1230     /* We only advertise 1 auth scheme at a time, so client
1231      * must pick the one we sent. Verify this */
1232     if (data[0] != vs->auth) { /* Reject auth */
1233        VNC_DEBUG("Reject auth %d\n", (int)data[0]);
1234        vnc_write_u32(vs, 1);
1235        if (vs->minor >= 8) {
1236            static const char err[] = "Authentication failed";
1237            vnc_write_u32(vs, sizeof(err));
1238            vnc_write(vs, err, sizeof(err));
1239        }
1240        vnc_client_error(vs);
1241     } else { /* Accept requested auth */
1242        VNC_DEBUG("Client requested auth %d\n", (int)data[0]);
1243        switch (vs->auth) {
1244        case VNC_AUTH_NONE:
1245            VNC_DEBUG("Accept auth none\n");
1246            vnc_write_u32(vs, 0); /* Accept auth completion */
1247            vnc_read_when(vs, protocol_client_init, 1);
1248            break;
1249
1250        case VNC_AUTH_VNC:
1251            VNC_DEBUG("Start VNC auth\n");
1252            return start_auth_vnc(vs);
1253
1254        default: /* Should not be possible, but just in case */
1255            VNC_DEBUG("Reject auth %d\n", vs->auth);
1256            vnc_write_u8(vs, 1);
1257            if (vs->minor >= 8) {
1258                static const char err[] = "Authentication failed";
1259                vnc_write_u32(vs, sizeof(err));
1260                vnc_write(vs, err, sizeof(err));
1261            }
1262            vnc_client_error(vs);
1263        }
1264     }
1265     return 0;
1266 }
1267
1268 static int protocol_version(VncState *vs, char *version, size_t len)
1269 {
1270     char local[13];
1271
1272     memcpy(local, version, 12);
1273     local[12] = 0;
1274
1275     if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
1276         VNC_DEBUG("Malformed protocol version %s\n", local);
1277         vnc_client_error(vs);
1278         return 0;
1279     }
1280     VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
1281     if (vs->major != 3 ||
1282         (vs->minor != 3 &&
1283          vs->minor != 5 &&
1284          vs->minor != 7 &&
1285          vs->minor != 8)) {
1286         VNC_DEBUG("Unsupported client version\n");
1287         vnc_write_u32(vs, VNC_AUTH_INVALID);
1288         vnc_flush(vs);
1289         vnc_client_error(vs);
1290         return 0;
1291     }
1292     /* Some broken client report v3.5 which spec requires to be treated
1293      * as equivalent to v3.3 by servers
1294      */
1295     if (vs->minor == 5)
1296         vs->minor = 3;
1297
1298     if (vs->minor == 3) {
1299         if (vs->auth == VNC_AUTH_NONE) {
1300             VNC_DEBUG("Tell client auth none\n");
1301             vnc_write_u32(vs, vs->auth);
1302             vnc_flush(vs);
1303             vnc_read_when(vs, protocol_client_init, 1);
1304        } else if (vs->auth == VNC_AUTH_VNC) {
1305             VNC_DEBUG("Tell client VNC auth\n");
1306             vnc_write_u32(vs, vs->auth);
1307             vnc_flush(vs);
1308             start_auth_vnc(vs);
1309        } else {
1310             VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->auth);
1311             vnc_write_u32(vs, VNC_AUTH_INVALID);
1312             vnc_flush(vs);
1313             vnc_client_error(vs);
1314        }
1315     } else {
1316         VNC_DEBUG("Telling client we support auth %d\n", vs->auth);
1317         vnc_write_u8(vs, 1); /* num auth */
1318         vnc_write_u8(vs, vs->auth);
1319         vnc_read_when(vs, protocol_client_auth, 1);
1320         vnc_flush(vs);
1321     }
1322
1323     return 0;
1324 }
1325
1326 static void vnc_listen_read(void *opaque)
1327 {
1328     VncState *vs = opaque;
1329     struct sockaddr_in addr;
1330     socklen_t addrlen = sizeof(addr);
1331
1332     vs->csock = accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
1333     if (vs->csock != -1) {
1334         socket_set_nonblock(vs->csock);
1335         qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, opaque);
1336         vnc_write(vs, "RFB 003.008\n", 12);
1337         vnc_flush(vs);
1338         vnc_read_when(vs, protocol_version, 12);
1339         memset(vs->old_data, 0, vs->ds->linesize * vs->ds->height);
1340         memset(vs->dirty_row, 0xFF, sizeof(vs->dirty_row));
1341         vs->has_resize = 0;
1342         vs->has_hextile = 0;
1343         vs->ds->dpy_copy = NULL;
1344     }
1345 }
1346
1347 extern int parse_host_port(struct sockaddr_in *saddr, const char *str);
1348
1349 void vnc_display_init(DisplayState *ds)
1350 {
1351     VncState *vs;
1352
1353     vs = qemu_mallocz(sizeof(VncState));
1354     if (!vs)
1355         exit(1);
1356
1357     ds->opaque = vs;
1358     vnc_state = vs;
1359     vs->display = NULL;
1360     vs->password = NULL;
1361
1362     vs->lsock = -1;
1363     vs->csock = -1;
1364     vs->depth = 4;
1365     vs->last_x = -1;
1366     vs->last_y = -1;
1367
1368     vs->ds = ds;
1369
1370     if (!keyboard_layout)
1371         keyboard_layout = "en-us";
1372
1373     vs->kbd_layout = init_keyboard_layout(keyboard_layout);
1374     if (!vs->kbd_layout)
1375         exit(1);
1376
1377     vs->ds->data = NULL;
1378     vs->ds->dpy_update = vnc_dpy_update;
1379     vs->ds->dpy_resize = vnc_dpy_resize;
1380     vs->ds->dpy_refresh = vnc_dpy_refresh;
1381
1382     memset(vs->dirty_row, 0xFF, sizeof(vs->dirty_row));
1383
1384     vnc_dpy_resize(vs->ds, 640, 400);
1385 }
1386
1387 void vnc_display_close(DisplayState *ds)
1388 {
1389     VncState *vs = ds ? (VncState *)ds->opaque : vnc_state;
1390
1391     if (vs->display) {
1392         qemu_free(vs->display);
1393         vs->display = NULL;
1394     }
1395     if (vs->lsock != -1) {
1396         qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);
1397         close(vs->lsock);
1398         vs->lsock = -1;
1399     }
1400     if (vs->csock != -1) {
1401         qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
1402         closesocket(vs->csock);
1403         vs->csock = -1;
1404         buffer_reset(&vs->input);
1405         buffer_reset(&vs->output);
1406         vs->need_update = 0;
1407     }
1408     vs->auth = VNC_AUTH_INVALID;
1409 }
1410
1411 int vnc_display_password(DisplayState *ds, const char *password)
1412 {
1413     VncState *vs = ds ? (VncState *)ds->opaque : vnc_state;
1414
1415     if (vs->password) {
1416         qemu_free(vs->password);
1417         vs->password = NULL;
1418     }
1419     if (password && password[0]) {
1420         if (!(vs->password = qemu_strdup(password)))
1421             return -1;
1422     }
1423
1424     return 0;
1425 }
1426
1427 int vnc_display_open(DisplayState *ds, const char *display)
1428 {
1429     struct sockaddr *addr;
1430     struct sockaddr_in iaddr;
1431 #ifndef _WIN32
1432     struct sockaddr_un uaddr;
1433 #endif
1434     int reuse_addr, ret;
1435     socklen_t addrlen;
1436     const char *p;
1437     VncState *vs = ds ? (VncState *)ds->opaque : vnc_state;
1438     const char *options;
1439     int password = 0;
1440
1441     vnc_display_close(ds);
1442     if (strcmp(display, "none") == 0)
1443         return 0;
1444
1445     if (!(vs->display = strdup(display)))
1446         return -1;
1447
1448     options = display;
1449     while ((options = strchr(options, ','))) {
1450         options++;
1451         if (strncmp(options, "password", 8) == 0)
1452             password = 1; /* Require password auth */
1453     }
1454
1455     if (password) {
1456         VNC_DEBUG("Initializing VNC server with password auth\n");
1457         vs->auth = VNC_AUTH_VNC;
1458     } else {
1459         VNC_DEBUG("Initializing VNC server with no auth\n");
1460         vs->auth = VNC_AUTH_NONE;
1461     }
1462 #ifndef _WIN32
1463     if (strstart(display, "unix:", &p)) {
1464         addr = (struct sockaddr *)&uaddr;
1465         addrlen = sizeof(uaddr);
1466
1467         vs->lsock = socket(PF_UNIX, SOCK_STREAM, 0);
1468         if (vs->lsock == -1) {
1469             fprintf(stderr, "Could not create socket\n");
1470             free(vs->display);
1471             vs->display = NULL;
1472             return -1;
1473         }
1474
1475         uaddr.sun_family = AF_UNIX;
1476         memset(uaddr.sun_path, 0, 108);
1477         snprintf(uaddr.sun_path, 108, "%s", p);
1478
1479         unlink(uaddr.sun_path);
1480     } else
1481 #endif
1482     {
1483         addr = (struct sockaddr *)&iaddr;
1484         addrlen = sizeof(iaddr);
1485
1486         if (parse_host_port(&iaddr, display) < 0) {
1487             fprintf(stderr, "Could not parse VNC address\n");
1488             free(vs->display);
1489             vs->display = NULL;
1490             return -1;
1491         }
1492
1493         iaddr.sin_port = htons(ntohs(iaddr.sin_port) + 5900);
1494
1495         vs->lsock = socket(PF_INET, SOCK_STREAM, 0);
1496         if (vs->lsock == -1) {
1497             fprintf(stderr, "Could not create socket\n");
1498             free(vs->display);
1499             vs->display = NULL;
1500             return -1;
1501         }
1502
1503         reuse_addr = 1;
1504         ret = setsockopt(vs->lsock, SOL_SOCKET, SO_REUSEADDR,
1505                          (const char *)&reuse_addr, sizeof(reuse_addr));
1506         if (ret == -1) {
1507             fprintf(stderr, "setsockopt() failed\n");
1508             close(vs->lsock);
1509             vs->lsock = -1;
1510             free(vs->display);
1511             vs->display = NULL;
1512             return -1;
1513         }
1514     }
1515
1516     if (bind(vs->lsock, addr, addrlen) == -1) {
1517         fprintf(stderr, "bind() failed\n");
1518         close(vs->lsock);
1519         vs->lsock = -1;
1520         free(vs->display);
1521         vs->display = NULL;
1522         return -1;
1523     }
1524
1525     if (listen(vs->lsock, 1) == -1) {
1526         fprintf(stderr, "listen() failed\n");
1527         close(vs->lsock);
1528         vs->lsock = -1;
1529         free(vs->display);
1530         vs->display = NULL;
1531         return -1;
1532     }
1533
1534     return qemu_set_fd_handler2(vs->lsock, vnc_listen_poll, vnc_listen_read, NULL, vs);
1535 }