Blame SOURCES/libvncserver-0.9.11-CVE-2017-18922.patch

80465d
Backport of:
80465d
From aac95a9dcf4bbba87b76c72706c3221a842ca433 Mon Sep 17 00:00:00 2001
80465d
From: Andreas Weigel <andreaswe@securepoint.de>
80465d
Date: Wed, 15 Feb 2017 12:31:05 +0100
80465d
Subject: [PATCH] fix overflow and refactor websockets decode (Hybi)
80465d
80465d
fix critical heap-based buffer overflow which allowed easy modification
80465d
of a return address via an overwritten function pointer
80465d
80465d
fix bug causing connections to fail due a "one websocket frame = one
80465d
ws_read" assumption, which failed with LibVNCServer-0.9.11
80465d
80465d
refactor websocket Hybi decode to use a simple state machine for
80465d
decoding of websocket frames
80465d
80465d
[Ubuntu note: Renamed b64_pton to __b64_pton in patch to ensure patch can be
80465d
applied.
80465d
 -- Avital]
80465d
80465d
---
80465d
 libvncserver/websockets.c | 595 +++++++++++++++++++++++++++++---------
80465d
 1 file changed, 463 insertions(+), 132 deletions(-)
80465d
80465d
--- a/libvncserver/websockets.c
80465d
+++ b/libvncserver/websockets.c
80465d
@@ -62,6 +62,9 @@
80465d
 
80465d
 #define B64LEN(__x) (((__x + 2) / 3) * 12 / 3)
80465d
 #define WSHLENMAX 14  /* 2 + sizeof(uint64_t) + sizeof(uint32_t) */
80465d
+#define WS_HYBI_MASK_LEN 4
80465d
+
80465d
+#define ARRAYSIZE(a) ((sizeof(a) / sizeof((a[0]))) / (size_t)(!(sizeof(a) % sizeof((a[0])))))
80465d
 
