Skip to contentSkip to conversation

vnc: added initial websocket protocol support

PATCH Superseded Tim Hardeck 2 participants 3 messages Nov 23, 2012 – Dec 5, 2012

v3 of 7 Superseded Latest is v7 →

lore
Share & tools
lore
#0 lore raw

PATCH v3 1/1 vnc: added initial websocket protocol support

This patch adds basic Websocket Protocol version 13 - RFC 6455 - support to QEMU VNC. Binary encoding support on the client side is mandatory.

Because of the GnuTLS requirement the Websockets implementation is optional (--enable-vnc-ws).

To activate Websocket support the VNC option "websocket"is used, for example "-vnc :0,websocket".
The listen port for Websocket connections is (5700 + display) so if QEMU VNC is started with :0 the Websocket port would be 5700. As an alternative the Websocket port could be manually specified by using ",websocket=<port>" instead.

Parts of the implementation base on Anthony Liguori's QEMU Websocket patch from 2010 and on Joel Martin's LibVNC Websocket implementation.

---

Changes v2
* removed automatic websocket recognition
* added new lwebsock socket on port 5700 + display when the vnc option "websocket" is passed on
* adapted vnc_connect vnc_listen_read to differ between websocket
* added separate event handler to read the Websocket handshake

Changes v3
* added manual port specification by using ",websocket=<port>"
* switched from memmem() to g_strstr_len()
* removed masked_size from vncws_decode_frame()
* resetted vnc_tls variable to default in the configure script

QEMU does segfault if a regular VNC client connects to the Websocket port and then disconnects because of several unitialized lists since vnc_init_state wasn't run before.
The segfault could be fixed by applying my previously sent patches "[PATCH 0/2] fix segfaults triggered by failed vnc handshakes".

I have used parts of the LibVNC websockets implementation that's why I have added the GPL header to the new files.

---
 configure        |   32 ++++++++
 qemu-options.hx  |    8 ++
 ui/Makefile.objs |    1 +
 ui/vnc-ws.c      |  206 +++++++++++++++++++++++++++++++++++++++++++++++++
 ui/vnc-ws.h      |  101 ++++++++++++++++++++++++
 ui/vnc.c         |  226 +++++++++++++++++++++++++++++++++++++++++++++++++-----
 ui/vnc.h         |   21 +++++
 7 files changed, 575 insertions(+), 20 deletions(-)
 create mode 100644 ui/vnc-ws.c
 create mode 100644 ui/vnc-ws.h
configure +32 -0
index 780b19a..c384138 100755
@@ -158,6 +158,7 @@ vnc_tls=""
 vnc_sasl=""
 vnc_jpeg=""
 vnc_png=""
+vnc_ws=""
 xen=""
 xen_ctrl_version=""
 xen_pci_passthrough=""
@@ -703,6 +704,10 @@ for opt do
   ;;
   --enable-vnc-png) vnc_png="yes"
   ;;
+  --disable-vnc-ws) vnc_ws="no"
+  ;;
+  --enable-vnc-ws) vnc_ws="yes"
+  ;;
   --disable-slirp) slirp="no"
   ;;
   --disable-uuid) uuid="no"
@@ -1048,6 +1053,8 @@ echo "  --disable-vnc-jpeg       disable JPEG lossy compression for VNC server"
 echo "  --enable-vnc-jpeg        enable JPEG lossy compression for VNC server"
 echo "  --disable-vnc-png        disable PNG compression for VNC server (default)"
 echo "  --enable-vnc-png         enable PNG compression for VNC server"
+echo "  --disable-vnc-ws         disable Websockets support for VNC server"
+echo "  --enable-vnc-ws          enable Websockets support for VNC server"
 echo "  --disable-curses         disable curses output"
 echo "  --enable-curses          enable curses output"
 echo "  --disable-curl           disable curl connectivity"
@@ -1772,6 +1779,26 @@ EOF
 fi
 
 ##########################################
+# VNC WS detection
+if test "$vnc" = "yes" -a "$vnc_ws" != "no" ; then
+  cat > $TMPC <<EOF
+#include <gnutls/gnutls.h>
+int main(void) { gnutls_session_t s; gnutls_init(&s, GNUTLS_SERVER); return 0; }
+EOF
+  vnc_ws_cflags=`$pkg_config --cflags gnutls 2> /dev/null`
+  vnc_ws_libs=`$pkg_config --libs gnutls 2> /dev/null`
+  if compile_prog "$vnc_ws_cflags" "$vnc_ws_libs" ; then
+    vnc_ws=yes
+    libs_softmmu="$vnc_ws_libs $libs_softmmu"
+  else
+    if test "$vnc_ws" = "yes" ; then
+      feature_not_found "vnc-ws"
+    fi
+    vnc_ws=no
+  fi
+fi
+
+##########################################
 # fnmatch() probe, used for ACL routines
 fnmatch="no"
 cat > $TMPC << EOF
@@ -3194,6 +3221,7 @@ if test "$vnc" = "yes" ; then
     echo "VNC SASL support  $vnc_sasl"
     echo "VNC JPEG support  $vnc_jpeg"
     echo "VNC PNG support   $vnc_png"
+    echo "VNC WS support    $vnc_ws"
 fi
 if test -n "$sparc_cpu"; then
     echo "Target Sparc Arch $sparc_cpu"
@@ -3370,6 +3398,10 @@ if test "$vnc_png" = "yes" ; then
   echo "CONFIG_VNC_PNG=y" >> $config_host_mak
   echo "VNC_PNG_CFLAGS=$vnc_png_cflags" >> $config_host_mak
 fi
+if test "$vnc_ws" = "yes" ; then
+  echo "CONFIG_VNC_WS=y" >> $config_host_mak
+  echo "VNC_WS_CFLAGS=$vnc_ws_cflags" >> $config_host_mak
+fi
 if test "$fnmatch" = "yes" ; then
   echo "CONFIG_FNMATCH=y" >> $config_host_mak
 fi
qemu-options.hx +8 -0
index 9bb29d3..647071e 100644
@@ -1096,6 +1096,14 @@ client is specified by the @var{display}. For reverse network
 connections (@var{host}:@var{d},@code{reverse}), the @var{d} argument
 is a TCP port number, not a display number.
 
+@item websocket
+
+Opens an additional TCP listening port dedicated to VNC Websocket connections.
+By defintion the Websocket port is 5700+@var{display}. If @var{host} is
+specified connections will only be allowed from this host.
+As an alternative the Websocket port could be specified by using
+@code{websocket}=@var{port}.
+
 @item password
 
 Require that password based authentication is used for client connections.
ui/Makefile.objs +1 -0
index adc07be..58e191b 100644
@@ -4,6 +4,7 @@ vnc-obj-y += vnc-enc-tight.o vnc-palette.o
 vnc-obj-y += vnc-enc-zrle.o
 vnc-obj-$(CONFIG_VNC_TLS) += vnc-tls.o vnc-auth-vencrypt.o
 vnc-obj-$(CONFIG_VNC_SASL) += vnc-auth-sasl.o
+vnc-obj-$(CONFIG_VNC_WS) += vnc-ws.o
 vnc-obj-y += vnc-jobs.o
 
 common-obj-y += keymaps.o
ui/vnc-ws.c new file +206 -0

206 lines not on this page · raw message

ui/vnc-ws.h new file +101 -0

101 lines not on this page · raw message

ui/vnc.c +206 -20

367 lines not on this page · raw message

ui/vnc.h +21 -0
index 6141e88..2c6bfe7 100644
@@ -99,6 +99,9 @@ typedef struct VncDisplay VncDisplay;
 #ifdef CONFIG_VNC_SASL
 #include "vnc-auth-sasl.h"
 #endif