80465d
 enum {
80465d
   WEBSOCKETS_VERSION_HIXIE,
80465d
@@ -78,20 +81,20 @@ static int gettid() {
80465d
 typedef int (*wsEncodeFunc)(rfbClientPtr cl, const char *src, int len, char **dst);
80465d
 typedef int (*wsDecodeFunc)(rfbClientPtr cl, char *dst, int len);
80465d
 
80465d
-typedef struct ws_ctx_s {
80465d
-    char codeBufDecode[B64LEN(UPDATE_BUF_SIZE) + WSHLENMAX]; /* base64 + maximum frame header length */
80465d
-	char codeBufEncode[B64LEN(UPDATE_BUF_SIZE) + WSHLENMAX]; /* base64 + maximum frame header length */
80465d
-	char readbuf[8192];
80465d
-    int readbufstart;
80465d
-    int readbuflen;
80465d
-    int dblen;
80465d
-    char carryBuf[3];                      /* For base64 carry-over */
80465d
-    int carrylen;
80465d
-    int version;
80465d
-    int base64;
80465d
-    wsEncodeFunc encode;
80465d
-    wsDecodeFunc decode;
80465d
-} ws_ctx_t;
80465d
+
80465d
+enum {
80465d
+  /* header not yet received completely */
80465d
+  WS_HYBI_STATE_HEADER_PENDING,
80465d
+  /* data available */
80465d
+  WS_HYBI_STATE_DATA_AVAILABLE,
80465d
+  WS_HYBI_STATE_DATA_NEEDED,
80465d
+  /* received a complete frame */
80465d
+  WS_HYBI_STATE_FRAME_COMPLETE,
80465d
+  /* received part of a 'close' frame */
80465d
+  WS_HYBI_STATE_CLOSE_REASON_PENDING,
80465d
+  /* */
80465d
+  WS_HYBI_STATE_ERR
80465d
+};
80465d
 
80465d
 typedef union ws_mask_s {
80465d
   char c[4];
80465d
@@ -119,6 +122,38 @@ typedef struct __attribute__ ((__packed_
80465d
   } u;
80465d
 } ws_header_t;
80465d
 
80465d
+typedef struct ws_header_data_s {
80465d
+  ws_header_t *data;
80465d
+  /** bytes read */
80465d
+  int nRead;
80465d
+  /** mask value */
80465d
+  ws_mask_t mask;
80465d
+  /** length of frame header including payload len, but without mask */
80465d
+  int headerLen;
80465d
+  /** length of the payload data */
80465d
+  int payloadLen;
80465d
+  /** opcode */
80465d
+  unsigned char opcode;
80465d
+} ws_header_data_t;
80465d
+
80465d
+typedef struct ws_ctx_s {
80465d
+    char codeBufDecode[B64LEN(UPDATE_BUF_SIZE) + WSHLENMAX]; /* base64 + maximum frame header length */
80465d
+    char codeBufEncode[B64LEN(UPDATE_BUF_SIZE) + WSHLENMAX]; /* base64 + maximum frame header length */
80465d
+    char *writePos;
80465d
+    unsigned char *readPos;
80465d
+    int readlen;
80465d
+    int hybiDecodeState;
80465d
+    char carryBuf[3];                      /* For base64 carry-over */
80465d
+    int carrylen;
80465d
+    int version;
80465d
+    int base64;
80465d
+    ws_header_data_t header;
80465d
+    int nReadRaw;
80465d
+    int nToRead;
80465d
+    wsEncodeFunc encode;
80465d
+    wsDecodeFunc decode;
80465d
+} ws_ctx_t;
80465d
+
80465d
 enum
80465d
 {
80465d
     WS_OPCODE_CONTINUATION = 0x0,
80465d
@@ -179,6 +214,8 @@ static int webSocketsEncodeHixie(rfbClie
80465d
 static int webSocketsDecodeHybi(rfbClientPtr cl, char *dst, int len);
80465d
 static int webSocketsDecodeHixie(rfbClientPtr cl, char *dst, int len);
80465d
 
80465d
+static void hybiDecodeCleanup(ws_ctx_t *wsctx);
80465d
+
80465d
 static int
80465d
 min (int a, int b) {
80465d
     return a < b ? a : b;
80465d
@@ -440,10 +477,11 @@ webSocketsHandshake(rfbClientPtr cl, cha
80465d
 	wsctx->decode = webSocketsDecodeHixie;
80465d
     }
80465d
     wsctx->base64 = base64;
80465d
+    hybiDecodeCleanup(wsctx);
80465d
     cl->wsctx = (wsCtx *)wsctx;
80465d
     return TRUE;
80465d
 }
80465d
- 
80465d
+
80465d
 void
80465d
 webSocketsGenMd5(char * target, char *key1, char *key2, char *key3)
80465d
 {
80465d
@@ -635,146 +673,439 @@ webSocketsDecodeHixie(rfbClientPtr cl, c
80465d
 }
80465d
 
80465d
 static int
80465d
-webSocketsDecodeHybi(rfbClientPtr cl, char *dst, int len)
80465d
+hybiRemaining(ws_ctx_t *wsctx)
80465d
 {
80465d
-    char *buf, *payload;
80465d
-    uint32_t *payload32;
80465d
-    int ret = -1, result = -1;
80465d
-    int total = 0;
80465d
-    ws_mask_t mask;
80465d
-    ws_header_t *header;
80465d
-    int i;
80465d
-    unsigned char opcode;
80465d
-    ws_ctx_t *wsctx = (ws_ctx_t *)cl->wsctx;
80465d
-    int flength, fhlen;
80465d
-    /* int fin; */ /* not used atm */ 
80465d
+  return wsctx->nToRead - wsctx->nReadRaw;
80465d
+}
80465d
 
80465d
-    /* rfbLog(" <== %s[%d]: %d cl: %p, wsctx: %p-%p (%d)\n", __func__, gettid(), len, cl, wsctx, (char *)wsctx + sizeof(ws_ctx_t), sizeof(ws_ctx_t)); */
80465d
+static void
80465d
+hybiDecodeCleanup(ws_ctx_t *wsctx)
80465d
+{
80465d
+  wsctx->header.payloadLen = 0;
80465d
+  wsctx->header.mask.u = 0;
80465d
+  wsctx->nReadRaw = 0;
80465d
+  wsctx->nToRead= 0;
80465d
+  wsctx->carrylen = 0;
80465d
+  wsctx->readPos = (unsigned char *)wsctx->codeBufDecode;
80465d
+  wsctx->readlen = 0;
80465d
+  wsctx->hybiDecodeState = WS_HYBI_STATE_HEADER_PENDING;
80465d
+  wsctx->writePos = NULL;
80465d
+  rfbLog("cleaned up wsctx\n");
80465d
+}
80465d
 
80465d
-    if (wsctx->readbuflen) {
80465d
-      /* simply return what we have */
80465d
-      if (wsctx->readbuflen > len) {
80465d
-	memcpy(dst, wsctx->readbuf +  wsctx->readbufstart, len);
80465d
-	result = len;
80465d
-	wsctx->readbuflen -= len;
80465d
-	wsctx->readbufstart += len;
80465d
+/**
80465d
+ * Return payload data that has been decoded/unmasked from
80465d
+ * a websocket frame.
80465d
+ *
80465d
+ * @param[out]     dst destination buffer
80465d
+ * @param[in]      len bytes to copy to destination buffer
80465d
+ * @param[in,out]  wsctx internal state of decoding procedure
80465d
+ * @param[out]     number of bytes actually written to dst buffer
80465d
+ * @return next hybi decoding state
80465d
+ */
80465d
+static int
80465d
+hybiReturnData(char *dst, int len, ws_ctx_t *wsctx, int *nWritten)
80465d
+{
80465d
+  int nextState = WS_HYBI_STATE_ERR;
80465d
+
80465d
+  /* if we have something already decoded copy and return */
80465d
+  if (wsctx->readlen > 0) {
80465d
+    /* simply return what we have */
80465d
+    if (wsctx->readlen > len) {
80465d
+      rfbLog("copy to %d bytes to dst buffer; readPos=%p, readLen=%d\n", len, wsctx->readPos, wsctx->readlen);
80465d
+      memcpy(dst, wsctx->readPos, len);
80465d
+      *nWritten = len;
80465d
+      wsctx->readlen -= len;
80465d
+      wsctx->readPos += len;
80465d
+      nextState = WS_HYBI_STATE_DATA_AVAILABLE;
80465d
+    } else {
80465d
+      rfbLog("copy to %d bytes to dst buffer; readPos=%p, readLen=%d\n", wsctx->readlen, wsctx->readPos, wsctx->readlen);
80465d
+      memcpy(dst, wsctx->readPos, wsctx->readlen);
80465d
+      *nWritten = wsctx->readlen;
80465d
+      wsctx->readlen = 0;
80465d
+      wsctx->readPos = NULL;
80465d
+      if (hybiRemaining(wsctx) == 0) {
80465d
+        nextState = WS_HYBI_STATE_FRAME_COMPLETE;
80465d
       } else {
80465d
-	memcpy(dst, wsctx->readbuf +  wsctx->readbufstart, wsctx->readbuflen);
80465d
-	result = wsctx->readbuflen;
80465d
-	wsctx->readbuflen = 0;
80465d
-	wsctx->readbufstart = 0;
80465d
+        nextState = WS_HYBI_STATE_DATA_NEEDED;
80465d
       }
80465d
-      goto spor;
80465d
     }
80465d
+    rfbLog("after copy: readPos=%p, readLen=%d\n", wsctx->readPos, wsctx->readlen);
80465d
+  } else if (wsctx->hybiDecodeState == WS_HYBI_STATE_CLOSE_REASON_PENDING) {
80465d
+    nextState = WS_HYBI_STATE_CLOSE_REASON_PENDING;
80465d
+  }
80465d
+  return nextState;
80465d
+}
80465d
 
80465d
-    buf = wsctx->codeBufDecode;
80465d
-    header = (ws_header_t *)wsctx->codeBufDecode;
80465d
+/**
80465d
+ * Read an RFC 6455 websocket frame (IETF hybi working group).
80465d
+ *
80465d
+ * Internal state is updated according to bytes received and the
80465d
+ * decoding of header information.
80465d
+ *
80465d
+ * @param[in]   cl client ptr with ptr to raw socket and ws_ctx_t ptr
80465d
+ * @param[out]  sockRet emulated recv return value
80465d
+ * @return next hybi decoding state; WS_HYBI_STATE_HEADER_PENDING indicates
80465d
+ *         that the header was not received completely.
80465d
+ */
80465d
+static int
80465d
+hybiReadHeader(rfbClientPtr cl, int *sockRet)
80465d
+{
80465d
+  int ret;
80465d
+  ws_ctx_t *wsctx = (ws_ctx_t *)cl->wsctx;
80465d
+  char *headerDst = wsctx->codeBufDecode + wsctx->nReadRaw;
80465d
+  int n = WSHLENMAX - wsctx->nReadRaw;
80465d
+
80465d
+  rfbLog("header_read to %p with len=%d\n", headerDst, n);
80465d
+  ret = ws_read(cl, headerDst, n);
80465d
+  rfbLog("read %d bytes from socket\n", ret);
80465d
+  if (ret <= 0) {
80465d
+    if (-1 == ret) {
80465d
+      /* save errno because rfbErr() will tamper it */
80465d
+      int olderrno = errno;
80465d
+      rfbErr("%s: peek; %m\n", __func__);
80465d
+      errno = olderrno;
80465d
+      *sockRet = -1;
80465d
+    } else {
80465d
+      *sockRet = 0;
80465d
+    }
80465d
+    return WS_HYBI_STATE_ERR;
80465d
+  }
80465d
 
80465d
-    ret = ws_peek(cl, buf, B64LEN(len) + WSHLENMAX);
80465d
+  wsctx->nReadRaw += ret;
80465d
+  if (wsctx->nReadRaw < 2) {
80465d
+    /* cannot decode header with less than two bytes */
80465d
+    errno = EAGAIN;
80465d
+    *sockRet = -1;
80465d
+    return WS_HYBI_STATE_HEADER_PENDING;
80465d
+  }
80465d
+
80465d
+  /* first two header bytes received; interpret header data and get rest */
80465d
+  wsctx->header.data = (ws_header_t *)wsctx->codeBufDecode;
80465d
+
80465d
+  wsctx->header.opcode = wsctx->header.data->b0 & 0x0f;
80465d
+
80465d
+  /* fin = (header->b0 & 0x80) >> 7; */ /* not used atm */
80465d
+  wsctx->header.payloadLen = wsctx->header.data->b1 & 0x7f;
80465d
+  rfbLog("first header bytes received; opcode=%d lenbyte=%d\n", wsctx->header.opcode, wsctx->header.payloadLen);
80465d
+
80465d
+  /*
80465d
+   * 4.3. Client-to-Server Masking
80465d
+   *
80465d
+   * The client MUST mask all frames sent to the server.  A server MUST
80465d
+   * close the connection upon receiving a frame with the MASK bit set to 0.
80465d
+  **/
80465d
+  if (!(wsctx->header.data->b1 & 0x80)) {
80465d
+    rfbErr("%s: got frame without mask ret=%d\n", __func__, ret);
80465d
+    errno = EIO;
80465d
+    *sockRet = -1;
80465d
+    return WS_HYBI_STATE_ERR;
80465d
+  }
80465d
+
80465d
+  if (wsctx->header.payloadLen < 126 && wsctx->nReadRaw >= 6) {
80465d
+    wsctx->header.headerLen = 2 + WS_HYBI_MASK_LEN;
80465d
+    wsctx->header.mask = wsctx->header.data->u.m;
80465d
+  } else if (wsctx->header.payloadLen == 126 && 8 <= wsctx->nReadRaw) {
80465d
+    wsctx->header.headerLen = 4 + WS_HYBI_MASK_LEN;
80465d
+    wsctx->header.payloadLen = WS_NTOH16(wsctx->header.data->u.s16.l16);
80465d
+    wsctx->header.mask = wsctx->header.data->u.s16.m16;
80465d
+  } else if (wsctx->header.payloadLen == 127 && 14 <= wsctx->nReadRaw) {
80465d
+    wsctx->header.headerLen = 10 + WS_HYBI_MASK_LEN;
80465d
+    wsctx->header.payloadLen = WS_NTOH64(wsctx->header.data->u.s64.l64);
80465d
+    wsctx->header.mask = wsctx->header.data->u.s64.m64;
80465d
+  } else {
80465d
+    /* Incomplete frame header, try again */
80465d
+    rfbErr("%s: incomplete frame header; ret=%d\n", __func__, ret);
80465d
+    errno = EAGAIN;
80465d
+    *sockRet = -1;
80465d
+    return WS_HYBI_STATE_HEADER_PENDING;
80465d
+  }
80465d
+
80465d
+  /* absolute length of frame */
80465d
+  wsctx->nToRead = wsctx->header.headerLen + wsctx->header.payloadLen;
80465d
 
80465d
-    if (ret < 2) {
80465d
-        /* save errno because rfbErr() will tamper it */
80465d
-        if (-1 == ret) {
80465d
-            int olderrno = errno;
80465d
-            rfbErr("%s: peek; %m\n", __func__);
80465d
-            errno = olderrno;
80465d
-        } else if (0 == ret) {
80465d
-            result = 0;
80465d
-        } else {
80465d
-            errno = EAGAIN;
80465d
-        }
80465d
-        goto spor;
80465d
-    }
80465d
+  /* set payload pointer just after header */
80465d
+  wsctx->writePos = wsctx->codeBufDecode + wsctx->nReadRaw;
80465d
 
80465d
-    opcode = header->b0 & 0x0f;
80465d
-    /* fin = (header->b0 & 0x80) >> 7; */ /* not used atm */
80465d
-    flength = header->b1 & 0x7f;
80465d
+  wsctx->readPos = (unsigned char *)(wsctx->codeBufDecode + wsctx->header.headerLen);
80465d
 
80465d
-    /*
80465d
-     * 4.3. Client-to-Server Masking
80465d
-     *
80465d
-     * The client MUST mask all frames sent to the server.  A server MUST
80465d
-     * close the connection upon receiving a frame with the MASK bit set to 0.
80465d
-    **/
80465d
-    if (!(header->b1 & 0x80)) {
80465d
-	rfbErr("%s: got frame without mask\n", __func__, ret);
80465d
-	errno = EIO;
80465d
-	goto spor;
80465d
-    }
80465d
-
80465d
-    if (flength < 126) {
80465d
-	fhlen = 2;
80465d
-	mask = header->u.m;
80465d
-    } else if (flength == 126 && 4 <= ret) {
80465d
-	flength = WS_NTOH16(header->u.s16.l16);
80465d
-	fhlen = 4;
80465d
-	mask = header->u.s16.m16;
80465d
-    } else if (flength == 127 && 10 <= ret) {
80465d
-	flength = WS_NTOH64(header->u.s64.l64);
80465d
-	fhlen = 10;
80465d
-	mask = header->u.s64.m64;
80465d
-    } else {
80465d
-      /* Incomplete frame header */
80465d
-      rfbErr("%s: incomplete frame header\n", __func__, ret);
80465d
-      errno = EIO;
80465d
-      goto spor;
80465d
-    }
80465d
+  rfbLog("header complete: state=%d flen=%d writeTo=%p\n", wsctx->hybiDecodeState, wsctx->nToRead, wsctx->writePos);
80465d
+
80465d
+  return WS_HYBI_STATE_DATA_NEEDED;
80465d
+}
80465d
 
80465d
-    /* absolute length of frame */
80465d
-    total = fhlen + flength + 4;
80465d
-    payload = buf + fhlen + 4; /* header length + mask */
80465d
+static int
80465d
+hybiWsFrameComplete(ws_ctx_t *wsctx)
80465d
+{
80465d
+  return wsctx != NULL && hybiRemaining(wsctx) == 0;
80465d
+}
80465d
 
80465d
-    if (-1 == (ret = ws_read(cl, buf, total))) {
80465d
+static char *
80465d
+hybiPayloadStart(ws_ctx_t *wsctx)
80465d
+{
80465d
+  return wsctx->codeBufDecode + wsctx->header.headerLen;
80465d
+}
80465d
+
80465d
+
80465d
+/**
80465d
+ * Read the remaining payload bytes from associated raw socket.
80465d
+ *
80465d
+ *  - try to read remaining bytes from socket
80465d
+ *  - unmask all multiples of 4
80465d
+ *  - if frame incomplete but some bytes are left, these are copied to
80465d
+ *      the carry buffer
80465d
+ *  - if opcode is TEXT: Base64-decode all unmasked received bytes
80465d
+ *  - set state for reading decoded data
80465d
+ *  - reset write position to begin of buffer (+ header)
80465d
+ *      --> before we retrieve more data we let the caller clear all bytes
80465d
+ *          from the reception buffer
80465d
+ *  - execute return data routine
80465d
+ *
80465d
+ *  Sets errno corresponding to what it gets from the underlying
80465d
+ *  socket or EIO if some internal sanity check fails.
80465d
+ *
80465d
+ *  @param[in]  cl client ptr with raw socket reference
80465d
+ *  @param[out] dst  destination buffer
80465d
+ *  @param[in]  len  size of destination buffer
80465d
+ *  @param[out] sockRet emulated recv return value
80465d
+ *  @return next hybi decode state
80465d
+ */
80465d
+static int
80465d
+hybiReadAndDecode(rfbClientPtr cl, char *dst, int len, int *sockRet)
80465d
+{
80465d
+  int n;
80465d
+  int i;
80465d
+  int toReturn;
80465d
+  int toDecode;
80465d
+  int bufsize;
80465d
+  int nextRead;
80465d
+  unsigned char *data;
80465d
+  uint32_t *data32;
80465d
+  ws_ctx_t *wsctx = (ws_ctx_t *)cl->wsctx;
80465d
+
80465d
+  /* if data was carried over, copy to start of buffer */
80465d
+  memcpy(wsctx->writePos, wsctx->carryBuf, wsctx->carrylen);
80465d
+  wsctx->writePos += wsctx->carrylen;
80465d
+
80465d
+  /* -1 accounts for potential '\0' terminator for base64 decoding */
80465d
+  bufsize = wsctx->codeBufDecode + ARRAYSIZE(wsctx->codeBufDecode) - wsctx->writePos - 1;
80465d
+  if (hybiRemaining(wsctx) > bufsize) {
80465d
+    nextRead = bufsize;
80465d
+  } else {
80465d
+    nextRead = hybiRemaining(wsctx);
80465d
+  }
80465d
+
80465d
+  rfbLog("calling read with buf=%p and len=%d (decodebuf=%p headerLen=%d\n)", wsctx->writePos, nextRead, wsctx->codeBufDecode, wsctx->header.headerLen);
80465d
+
80465d
+  if (wsctx->nReadRaw < wsctx->nToRead) {
80465d
+    /* decode more data */
80465d
+    if (-1 == (n = ws_read(cl, wsctx->writePos, nextRead))) {
80465d
       int olderrno = errno;
80465d
       rfbErr("%s: read; %m", __func__);
80465d
       errno = olderrno;
80465d
-      return ret;
80465d
-    } else if (ret < total) {
80465d
-      /* GT TODO: hmm? */
80465d
-      rfbLog("%s: read; got partial data\n", __func__);
80465d
-    } else {
80465d
-      buf[ret] = '\0';
80465d
-    }
80465d
+      *sockRet = -1;
80465d
+      return WS_HYBI_STATE_ERR;
80465d
+    } else if (n == 0) {
80465d
+      *sockRet = 0;
80465d
+      return WS_HYBI_STATE_ERR;
80465d
+    }
80465d
+    wsctx->nReadRaw += n;
80465d
+    rfbLog("read %d bytes from socket; nRead=%d\n", n, wsctx->nReadRaw);
80465d
+  } else {
80465d
+    n = 0;
80465d
+  }
80465d
+
80465d
+  wsctx->writePos += n;
80465d
+
80465d
+  if (wsctx->nReadRaw >= wsctx->nToRead) {
80465d
+    if (wsctx->nReadRaw > wsctx->nToRead) {
80465d
+      rfbErr("%s: internal error, read past websocket frame", __func__);
80465d
+      errno=EIO;
80465d
+      *sockRet = -1;
80465d
+      return WS_HYBI_STATE_ERR;
80465d
+    }
80465d
+  }
80465d
+
80465d
+  toDecode = wsctx->writePos - hybiPayloadStart(wsctx);
80465d
+  rfbLog("toDecode=%d from n=%d carrylen=%d headerLen=%d\n", toDecode, n, wsctx->carrylen, wsctx->header.headerLen);
80465d
+  if (toDecode < 0) {
80465d
+    rfbErr("%s: internal error; negative number of bytes to decode: %d", __func__, toDecode);
80465d
+    errno=EIO;
80465d
+    *sockRet = -1;
80465d
+    return WS_HYBI_STATE_ERR;
80465d
+  }
80465d
+
80465d
+  /* for a possible base64 decoding, we decode multiples of 4 bytes until
80465d
+   * the whole frame is received and carry over any remaining bytes in the carry buf*/
80465d
+  data = (unsigned char *)hybiPayloadStart(wsctx);
80465d
+  data32= (uint32_t *)data;
80465d
+
80465d
+  for (i = 0; i < (toDecode >> 2); i++) {
80465d
+    data32[i] ^= wsctx->header.mask.u;
80465d
+  }
80465d
+  rfbLog("mask decoding; i=%d toDecode=%d\n", i, toDecode);
80465d
 
80465d
-    /* process 1 frame (32 bit op) */
80465d
-    payload32 = (uint32_t *)payload;
80465d
-    for (i = 0; i < flength / 4; i++) {
80465d
-	payload32[i] ^= mask.u;
80465d
-    }
80465d
+  if (wsctx->hybiDecodeState == WS_HYBI_STATE_FRAME_COMPLETE) {
80465d
     /* process the remaining bytes (if any) */
80465d
-    for (i*=4; i < flength; i++) {
80465d
-	payload[i] ^= mask.c[i % 4];
80465d
+    for (i*=4; i < toDecode; i++) {
80465d
+      data[i] ^= wsctx->header.mask.c[i % 4];
80465d
     }
80465d
 
80465d
-    switch (opcode) {
80465d
-      case WS_OPCODE_CLOSE:
80465d
-	rfbLog("got closure, reason %d\n", WS_NTOH16(((uint16_t *)payload)[0]));
80465d
-	errno = ECONNRESET;
80465d
-	break;
80465d
-      case WS_OPCODE_TEXT_FRAME:
80465d
-	if (-1 == (flength = __b64_pton(payload, (unsigned char *)wsctx->codeBufDecode, sizeof(wsctx->codeBufDecode)))) {
80465d
-	  rfbErr("%s: Base64 decode error; %m\n", __func__);
80465d
-	  break;
80465d
-	}
80465d
-	payload = wsctx->codeBufDecode;
80465d
-	/* fall through */
80465d
-      case WS_OPCODE_BINARY_FRAME:
80465d
-	if (flength > len) {
80465d
-	  memcpy(wsctx->readbuf, payload + len, flength - len);
80465d
-	  wsctx->readbufstart = 0;
80465d
-	  wsctx->readbuflen = flength - len;
80465d
-	  flength = len;
80465d
-	}
80465d
-	memcpy(dst, payload, flength);
80465d
-	result = flength;
80465d
-	break;
80465d
+    /* all data is here, no carrying */
80465d
+    wsctx->carrylen = 0;
80465d
+  } else {
80465d
+    /* carry over remaining, non-multiple-of-four bytes */
80465d
+    wsctx->carrylen = toDecode - (i * 4);
80465d
+    if (wsctx->carrylen < 0 || wsctx->carrylen > ARRAYSIZE(wsctx->carryBuf)) {
80465d
+      rfbErr("%s: internal error, invalid carry over size: carrylen=%d, toDecode=%d, i=%d", __func__, wsctx->carrylen, toDecode, i);
80465d
+      *sockRet = -1;
80465d
+      errno = EIO;
80465d
+      return WS_HYBI_STATE_ERR;
80465d
+    }
80465d
+    rfbLog("carrying over %d bytes from %p to %p\n", wsctx->carrylen, wsctx->writePos + (i * 4), wsctx->carryBuf);
80465d
+    memcpy(wsctx->carryBuf, data + (i * 4), wsctx->carrylen);
80465d
+  }
80465d
+
80465d
+  toReturn = toDecode - wsctx->carrylen;
80465d
+
80465d
+  switch (wsctx->header.opcode) {
80465d
+    case WS_OPCODE_CLOSE:
80465d
+
80465d
+      /* this data is not returned as payload data */
80465d
+      if (hybiWsFrameComplete(wsctx)) {
80465d
+        rfbLog("got closure, reason %d\n", WS_NTOH16(((uint16_t *)data)[0]));
80465d
+        errno = ECONNRESET;
80465d
+        *sockRet = -1;
80465d
+        return WS_HYBI_STATE_FRAME_COMPLETE;
80465d
+      } else {
80465d
+        rfbErr("%s: close reason with long frame not supported", __func__);
80465d
+        errno = EIO;
80465d
+        *sockRet = -1;
80465d
+        return WS_HYBI_STATE_ERR;
80465d
+      }
80465d
+      break;
80465d
+    case WS_OPCODE_TEXT_FRAME:
80465d
+      data[toReturn] = '\0';
80465d
+      rfbLog("Initiate Base64 decoding in %p with max size %d and '\\0' at %p\n", data, bufsize, data + toReturn);
80465d
+      if (-1 == (wsctx->readlen = __b64_pton((char *)data, data, bufsize))) {
80465d
+        rfbErr("Base64 decode error in %s; data=%p bufsize=%d", __func__, data, bufsize);
80465d
+        rfbErr("%s: Base64 decode error; %m\n", __func__);
80465d
+      }
80465d
+      wsctx->writePos = hybiPayloadStart(wsctx);
80465d
+      break;
80465d
+    case WS_OPCODE_BINARY_FRAME:
80465d
+      wsctx->readlen = toReturn;
80465d
+      wsctx->writePos = hybiPayloadStart(wsctx);
80465d
+      break;
80465d
+    default:
80465d
+      rfbErr("%s: unhandled opcode %d, b0: %02x, b1: %02x\n", __func__, (int)wsctx->header.opcode, wsctx->header.data->b0, wsctx->header.data->b1);
80465d
+  }
80465d
+  wsctx->readPos = data;
80465d
+
80465d
+  return hybiReturnData(dst, len, wsctx, sockRet);
80465d
+}
80465d
+
80465d
+/**
80465d
+ * Read function for websocket-socket emulation.
80465d
+ *
80465d
+ *    0                   1                   2                   3
80465d
+ *    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
80465d
+ *   +-+-+-+-+-------+-+-------------+-------------------------------+
80465d
+ *   |F|R|R|R| opcode|M| Payload len |    Extended payload length    |
80465d
+ *   |I|S|S|S|  (4)  |A|     (7)     |             (16/64)           |
80465d
+ *   |N|V|V|V|       |S|             |   (if payload len==126/127)   |
80465d
+ *   | |1|2|3|       |K|             |                               |
80465d
+ *   +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
80465d
+ *   |     Extended payload length continued, if payload len == 127  |
80465d
+ *   + - - - - - - - - - - - - - - - +-------------------------------+
80465d
+ *   |                               |Masking-key, if MASK set to 1  |
80465d
+ *   +-------------------------------+-------------------------------+
80465d
+ *   | Masking-key (continued)       |          Payload Data         |
80465d
+ *   +-------------------------------- - - - - - - - - - - - - - - - +
80465d
+ *   :                     Payload Data continued ...                :
80465d
+ *   + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
80465d
+ *   |                     Payload Data continued ...                |
80465d
+ *   +---------------------------------------------------------------+
80465d
+ *
80465d
+ * Using the decode buffer, this function:
80465d
+ *  - reads the complete header from the underlying socket
80465d
+ *  - reads any remaining data bytes
80465d
+ *  - unmasks the payload data using the provided mask
80465d
+ *  - decodes Base64 encoded text data
80465d
+ *  - copies len bytes of decoded payload data into dst
80465d
+ *
80465d
+ * Emulates a read call on a socket.
80465d
+ */
80465d
+static int
80465d
+webSocketsDecodeHybi(rfbClientPtr cl, char *dst, int len)
80465d
+{
80465d
+    int result = -1;
80465d
+    ws_ctx_t *wsctx = (ws_ctx_t *)cl->wsctx;
80465d
+    /* int fin; */ /* not used atm */
80465d
+
80465d
+    /* rfbLog(" <== %s[%d]: %d cl: %p, wsctx: %p-%p (%d)\n", __func__, gettid(), len, cl, wsctx, (char *)wsctx + sizeof(ws_ctx_t), sizeof(ws_ctx_t)); */
80465d
+    rfbLog("%s_enter: len=%d; "
80465d
+                      "CTX: readlen=%d readPos=%p "
80465d
+                      "writeTo=%p "
80465d
+                      "state=%d toRead=%d remaining=%d "
80465d
+                      " nReadRaw=%d carrylen=%d carryBuf=%p\n",
80465d
+                      __func__, len,
80465d
+                      wsctx->readlen, wsctx->readPos,
80465d
+                      wsctx->writePos,
80465d
+                      wsctx->hybiDecodeState, wsctx->nToRead, hybiRemaining(wsctx),
80465d
+                      wsctx->nReadRaw, wsctx->carrylen, wsctx->carryBuf);
80465d
+
80465d
+    switch (wsctx->hybiDecodeState){
80465d
+      case WS_HYBI_STATE_HEADER_PENDING:
80465d
+        wsctx->hybiDecodeState = hybiReadHeader(cl, &result);
80465d
+        if (wsctx->hybiDecodeState == WS_HYBI_STATE_ERR) {
80465d
+          goto spor;
80465d
+        }
80465d
+        if (wsctx->hybiDecodeState != WS_HYBI_STATE_HEADER_PENDING) {
80465d
+
80465d
+          /* when header is complete, try to read some more data */
80465d
+          wsctx->hybiDecodeState = hybiReadAndDecode(cl, dst, len, &result);
80465d
+        }
80465d
+        break;
80465d
+      case WS_HYBI_STATE_DATA_AVAILABLE:
80465d
+        wsctx->hybiDecodeState = hybiReturnData(dst, len, wsctx, &result);
80465d
+        break;
80465d
+      case WS_HYBI_STATE_DATA_NEEDED:
80465d
+        wsctx->hybiDecodeState = hybiReadAndDecode(cl, dst, len, &result);
80465d
+        break;
80465d
+      case WS_HYBI_STATE_CLOSE_REASON_PENDING:
80465d
+        wsctx->hybiDecodeState = hybiReadAndDecode(cl, dst, len, &result);
80465d
+        break;
80465d
       default:
80465d
-	rfbErr("%s: unhandled opcode %d, b0: %02x, b1: %02x\n", __func__, (int)opcode, header->b0, header->b1);
80465d
+        /* invalid state */
80465d
+        rfbErr("%s: called with invalid state %d\n", wsctx->hybiDecodeState);
80465d
+        result = -1;
80465d
+        errno = EIO;
80465d
+        wsctx->hybiDecodeState = WS_HYBI_STATE_ERR;
80465d
     }
80465d
 
80465d
     /* single point of return, if someone has questions :-) */
80465d
 spor:
80465d
     /* rfbLog("%s: ret: %d/%d\n", __func__, result, len); */
80465d
+    if (wsctx->hybiDecodeState == WS_HYBI_STATE_FRAME_COMPLETE) {
80465d
+      rfbLog("frame received successfully, cleaning up: read=%d hlen=%d plen=%d\n", wsctx->header.nRead, wsctx->header.headerLen, wsctx->header.payloadLen);
80465d
+      /* frame finished, cleanup state */
80465d
+      hybiDecodeCleanup(wsctx);
80465d
+    } else if (wsctx->hybiDecodeState == WS_HYBI_STATE_ERR) {
80465d
+      hybiDecodeCleanup(wsctx);
80465d
+    }
80465d
+    rfbLog("%s_exit: len=%d; "
80465d
+                      "CTX: readlen=%d readPos=%p "
80465d
+                      "writePos=%p "
80465d
+                      "state=%d toRead=%d remaining=%d "
80465d
+                      "nRead=%d carrylen=%d carryBuf=%p "
80465d
+                      "result=%d\n",
80465d
+                      __func__, len,
80465d
+                      wsctx->readlen, wsctx->readPos,
80465d
+                      wsctx->writePos,
80465d
+                      wsctx->hybiDecodeState, wsctx->nToRead, hybiRemaining(wsctx),
80465d
+                      wsctx->nReadRaw, wsctx->carrylen, wsctx->carryBuf,
80465d
+                      result);
80465d
     return result;
80465d
 }
80465d
 
80465d
@@ -924,7 +1255,7 @@ webSocketsHasDataInBuffer(rfbClientPtr c
80465d
 {
80465d
     ws_ctx_t *wsctx = (ws_ctx_t *)cl->wsctx;
80465d
 
80465d
-    if (wsctx && wsctx->readbuflen)
80465d
+    if (wsctx && wsctx->readlen)
80465d
       return TRUE;
80465d
 
80465d
     return (cl->sslctx && rfbssl_pending(cl) > 0);