+#ifdef CONFIG_VNC_WS
+#include "vnc-ws.h"
+#endif
 
 struct VncRectStat
 {
@@ -142,6 +145,11 @@ struct VncDisplay
     QEMUTimer *timer;
     int timer_interval;
     int lsock;
+#ifdef CONFIG_VNC_WS
+    int lwebsock;
+    int websocket;
+    char *ws_display;
+#endif
     DisplayState *ds;
     kbd_layout_t *kbd_layout;
     int lock_key_sync;
@@ -269,11 +277,18 @@ struct VncState
 #ifdef CONFIG_VNC_SASL
     VncStateSASL sasl;
 #endif
+#ifdef CONFIG_VNC_WS
+    int encode_ws;
+    int websocket;
+#endif
 
     QObject *info;
 
     Buffer output;
     Buffer input;
+#ifdef CONFIG_VNC_WS
+    Buffer ws_input;
+#endif
     /* current output mode information */
     VncWritePixels *write_pixels;
     PixelFormat client_pf;
@@ -505,11 +520,17 @@ int vnc_client_io_error(VncState *vs, int ret, int last_errno);
 void start_client_init(VncState *vs);
 void start_auth_vnc(VncState *vs);
 
+#ifdef CONFIG_VNC_WS
+void vncws_handshake_read(void *opaque);
+void vnc_init_state(VncState *vs);
+#endif
+
 /* Buffer management */
 void buffer_reserve(Buffer *buffer, size_t len);
 void buffer_reset(Buffer *buffer);
 void buffer_free(Buffer *buffer);
 void buffer_append(Buffer *buffer, const void *data, size_t len);
+void buffer_advance(Buffer *buf, size_t len);
 
 
 /* Misc helpers */
Signature · 1 line
1.7.10.4
#1 lore raw

On Fri, Nov 23, 2012 at 08:00:47PM +0100, Tim Hardeck wrote:

Thanks for the patch, Tim. Some general code review comments below. I hope someone has time to review the VNC and WebSocket specific stuff. I didn't check the details of buffers, whether the WebSocket spec is correctly implemented, etc.

Quoted 5 lines

QEMU does segfault if a regular VNC client connects to the Websocket port and then disconnects because of several unitialized lists since vnc_init_state wasn't run before.
The segfault could be fixed by applying my previously sent patches "[PATCH 0/2] fix segfaults triggered by failed vnc handshakes".

The segfault issue should be addressed before merging it. I think the response on that email thread was to fix the qemu-queue.h users rather than making it okay to remove an element that isn't on a list (especially because this relies on uninitialized elements having a NULL value). So is the next step to fix those list users in VNC code?

Quoted 9 lines

##########################################

configure +8 -0
+# VNC WS detection
+if test "$vnc" = "yes" -a "$vnc_ws" != "no" ; then
+  cat > $TMPC <<EOF
+#include <gnutls/gnutls.h>
+int main(void) { gnutls_session_t s; gnutls_init(&s, GNUTLS_SERVER); return 0; }
+EOF
+  vnc_ws_cflags=`$pkg_config --cflags gnutls 2> /dev/null`
+  vnc_ws_libs=`$pkg_config --libs gnutls 2> /dev/null`

configure EOF · line 1799

Quoted 10 lines
configure +10 -0
+  if compile_prog "$vnc_ws_cflags" "$vnc_ws_libs" ; then
+    vnc_ws=yes
+    libs_softmmu="$vnc_ws_libs $libs_softmmu"
+  else
+    if test "$vnc_ws" = "yes" ; then
+      feature_not_found "vnc-ws"
+    fi
+    vnc_ws=no
+  fi
+fi

This is really testing for GnuTLS rather than WebSockets. This probing is duplicated from the VNC TLS option.

I suggest probing GnuTLS once and then using the result for both vnc_tls and vnc_ws. That way we don't duplicate the GnuTLS code.

qemu-options.hx client is specified by the @var{display}. For reverse network · line 1102

Quoted 12 lines
qemu-options.hx +4 -0
index 9bb29d3..647071e 100644
@@ -1096,6 +1096,14 @@ client is specified by the @var{display}. For reverse network
 connections (@var{host}:@var{d},@code{reverse}), the @var{d} argument
 is a TCP port number, not a display number.
 
+@item websocket
+
+Opens an additional TCP listening port dedicated to VNC Websocket connections.
+By defintion the Websocket port is 5700+@var{display}. If @var{host} is

s/defintion/definition/

qemu-options.hx client is specified by the @var{display}. For reverse network · line 1104

Quoted 2 lines
qemu-options.hx +2 -0
+char *vncws_extract_handshake_entry(const char *handshake,
+    size_t handshake_len, const char *name)

This function should be static.

Quoted 4 lines
qemu-options.hx +4 -0
+void vncws_process_handshake(VncState *vs, uint8_t *line, size_t size)
+{
+    char *protocols = vncws_extract_handshake_entry((const char *)line, size,
+            "Sec-WebSocket-Protocol: ");

qemu-options.hx client is specified by the @var{display}. For reverse network

Quoted 10 lines
qemu-options.hx +10 -0
+    char *version = vncws_extract_handshake_entry((const char *)line, size,
+            "Sec-WebSocket-Version: ");
+    char *key = vncws_extract_handshake_entry((const char *)line, size,
+            "Sec-WebSocket-Key: ");
+
+    if (protocols && version && key
+         && g_strrstr(protocols, "binary") != NULL
+         && strcmp(version, WS_SUPPORTED_VERSION) == 0
+         && strlen(key) == WS_CLIENT_KEY_LEN) {
+            vncws_send_handshake_response(vs, key);

Indentation should be 4 spaces.

qemu-options.hx

Quoted 11 lines
qemu-options.hx +11 -0
+    } else {
+        VNC_DEBUG("Defective Websockets header or unsupported protocol\n");
+        vnc_client_error(vs);
+    }
+
+    g_free(protocols);
+    g_free(version);
+    g_free(key);
+}
+
+void vncws_send_handshake_response(VncState *vs, const char* key)

This function should be static.

qemu-options.hx

Quoted 4 lines
qemu-options.hx +4 -0
+{
+    char combined_key[WS_CLIENT_KEY_LEN + WS_GUID_LEN + 1];
+    char response[WS_HANDSHAKE_MAX_LEN];
+    char hash[SHA1_DIGEST_LEN + 1];

Why +1 if this is a 20-byte SHA1 binary hash?

Quoted 14 lines
qemu-options.hx +14 -0
+    char *accept = NULL;
+    size_t hash_size = SHA1_DIGEST_LEN, response_size = 0;
+    gnutls_datum_t in;
+
+    /* create combined key */
+    pstrcpy(combined_key, WS_CLIENT_KEY_LEN + 1, key);
+    pstrcat(combined_key, WS_CLIENT_KEY_LEN + WS_GUID_LEN + 1, WS_GUID);
+
+    /* hash and encode it */
+    in.data = (void *)combined_key;
+    in.size = WS_CLIENT_KEY_LEN + WS_GUID_LEN;
+    if (gnutls_fingerprint(GNUTLS_DIG_SHA1, &in, hash, &hash_size)
+            == GNUTLS_E_SUCCESS) {
+        accept = g_base64_encode((guchar *)hash, SHA1_DIGEST_LEN);

qemu-options.hx

Quoted 10 lines
qemu-options.hx +10 -0
+    }
+    if (accept == NULL) {
+        VNC_DEBUG("Hashing Websocket combined key failed\n");
+        vnc_client_error(vs);
+        return;
+    }
+
+    /* create handshake response */
+    response_size = snprintf(response, WS_HANDSHAKE_MAX_LEN,
+            WS_HANDSHAKE, accept);

Please use sizeof(response) instead of WS_HANDSHAKE_MAX_LEN. It's safer to use sizeof() rather than repeating the constant so that the sizes still match up if the variable definition is changed.

Quoted 6 lines
qemu-options.hx +6 -0
+    g_free(accept);
+
+    vnc_write(vs, response, response_size);
+    vnc_flush(vs);
+
+    vs->encode_ws = 1;

qemu-options.hx

Quoted 10 lines
qemu-options.hx +10 -0
+    vnc_init_state(vs);
+}
+
+void vncws_encode_frame(Buffer *output, const void *payload,
+        const size_t payload_size)
+{
+    size_t header_size = 0;
+    unsigned char opcode = WS_OPCODE_BINARY_FRAME;
+    char header_buf[WS_HEAD_MAX_LEN];
+    ws_header_t *header = (ws_header_t *)header_buf;

It's slightly cleaner to use:

union {
    char buf[WS_HEAD_MAX_LEN];
    ws_header_t ws;
} header;

That way the compiler know they are aliased and can even align buf[] so that ws_header_t field accesses are aligned, if necessary.

Quoted 24 lines
ui/vnc-ws.h new file +18 -0
new file mode 100644
index 0000000..0c5e2b5
@@ -0,0 +1,101 @@
+/*
+ * QEMU VNC display driver: Websockets support
+ *
+ * Copyright (C) 2010 Joel Martin
+ * Copyright (C) 2012 Tim Hardeck
+ *
+ * This is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this software; if not, write to the Free Software

ui/vnc-ws.h line 28

Quoted 10 lines
ui/vnc-ws.h new file +10 -0
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301,
+ * USA.
+ */
+
+#ifndef __QEMU_VNC_WS_H
+#define __QEMU_VNC_WS_H
+
+#ifndef CONFIG_VNC_TLS
+#include <gnutls/gnutls.h>
+#endif

Your ./configure change does not depend on CONFIG_VNC_TLS. It would be possible to say ./configure --disable-vnc-tls --enable-vnc-ws. I think the #ifdef here can be dropped.

Quoted 12 lines
ui/vnc-ws.h new file +12 -0
+
+#define B64LEN(__x) (((__x + 2) / 3) * 12 / 3)
+#define SHA1_DIGEST_LEN 20
+
+#define WS_ACCEPT_LEN (B64LEN(SHA1_DIGEST_LEN) + 1)
+#define WS_CLIENT_KEY_LEN 24
+#define WS_GUID "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
+#define WS_GUID_LEN strlen(WS_GUID)
+
+#define WS_HANDSHAKE_MAX_LEN 192
+#define WS_HANDSHAKE "HTTP/1.1 101 Switching Protocols\r\n\
+Upgrade: websocket\r\n\

ui/vnc-ws.h line 50

Quoted 10 lines
ui/vnc-ws.h new file +10 -0
+Connection: Upgrade\r\n\
+Sec-WebSocket-Accept: %s\r\n\
+Sec-WebSocket-Protocol: binary\r\n\
+\r\n"
+#define WS_HANDSHAKE_DELIM "\r\n"
+#define WS_HANDSHAKE_END "\r\n\r\n"
+#define WS_SUPPORTED_VERSION "13"
+
+#define WS_HEAD_MIN_LEN 2
+#define WS_HEAD_MAX_LEN 14  /* 2 + sizeof(uint64_t) + sizeof(uint32_t) */

Perhaps best to convert the comment into code:

#define WS_HEAD_MAX_LEN (WS_HEAD_MIN_LEN + sizeof(uint64_t) + sizeof(uint32_t))

ui/vnc-ws.h line 55

Quoted 5 lines
ui/vnc-ws.h new file +5 -0
+
+#define WS_HTON64(n) htobe64(n)
+#define WS_HTON16(n) htobe16(n)
+#define WS_NTOH16(n) htobe16(n)
+#define WS_NTOH64(n) htobe64(n)

Why wrapper macros?

Quoted 15 lines
ui/vnc-ws.h new file +15 -0
+typedef union ws_mask_s {
+    char c[4];
+    uint32_t u;
+} ws_mask_t;
+
+/* XXX: The union and the structs do not need to be named.
+ *      We are working around a bug present in GCC < 4.6 which prevented
+ *      it from recognizing anonymous structs and unions.
+ *      See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=4784
+ */
+typedef struct __attribute__ ((__packed__)) ws_header_s {
+    unsigned char b0;
+    unsigned char b1;
+    union {
+        struct __attribute__ ((__packed__)) {

ui/vnc-ws.h line 81

Quoted 10 lines
ui/vnc-ws.h new file +10 -0
+            uint16_t l16;
+            ws_mask_t m16;
+        } s16;
+        struct __attribute__ ((__packed__)) {
+            uint64_t l64;
+            ws_mask_t m64;
+        } s64;
+        ws_mask_t m;
+    } u;
+} ws_header_t;

QEMU naming does not allow _t. This should be WsHeader or WSHeader.

Quoted 25 lines
ui/vnc-ws.h new file +20 -0
+
+enum {
+    WS_OPCODE_CONTINUATION = 0x0,
+    WS_OPCODE_TEXT_FRAME = 0x1,
+    WS_OPCODE_BINARY_FRAME = 0x2,
+    WS_OPCODE_CLOSE = 0x8,
+    WS_OPCODE_PING = 0x9,
+    WS_OPCODE_PONG = 0xA
+};
+
+char *vncws_extract_handshake_entry(const char *header, size_t header_len,
+            const char *name);
+void vncws_process_handshake(VncState *vs, uint8_t *line, size_t size);
+void vncws_send_handshake_response(VncState *vs, const char* key);
+void vncws_encode_frame(Buffer *output, const void *payload,
+            const size_t payload_size);
+int vncws_decode_frame(Buffer *input, uint8_t **payload,
+                               size_t *payload_size, size_t *frame_size);
+
+#endif /* __QEMU_VNC_WS_H */
ui/vnc.c +0 -0
index 61f120e..676ac0d 100644

ui/vnc.c void buffer_append(Buffer *buffer, const void *data, size_t len) · line 518

Quoted 9 lines
ui/vnc.c +6 -0
@@ -510,6 +510,13 @@ void buffer_append(Buffer *buffer, const void *data, size_t len)
     buffer->offset += len;
 }
 
+void buffer_advance(Buffer *buf, size_t len)
+{
+    memmove(buf->buffer, buf->buffer + len,
+            (buf->offset - len));
+    buf->offset -= len;
+}

Please introduce this function and convert its callers in a separate commit. That makes it easier to review, bisect, revert, etc the commits. This change isn't WS-specific.

Quoted 84 lines
ui/vnc.c +46 -3
+
 static void vnc_desktop_resize(VncState *vs)
 {
     DisplayState *ds = vs->ds;
@@ -1027,6 +1034,9 @@ static void vnc_disconnect_finish(VncState *vs)
 
     buffer_free(&vs->input);
     buffer_free(&vs->output);
+#ifdef CONFIG_VNC_WS
+    buffer_free(&vs->ws_input);
+#endif
 
     qobject_decref(vs->info);
 
@@ -1166,8 +1176,7 @@ static long vnc_client_write_plain(VncState *vs)
     if (!ret)
         return 0;
 
-    memmove(vs->output.buffer, vs->output.buffer + ret, (vs->output.offset - ret));
-    vs->output.offset -= ret;
+    buffer_advance(&vs->output, ret);
 
     if (vs->output.offset == 0) {
         qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
@@ -1280,6 +1289,26 @@ static void vnc_jobs_bh(void *opaque)
     vnc_jobs_consume_buffer(vs);
 }
 
+#ifdef CONFIG_VNC_WS
+void vncws_handshake_read(void *opaque)
+{
+    VncState *vs = opaque;
+    long ret = vnc_client_read_plain(vs);
+    if (!ret) {
+        if (vs->csock == -1) {
+            vnc_disconnect_finish(vs);
+        }
+        return;
+    }
+
+    if (vs->input.offset > 0) {
+        qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
+        vncws_process_handshake(vs, vs->input.buffer, vs->input.offset);
+        buffer_reset(&vs->input);
+    }
+}
+#endif
+
 /*
  * First function called whenever there is more data to be read from
  * the client socket. Will delegate actual work according to whether
@@ -1289,6 +1318,7 @@ void vnc_client_read(void *opaque)
 {
     VncState *vs = opaque;
     long ret;
+    Buffer *buf;
 
 #ifdef CONFIG_VNC_SASL
     if (vs->sasl.conn && vs->sasl.runSSF)
@@ -1302,19 +1332,49 @@ void vnc_client_read(void *opaque)
         return;
     }
 
-    while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
+#ifdef CONFIG_VNC_WS
+    if (vs->encode_ws) {
+        uint8_t *payload;
+        size_t payload_size, frame_size;
+
+        /* make sure that nothing is left in the input buffer */
+        do {
+            ret = vncws_decode_frame(&vs->input, &payload,
+                                  &payload_size, &frame_size);
+
+            if (ret == 0) {
+                /* not enough data to process, wait for more */
+                return;
+            } else if (ret == -1) {
+                vnc_disconnect_start(vs);
+                return;
+            } else if (ret == -2) {
+                vnc_client_error(vs);
+                return;
+            }

ui/vnc.c void vnc_client_read(void *opaque) · line 1364

Quoted 10 lines
ui/vnc.c +10 -0
+
+            buffer_reserve(&vs->ws_input, payload_size);
+            buffer_append(&vs->ws_input, payload, payload_size);
+
+            buffer_advance(&vs->input, frame_size);
+        } while (vs->input.offset > 0);
+        buf = &vs->ws_input;
+    } else
+#endif /* CONFIG_VNC_WS */
+        buf = &vs->input;

QEMU coding style always requires {}, even if the if/else statement body is only 1 line.

Quoted 20 lines
ui/vnc.c +4 -3
+
+    while (vs->read_handler && buf->offset >= vs->read_handler_expect) {
         size_t len = vs->read_handler_expect;
         int ret;
 
-        ret = vs->read_handler(vs, vs->input.buffer, len);
+        ret = vs->read_handler(vs, buf->buffer, len);
         if (vs->csock == -1) {
             vnc_disconnect_finish(vs);
             return;
         }
 
         if (!ret) {
-            memmove(vs->input.buffer, vs->input.buffer + len, (vs->input.offset - len));
-            vs->input.offset -= len;
+            buffer_advance(buf, len);
         } else {
             vs->read_handler_expect = ret;
         }

ui/vnc.c void vnc_client_read(void *opaque) · line 1391

Quoted 10 lines
ui/vnc.c +6 -1
@@ -1323,13 +1383,26 @@ void vnc_client_read(void *opaque)
 
 void vnc_write(VncState *vs, const void *data, size_t len)
 {
-    buffer_reserve(&vs->output, len);
+#ifdef CONFIG_VNC_WS
+    if (vs->encode_ws) {
+        if (vs->csock != -1 && buffer_empty(&vs->output)) {
+            qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read,
+                    vnc_client_write, vs);
+        }

Can this be done unconditionally outside the if statement and #ifdef? Seems to be duplicated below into the else body.

Quoted 8 lines
ui/vnc.c +4 -3
+        vncws_encode_frame(&vs->output, data, len);
+    } else {
+#endif /* CONFIG_VNC_WS */
+        buffer_reserve(&vs->output, len);
 
-    if (vs->csock != -1 && buffer_empty(&vs->output)) {
-        qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
-    }

ui/vnc.c void vnc_client_read(void *opaque) · line 1405

Quoted 10 lines
ui/vnc.c +8 -1
+        if (vs->csock != -1 && buffer_empty(&vs->output)) {
+            qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read,
+                    vnc_client_write, vs);
+        }
 
-    buffer_append(&vs->output, data, len);
+        buffer_append(&vs->output, data, len);
+#ifdef CONFIG_VNC_WS
+    }
+#endif

This #ifdef can be avoided by:
#ifdef CONFIG_VNC_WS

if (...) {
    ...
} else
#endif
{
    ...
}

ui/vnc.c static void vnc_remove_timer(VncDisplay *vd) · line 2733

Quoted 9 lines
ui/vnc.c +1 -1
 }
 
 void vnc_write_s32(VncState *vs, int32_t value)
@@ -2657,7 +2730,7 @@ static void vnc_remove_timer(VncDisplay *vd)
     }
 }
 
-static void vnc_connect(VncDisplay *vd, int csock, int skipauth)
+static void vnc_connect(VncDisplay *vd, int csock, int skipauth, int websocket)

bool websocket

Quoted 24 lines
ui/vnc.c +10 -1
 {
     VncState *vs = g_malloc0(sizeof(VncState));
     int i;
@@ -2684,13 +2757,33 @@ static void vnc_connect(VncDisplay *vd, int csock, int skipauth)
     VNC_DEBUG("New client on socket %d\n", csock);
     dcl->idle = 0;
     socket_set_nonblock(vs->csock);
-    qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
+#ifdef CONFIG_VNC_WS
+    if (websocket) {
+        vs->websocket = 1;
+        qemu_set_fd_handler2(vs->csock, NULL, vncws_handshake_read, NULL, vs);
+    } else
+#endif
+    {
+        qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
+    }
 
     vnc_client_cache_addr(vs);
     vnc_qmp_event(vs, QEVENT_VNC_CONNECTED);
     vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
 
     vs->vd = vd;
+

ui/vnc.c static void vnc_connect(VncDisplay *vd, int csock, int skipauth) · line 2785

Quoted 10 lines
ui/vnc.c +10 -0
+#ifdef CONFIG_VNC_WS
+    if (!vs->websocket) {
+        vnc_init_state(vs);
+    }
+}
+
+void vnc_init_state(VncState *vs)
+{
+    VncDisplay *vd = vs->vd;
+#endif /* CONFIG_VNC_WS */

Using an #ifdef to split a function at compile time is too ugly IMO.

I suggest splitting the function, always have vnc_init_state().

ui/vnc.c static void vnc_connect(VncDisplay *vd, int csock, int skipauth) · line 2818

Quoted 10 lines
ui/vnc.c +2 -1
+
     vs->ds = vd->ds;
     vs->last_x = -1;
     vs->last_y = -1;
@@ -2722,21 +2815,41 @@ static void vnc_connect(VncDisplay *vd, int csock, int skipauth)
     /* vs might be free()ed here */
 }
 
-static void vnc_listen_read(void *opaque)
+static void vnc_listen_read(void *opaque, int websocket)

s/int/bool/

Quoted 50 lines
ui/vnc.c +25 -2
 {
     VncDisplay *vs = opaque;
     struct sockaddr_in addr;
     socklen_t addrlen = sizeof(addr);
+    int csock;
 
     /* Catch-up */
     vga_hw_update();
+#ifdef CONFIG_VNC_WS
+    if (websocket) {
+        csock = qemu_accept(vs->lwebsock, (struct sockaddr *)&addr, &addrlen);
+    } else
+#endif
+    {
+        csock = qemu_accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
+    }
 
-    int csock = qemu_accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
     if (csock != -1) {
-        vnc_connect(vs, csock, 0);
+        vnc_connect(vs, csock, 0, websocket);
     }
 }
 
+static void vnc_listen_regular_read(void *opaque)
+{
+    vnc_listen_read(opaque, 0);
+}
+
+#ifdef CONFIG_VNC_WS
+static void vnc_listen_websocket_read(void *opaque)
+{
+    vnc_listen_read(opaque, 1);
+}
+#endif
+
 void vnc_display_init(DisplayState *ds)
 {
     VncDisplay *vs = g_malloc0(sizeof(*vs));
@@ -2748,6 +2861,9 @@ void vnc_display_init(DisplayState *ds)
     vnc_display = vs;
 
     vs->lsock = -1;
+#ifdef CONFIG_VNC_WS
+    vs->lwebsock = -1;
+#endif
 
     vs->ds = ds;
     QTAILQ_INIT(&vs->clients);

ui/vnc.c static void vnc_display_close(DisplayState *ds) · line 2912

Quoted 8 lines
ui/vnc.c +5 -0
@@ -2789,6 +2905,17 @@ static void vnc_display_close(DisplayState *ds)
         close(vs->lsock);
         vs->lsock = -1;
     }
+#ifdef CONFIG_VNC_WS
+    if (vs->ws_display) {
+        g_free(vs->ws_display);
+        vs->ws_display = NULL;
+    }

NULL test not necessary since g_free(NULL) is a nop.

Quoted 10 lines
ui/vnc.c +6 -0
+    if (vs->lwebsock != -1) {
+        qemu_set_fd_handler2(vs->lwebsock, NULL, NULL, NULL, NULL);
+        close(vs->lwebsock);
+        vs->lwebsock = -1;
+    }
+#endif
     vs->auth = VNC_AUTH_INVALID;
 #ifdef CONFIG_VNC_TLS
     vs->subauth = VNC_AUTH_INVALID;

ui/vnc.c void vnc_display_open(DisplayState *ds, const char *display, Error **errp) · line 3045

Quoted 9 lines
ui/vnc.c +6 -0
@@ -2910,6 +3037,36 @@ void vnc_display_open(DisplayState *ds, const char *display, Error **errp)
         } else if (strncmp(options, "sasl", 4) == 0) {
             sasl = 1; /* Require SASL auth */
 #endif
+#ifdef CONFIG_VNC_WS
+        } else if (strncmp(options, "websocket", 9) == 0) {
+            char *start, *end;
+            vs->websocket = 1;
+
+            /* Check for 'websocket=<port> */

s/'websocket=<port>/'websocket=<port>'/

Quoted 60 lines
ui/vnc.c +38 -1
+            start = strchr(options, '=');
+            end = strchr(options, ',');
+            if (start && (!end || (start < end))) {
+                int len = end ? end-(start+1) : strlen(start+1);
+                if (len < 6) {
+                    /* extract the host specification from display */
+                    char  *host = NULL, *port = NULL, *host_end = NULL;
+                    port = g_strndup(start + 1, len);
+
+                    /* ipv6 host have colons */
+                    end = strchr(display, ',');
+                    host_end = g_strrstr_len(display, end - display, ":");
+
+                    if (host_end) {
+                        host = g_strndup(display, host_end - display + 1);
+                    } else {
+                        host = g_strndup(":", 1);
+                    }
+                    vs->ws_display = g_strconcat(host, port, NULL);
+                    g_free(host);
+                    g_free(port);
+                }
+            }
+#endif
 #ifdef CONFIG_VNC_TLS
         } else if (strncmp(options, "tls", 3) == 0) {
             tls = 1; /* Require TLS */
@@ -3068,6 +3225,9 @@ void vnc_display_open(DisplayState *ds, const char *display, Error **errp)
         /* connect to viewer */
         int csock;
         vs->lsock = -1;
+#ifdef CONFIG_VNC_WS
+        vs->lwebsock = -1;
+#endif
         if (strncmp(display, "unix:", 5) == 0) {
             csock = unix_connect(display+5, errp);
         } else {
@@ -3076,7 +3236,7 @@ void vnc_display_open(DisplayState *ds, const char *display, Error **errp)
         if (csock < 0) {
             goto fail;
         }
-        vnc_connect(vs, csock, 0);
+        vnc_connect(vs, csock, 0, 0);
     } else {
         /* listen for connects */
         char *dpy;
@@ -3087,25 +3247,51 @@ void vnc_display_open(DisplayState *ds, const char *display, Error **errp)
         } else {
             vs->lsock = inet_listen(display, dpy, 256,
                                     SOCK_STREAM, 5900, errp);
+#ifdef CONFIG_VNC_WS
+            if (vs->websocket) {
+                if (vs->ws_display) {
+                    vs->lwebsock = inet_listen(vs->ws_display, NULL, 256,
+                        SOCK_STREAM, 0, errp);
+                } else {
+                    vs->lwebsock = inet_listen(vs->display, NULL, 256,
+                        SOCK_STREAM, 5700, errp);
+                }
+            }

ui/vnc.c void vnc_display_open(DisplayState *ds, const char *display, Error **errp) · line 3268

Quoted 10 lines
ui/vnc.c +6 -1
+#endif
         }
-        if (vs->lsock < 0) {
+        if (vs->lsock < 0
+#ifdef CONFIG_VNC_WS
+                || (vs->websocket && vs->lwebsock < 0)
+#endif
+                ) {
             g_free(dpy);
             goto fail;

Will this leak the lsock file descriptor when both a regular VNC port and a websocket port are given but inet_listen() fails on just the websocket?

Quoted 46 lines
ui/vnc.c +13 -2
         }
         g_free(vs->display);
         vs->display = dpy;
-        qemu_set_fd_handler2(vs->lsock, NULL, vnc_listen_read, NULL, vs);
+        qemu_set_fd_handler2(vs->lsock, NULL,
+                vnc_listen_regular_read, NULL, vs);
+#ifdef CONFIG_VNC_WS
+        if (vs->websocket) {
+            qemu_set_fd_handler2(vs->lwebsock, NULL,
+                    vnc_listen_websocket_read, NULL, vs);
+        }
+#endif
     }
     return;
 
 fail:
     g_free(vs->display);
     vs->display = NULL;
+#ifdef CONFIG_VNC_WS
+    g_free(vs->ws_display);
+    vs->ws_display = NULL;
+#endif
 }
 
 void vnc_display_add_client(DisplayState *ds, int csock, int skipauth)
 {
     VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;
 
-    vnc_connect(vs, csock, skipauth);
+    vnc_connect(vs, csock, skipauth, 0);
 }
ui/vnc.h +3 -0
index 6141e88..2c6bfe7 100644
@@ -99,6 +99,9 @@ typedef struct VncDisplay VncDisplay;
 #ifdef CONFIG_VNC_SASL
 #include "vnc-auth-sasl.h"
 #endif
+#ifdef CONFIG_VNC_WS
+#include "vnc-ws.h"
+#endif
 
 struct VncRectStat
 {

ui/vnc.h struct VncDisplay · line 150

Quoted 6 lines
ui/vnc.h +3 -0
@@ -142,6 +145,11 @@ struct VncDisplay
     QEMUTimer *timer;
     int timer_interval;
     int lsock;
+#ifdef CONFIG_VNC_WS
+    int lwebsock;
+    int websocket;

Please use bool.

ui/vnc.h struct VncState · line 281

Quoted 11 lines
ui/vnc.h +4 -0
+    char *ws_display;
+#endif
     DisplayState *ds;
     kbd_layout_t *kbd_layout;
     int lock_key_sync;
@@ -269,11 +277,18 @@ struct VncState
 #ifdef CONFIG_VNC_SASL
     VncStateSASL sasl;
 #endif
+#ifdef CONFIG_VNC_WS
+    int encode_ws;

Please use bool.

ui/vnc.h struct VncState · line 282

Quoted 1 line
ui/vnc.h +1 -0
+    int websocket;

Please use bool.

#2 lore raw

Hi Stefan,

Quoted 1 line · Stefan Hajnoczi

Thanks for the patch, Tim. Some general code review comments below.

Thanks for the code review. I am going to incorporate them in my new patch.

Quoted 3 lines

I hope someone has time to review the VNC and WebSocket specific stuff. I didn't check the details of buffers, whether the WebSocket spec is correctly implemented, etc.

I have mainly tested my websockets implementation with the guest OS openSUSE 12.2 which worked fine during all my tests on several browsers. I recently found out though that when I run Firefox in openSUSE 12.1, noVNC complains about an unsupported VNC encoding and QEMU crashes. I have attached the back trace at the end of this mail.

This issue could be fixed by not encoding Websocket frames directly in vnc_write but in vnc_client_write_locked. This should also decrease the overhead through websocket frame headers.
Nevertheless it looks like QEMU did crash because of the sudden disconnect which shouldn't happen.

I have created a vnc_client_write_ws function which is used instead of vnc_client_write_plain. I have also moved the decoding part to vnc_client_read_ws to keep consistency?
Is this Ok or should I add the websocket en/decoding to the existing vnc plain functions?

Regards
Tim

#0 0x00007ffff3f92d25 in __GI_raise (sig=sig@entry=6) at ../nptl/sysdeps/unix/sysv/linux/raise.c:64

        resultvar = 0
        pid = 24308
        selftid = 24312

#1 0x00007ffff3f941a8 in __GI_abort () at abort.c:91
save_stage = 2
act = {__sigaction_handler = {sa_handler = 0x5555559153c0
<__func__.4908>, sa_sigaction =

    0x5555559153c0 <__func__.4908>}, sa_mask = {__val =
{140737287809753, 0, 18374686479671623680,
    0, 140737286898450, 131072, 93825010082032, 2064448, 93825010157472,
1989008, 22,
    140737218422160, 1, 140737488346032, 0, 140737218426624}}, sa_flags
= -201457138, sa_restorer =
    0x6d940}
        sigs = {__val = {32, 0 <repeats 15 times>}}

#2 0x000055555577b5c2 in error_exit (err=22, msg=0x5555559153c0 <__func__.4908> "qemu_mutex_lock")
at qemu-thread-posix.c:28
No locals.
#3 0x000055555577b6e1 in qemu_mutex_lock (mutex=0x555556666328) at qemu-thread-posix.c:59

        err = 22
        __func__ = "qemu_mutex_lock"

#4 0x00005555557bb075 in vnc_lock_output (vs=0x55555665a100) at ui/vnc-jobs.h:63
No locals.
#5 0x00005555557bb5eb in vnc_jobs_consume_buffer (vs=0x55555665a100) at ui/vnc-jobs.c:166
flush = false
#6 0x00005555557bb5ae in vnc_jobs_join (vs=0x55555665a100) at ui/vnc-jobs.c:159
No locals.
#7 0x00005555557bf9d9 in vnc_update_client_sync (vs=0x55555665a100, has_dirty=1) at ui/vnc.c:876

        ret = 0
---Type <return> to continue, or q <return> to quit---
#8  0x00005555557bf308 in vnc_dpy_copy (ds=0x555556583240, src_x=99,
src_y=143, dst_x=99, dst_y=
    146, w=8, h=1) at ui/vnc.c:752
        vd = 0x7fffeea48010
        vs = 0x55555665a100
        vn = 0x0
        src_row = 0x1800000000 <Address 0x1800000000 out of bounds>
        dst_row = 0xc0000000c00 <Address 0xc0000000c00 out of bounds>
        i = 768
        x = -1
        y = 24
        pitch = 1024
        inc = 0
        w_lim = 0
        s = 8
        cmp_bytes = 2359296
#9  0x0000555555623e78 in dpy_gfx_copy (s=0x555556583240, src_x=99,
src_y=143, dst_x=99, dst_y=146,
    w=8, h=1) at console.h:275
        dcl = 0x5555565f38e0
#10 0x00005555556281f4 in qemu_console_copy (ds=0x555556583240,
src_x=99, src_y=143, dst_x=99,
    dst_y=146, w=8, h=1) at console.c:1598
No locals.
#11 0x000055555566a79a in cirrus_do_copy (s=0x5555565afc08, dst=448832,
src=439616, w=8, h=1)
    at hw/cirrus_vga.c:732
        sx = 99
        sy = 143
        dx = 99

---Type <return> to continue, or q <return> to quit---
dy = 146
depth = 3
notify = 1
#12 0x000055555566a8f7 in cirrus_bitblt_videotovideo_copy (s=0x5555565afc08) at hw/cirrus_vga.c:750
No locals.
#13 0x000055555566ae8b in cirrus_bitblt_videotovideo (s=0x5555565afc08)

at hw/cirrus_vga.c:872
        ret = 1
#14 0x000055555566b61c in cirrus_bitblt_start (s=0x5555565afc08) at
hw/cirrus_vga.c:1013
        blt_rop = 13 '\r'
#15 0x000055555566b6c8 in cirrus_write_bitblt (s=0x5555565afc08,
reg_value=2)
    at hw/cirrus_vga.c:1034
        old_value = 0
#16 0x000055555566c589 in cirrus_vga_write_gr (s=0x5555565afc08,
reg_index=49, reg_value=2)
    at hw/cirrus_vga.c:1529
No locals.
#17 0x000055555566cebb in cirrus_mmio_blt_write (s=0x5555565afc08,
address=64, value=2 '\002')
    at hw/cirrus_vga.c:1883
No locals.
#18 0x000055555566ed4c in cirrus_mmio_write (opaque=0x5555565afc08,
addr=320, val=2, size=1)
    at hw/cirrus_vga.c:2659
        s = 0x5555565afc08
#19 0x000055555584b7ca in memory_region_write_accessor
(opaque=0x5555565c0538, addr=320, value=
    0x7fffefe92a98, size=1, shift=0, mask=255) at
/suse/thardeck/Development/qemu/memory.c:334
        mr = 0x5555565c0538
        tmp = 2
#20 0x000055555584b8ac in access_with_adjusted_size (addr=320,
value=0x7fffefe92a98, size=4,
---Type <return> to continue, or q <return> to quit---
    access_size_min=1, access_size_max=1, access=0x55555584b745
<memory_region_write_accessor>,
    opaque=0x5555565c0538) at /suse/thardeck/Development/qemu/memory.c:364
        access_mask = 255
        access_size = 1
        i = 0
#21 0x000055555584e51a in memory_region_dispatch_write
(mr=0x5555565c0538, addr=320, data=
    4294967042, size=4) at /suse/thardeck/Development/qemu/memory.c:916

No locals.
#22 0x000055555585154a in io_mem_write (mr=0x5555565c0538, addr=320, val=4294967042, size=4)
at /suse/thardeck/Development/qemu/memory.c:1581
No locals.
#23 0x00005555557ea58f in address_space_rw (as=0x5555564ec440 <address_space_memory>, addr=

    4273930560, buf=0x7ffff7ff2028 "\002\377\377\377", len=4, is_write=true)
    at /suse/thardeck/Development/qemu/exec.c:3397
        addr1 = 320
        d = 0x555556561860
        l = 4
        ptr = 0x555555808a39 <cpu_set_apic_base+128> "H\213E\370dH3\004%("
        val = 4294967042
        page = 4273930240
        section = 0x55555664f1a0
#24 0x00005555557ea953 in cpu_physical_memory_rw (addr=4273930560, buf=
    0x7ffff7ff2028 "\002\377\377\377", len=4, is_write=1)
    at /suse/thardeck/Development/qemu/exec.c:3479
No locals.
#25 0x000055555584886e in kvm_cpu_exec (env=0x555556569300)
---Type <return> to continue, or q <return> to quit---
    at /suse/thardeck/Development/qemu/kvm-all.c:1580
        run = 0x7ffff7ff2000
        ret = 0
        run_ret = 0
#26 0x00005555557dc6a0 in qemu_kvm_cpu_thread_fn (arg=0x555556569300)
    at /suse/thardeck/Development/qemu/cpus.c:757
        env = 0x555556569300
        cpu = 0x5555565692a0
        r = 65536

#27 0x00007ffff4fdce0e in start_thread (arg=0x7fffefe93700) at pthread_create.c:305
__res = <optimized out>
pd = 0x7fffefe93700
now = <optimized out>
unwind_buf = {cancel_jmp_buf = {{jmp_buf = {140737218426624,
-6613775898926182534, 1,

    140737488346032, 0, 140737218426624, 6613810991376830330,
6613760524492017530},
              mask_was_saved = 0}}, priv = {pad = {0x0, 0x0, 0x0, 0x0},

data = {prev = 0x0,
cleanup = 0x0, canceltype = 0}}}
not_first_call = 0
pagesize_m1 = <optimized out>
sp = <optimized out>
freesize = <optimized out>
__PRETTY_FUNCTION__ = "start_thread"
#28 0x00007ffff40422bd in clone () at
../sysdeps/unix/sysv/linux/x86_64/clone.S:115
No locals.

Signature · 5 lines
SUSE LINUX Products GmbH, GF: Jeff Hawn, Jennifer Guild, Felix
Imendörffer, HRB 16746 (AG Nürnberg)
Maxfeldstr. 5, 90409 Nürnberg, Germany
T: +49 (0) 911 74053-0  F: +49 (0) 911 74053-483
http://www.suse.de/