websockets: Initial WebSockets support.

Has a bug: WebSocket client disconnects are not detected.
rfbSendFramebufferUpdate is doing a MSG_PEEK recv to determine if
enough data is available which prevents a disconnect from being
detected.

Otherwise it's working pretty well.

[jes: moved added struct members to the end for binary compatibility with
previous LibVNCServer versions, removed an unused variable]

Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de>
pull/1/head
Joel Martin 13 years ago committed by Johannes Schindelin
parent 353b35e86a
commit 6fac22a74b

@ -25,6 +25,14 @@ AC_ARG_WITH(tightvnc-filetransfer,
, [ with_tightvnc_filetransfer=yes ])
# AC_DEFINE moved to after libpthread check.
# WebSockets support
AC_CHECK_LIB(resolv, __b64_ntop, HAVE_B64="true", HAVE_B64="false")
AH_TEMPLATE(WITH_WEBSOCKETS, [Disable WebSockets support])
AC_ARG_WITH(websockets,
[ --without-websockets disable WebSockets support],
, [ with_websockets=yes ])
# AC_DEFINE moved to after libresolve check.
AH_TEMPLATE(ALLOW24BPP, [Enable 24 bit per pixel in native framebuffer])
AC_ARG_WITH(24bpp,
[ --without-24bpp disable 24 bpp framebuffers],
@ -301,6 +309,7 @@ elif test "x$uname_s" = "xDarwin"; then
fi
AH_TEMPLATE(HAVE_LIBCRYPT, [libcrypt library present])
AC_ARG_WITH(crypt,
[ --without-crypt disable support for libcrypt],,)
@ -706,6 +715,16 @@ if test "x$with_tightvnc_filetransfer" = "xyes"; then
fi
AM_CONDITIONAL(WITH_TIGHTVNC_FILETRANSFER, test "$with_tightvnc_filetransfer" = "yes")
# websockets implemented using base64 from resolve
if test "x$HAVE_B64" != "xtrue"; then
with_websockets=""
fi
if test "x$with_websockets" = "xyes"; then
LIBS="$LIBS -lresolv"
AC_DEFINE(WITH_WEBSOCKETS)
fi
AM_CONDITIONAL(WITH_WEBSOCKETS, test "$with_websockets" = "yes")
AM_CONDITIONAL(HAVE_LIBZ, test ! -z "$HAVE_ZLIB_H")
AM_CONDITIONAL(HAVE_LIBJPEG, test ! -z "$HAVE_JPEGLIB_H")
AM_CONDITIONAL(HAVE_LIBPNG, test ! -z "$HAVE_PNGLIB_H")

@ -12,6 +12,10 @@ TIGHTVNCFILETRANSFERSRCS = tightvnc-filetransfer/rfbtightserver.c \
tightvnc-filetransfer/filelistinfo.c
endif
if WITH_WEBSOCKETS
WEBSOCKETSSRCS = websockets.c md5.c
endif
includedir=$(prefix)/include/rfb
#include_HEADERS=rfb.h rfbconfig.h rfbint.h rfbproto.h keysym.h rfbregion.h
@ -37,7 +41,7 @@ endif
endif
endif
LIB_SRCS = main.c rfbserver.c rfbregion.c auth.c sockets.c \
LIB_SRCS = main.c rfbserver.c rfbregion.c auth.c sockets.c $(WEBSOCKETSSRCS) \
stats.c corre.c hextile.c rre.c translate.c cutpaste.c \
httpd.c cursor.c font.c \
draw.c selbox.c ../common/d3des.c ../common/vncauth.c cargs.c ../common/minilzo.c ultra.c scale.c \

@ -0,0 +1,448 @@
/* Functions to compute MD5 message digest of files or memory blocks.
according to the definition of MD5 in RFC 1321 from April 1992.
Copyright (C) 1995,1996,1997,1999,2000,2001,2005
Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
/* Written by Ulrich Drepper <drepper@gnu.ai.mit.edu>, 1995. */
#include <sys/types.h>
# include <stdlib.h>
# include <string.h>
#include "md5.h"
#ifdef _LIBC
# include <endian.h>
# if __BYTE_ORDER == __BIG_ENDIAN
# define WORDS_BIGENDIAN 1
# endif
/* We need to keep the namespace clean so define the MD5 function
protected using leading __ . */
# define md5_init_ctx __md5_init_ctx
# define md5_process_block __md5_process_block
# define md5_process_bytes __md5_process_bytes
# define md5_finish_ctx __md5_finish_ctx
# define md5_read_ctx __md5_read_ctx
# define md5_stream __md5_stream
# define md5_buffer __md5_buffer
#endif
#ifdef WORDS_BIGENDIAN
# define SWAP(n) \
(((n) << 24) | (((n) & 0xff00) << 8) | (((n) >> 8) & 0xff00) | ((n) >> 24))
#else
# define SWAP(n) (n)
#endif
/* This array contains the bytes used to pad the buffer to the next
64-byte boundary. (RFC 1321, 3.1: Step 1) */
static const unsigned char fillbuf[64] = { 0x80, 0 /* , 0, 0, ... */ };
/* Initialize structure containing state of computation.
(RFC 1321, 3.3: Step 3) */
void
md5_init_ctx (ctx)
struct md5_ctx *ctx;
{
ctx->A = 0x67452301;
ctx->B = 0xefcdab89;
ctx->C = 0x98badcfe;
ctx->D = 0x10325476;
ctx->total[0] = ctx->total[1] = 0;
ctx->buflen = 0;
}
/* Put result from CTX in first 16 bytes following RESBUF. The result
must be in little endian byte order.
IMPORTANT: On some systems it is required that RESBUF is correctly
aligned for a 32 bits value. */
void *
md5_read_ctx (ctx, resbuf)
const struct md5_ctx *ctx;
void *resbuf;
{
((md5_uint32 *) resbuf)[0] = SWAP (ctx->A);
((md5_uint32 *) resbuf)[1] = SWAP (ctx->B);
((md5_uint32 *) resbuf)[2] = SWAP (ctx->C);
((md5_uint32 *) resbuf)[3] = SWAP (ctx->D);
return resbuf;
}
/* Process the remaining bytes in the internal buffer and the usual
prolog according to the standard and write the result to RESBUF.
IMPORTANT: On some systems it is required that RESBUF is correctly
aligned for a 32 bits value. */
void *
md5_finish_ctx (ctx, resbuf)
struct md5_ctx *ctx;
void *resbuf;
{
/* Take yet unprocessed bytes into account. */
md5_uint32 bytes = ctx->buflen;
size_t pad;
/* Now count remaining bytes. */
ctx->total[0] += bytes;
if (ctx->total[0] < bytes)
++ctx->total[1];
pad = bytes >= 56 ? 64 + 56 - bytes : 56 - bytes;
memcpy (&ctx->buffer[bytes], fillbuf, pad);
/* Put the 64-bit file length in *bits* at the end of the buffer. */
*(md5_uint32 *) &ctx->buffer[bytes + pad] = SWAP (ctx->total[0] << 3);
*(md5_uint32 *) &ctx->buffer[bytes + pad + 4] = SWAP ((ctx->total[1] << 3) |
(ctx->total[0] >> 29));
/* Process last bytes. */
md5_process_block (ctx->buffer, bytes + pad + 8, ctx);
return md5_read_ctx (ctx, resbuf);
}
/* Compute MD5 message digest for bytes read from STREAM. The
resulting message digest number will be written into the 16 bytes
beginning at RESBLOCK. */
int
md5_stream (stream, resblock)
FILE *stream;
void *resblock;
{
/* Important: BLOCKSIZE must be a multiple of 64. */
#define BLOCKSIZE 4096
struct md5_ctx ctx;
char buffer[BLOCKSIZE + 72];
size_t sum;
/* Initialize the computation context. */
md5_init_ctx (&ctx);
/* Iterate over full file contents. */
while (1)
{
/* We read the file in blocks of BLOCKSIZE bytes. One call of the
computation function processes the whole buffer so that with the
next round of the loop another block can be read. */
size_t n;
sum = 0;
/* Read block. Take care for partial reads. */
do
{
n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);
sum += n;
}
while (sum < BLOCKSIZE && n != 0);
if (n == 0 && ferror (stream))
return 1;
/* If end of file is reached, end the loop. */
if (n == 0)
break;
/* Process buffer with BLOCKSIZE bytes. Note that
BLOCKSIZE % 64 == 0
*/
md5_process_block (buffer, BLOCKSIZE, &ctx);
}
/* Add the last bytes if necessary. */
if (sum > 0)
md5_process_bytes (buffer, sum, &ctx);
/* Construct result in desired memory. */
md5_finish_ctx (&ctx, resblock);
return 0;
}
/* Compute MD5 message digest for LEN bytes beginning at BUFFER. The
result is always in little endian byte order, so that a byte-wise
output yields to the wanted ASCII representation of the message
digest. */
void *
md5_buffer (buffer, len, resblock)
const char *buffer;
size_t len;
void *resblock;
{
struct md5_ctx ctx;
/* Initialize the computation context. */
md5_init_ctx (&ctx);
/* Process whole buffer but last len % 64 bytes. */
md5_process_bytes (buffer, len, &ctx);
/* Put result in desired memory area. */
return md5_finish_ctx (&ctx, resblock);
}
void
md5_process_bytes (buffer, len, ctx)
const void *buffer;
size_t len;
struct md5_ctx *ctx;
{
/* When we already have some bits in our internal buffer concatenate
both inputs first. */
if (ctx->buflen != 0)
{
size_t left_over = ctx->buflen;
size_t add = 128 - left_over > len ? len : 128 - left_over;
memcpy (&ctx->buffer[left_over], buffer, add);
ctx->buflen += add;
if (ctx->buflen > 64)
{
md5_process_block (ctx->buffer, ctx->buflen & ~63, ctx);
ctx->buflen &= 63;
/* The regions in the following copy operation cannot overlap. */
memcpy (ctx->buffer, &ctx->buffer[(left_over + add) & ~63],
ctx->buflen);
}
buffer = (const char *) buffer + add;
len -= add;
}
/* Process available complete blocks. */
if (len >= 64)
{
#if !_STRING_ARCH_unaligned
/* To check alignment gcc has an appropriate operator. Other
compilers don't. */
# if __GNUC__ >= 2
# define UNALIGNED_P(p) (((md5_uintptr) p) % __alignof__ (md5_uint32) != 0)
# else
# define UNALIGNED_P(p) (((md5_uintptr) p) % sizeof (md5_uint32) != 0)
# endif
if (UNALIGNED_P (buffer))
while (len > 64)
{
md5_process_block (memcpy (ctx->buffer, buffer, 64), 64, ctx);
buffer = (const char *) buffer + 64;
len -= 64;
}
else
#endif
{
md5_process_block (buffer, len & ~63, ctx);
buffer = (const char *) buffer + (len & ~63);
len &= 63;
}
}
/* Move remaining bytes in internal buffer. */
if (len > 0)
{
size_t left_over = ctx->buflen;
memcpy (&ctx->buffer[left_over], buffer, len);
left_over += len;
if (left_over >= 64)
{
md5_process_block (ctx->buffer, 64, ctx);
left_over -= 64;
memcpy (ctx->buffer, &ctx->buffer[64], left_over);
}
ctx->buflen = left_over;
}
}
/* These are the four functions used in the four steps of the MD5 algorithm
and defined in the RFC 1321. The first function is a little bit optimized
(as found in Colin Plumbs public domain implementation). */
/* #define FF(b, c, d) ((b & c) | (~b & d)) */
#define FF(b, c, d) (d ^ (b & (c ^ d)))
#define FG(b, c, d) FF (d, b, c)
#define FH(b, c, d) (b ^ c ^ d)
#define FI(b, c, d) (c ^ (b | ~d))
/* Process LEN bytes of BUFFER, accumulating context into CTX.
It is assumed that LEN % 64 == 0. */
void
md5_process_block (buffer, len, ctx)
const void *buffer;
size_t len;
struct md5_ctx *ctx;
{
md5_uint32 correct_words[16];
const md5_uint32 *words = buffer;
size_t nwords = len / sizeof (md5_uint32);
const md5_uint32 *endp = words + nwords;
md5_uint32 A = ctx->A;
md5_uint32 B = ctx->B;
md5_uint32 C = ctx->C;
md5_uint32 D = ctx->D;
/* First increment the byte count. RFC 1321 specifies the possible
length of the file up to 2^64 bits. Here we only compute the
number of bytes. Do a double word increment. */
ctx->total[0] += len;
if (ctx->total[0] < len)
++ctx->total[1];
/* Process all bytes in the buffer with 64 bytes in each round of
the loop. */
while (words < endp)
{
md5_uint32 *cwp = correct_words;
md5_uint32 A_save = A;
md5_uint32 B_save = B;
md5_uint32 C_save = C;
md5_uint32 D_save = D;
/* First round: using the given function, the context and a constant
the next context is computed. Because the algorithms processing
unit is a 32-bit word and it is determined to work on words in
little endian byte order we perhaps have to change the byte order
before the computation. To reduce the work for the next steps
we store the swapped words in the array CORRECT_WORDS. */
#define OP(a, b, c, d, s, T) \
do \
{ \
a += FF (b, c, d) + (*cwp++ = SWAP (*words)) + T; \
++words; \
CYCLIC (a, s); \
a += b; \
} \
while (0)
/* It is unfortunate that C does not provide an operator for
cyclic rotation. Hope the C compiler is smart enough. */
#define CYCLIC(w, s) (w = (w << s) | (w >> (32 - s)))
/* Before we start, one word to the strange constants.
They are defined in RFC 1321 as
T[i] = (int) (4294967296.0 * fabs (sin (i))), i=1..64
*/
/* Round 1. */
OP (A, B, C, D, 7, 0xd76aa478);
OP (D, A, B, C, 12, 0xe8c7b756);
OP (C, D, A, B, 17, 0x242070db);
OP (B, C, D, A, 22, 0xc1bdceee);
OP (A, B, C, D, 7, 0xf57c0faf);
OP (D, A, B, C, 12, 0x4787c62a);
OP (C, D, A, B, 17, 0xa8304613);
OP (B, C, D, A, 22, 0xfd469501);
OP (A, B, C, D, 7, 0x698098d8);
OP (D, A, B, C, 12, 0x8b44f7af);
OP (C, D, A, B, 17, 0xffff5bb1);
OP (B, C, D, A, 22, 0x895cd7be);
OP (A, B, C, D, 7, 0x6b901122);
OP (D, A, B, C, 12, 0xfd987193);
OP (C, D, A, B, 17, 0xa679438e);
OP (B, C, D, A, 22, 0x49b40821);
/* For the second to fourth round we have the possibly swapped words
in CORRECT_WORDS. Redefine the macro to take an additional first
argument specifying the function to use. */
#undef OP
#define OP(f, a, b, c, d, k, s, T) \
do \
{ \
a += f (b, c, d) + correct_words[k] + T; \
CYCLIC (a, s); \
a += b; \
} \
while (0)
/* Round 2. */
OP (FG, A, B, C, D, 1, 5, 0xf61e2562);
OP (FG, D, A, B, C, 6, 9, 0xc040b340);
OP (FG, C, D, A, B, 11, 14, 0x265e5a51);
OP (FG, B, C, D, A, 0, 20, 0xe9b6c7aa);
OP (FG, A, B, C, D, 5, 5, 0xd62f105d);
OP (FG, D, A, B, C, 10, 9, 0x02441453);
OP (FG, C, D, A, B, 15, 14, 0xd8a1e681);
OP (FG, B, C, D, A, 4, 20, 0xe7d3fbc8);
OP (FG, A, B, C, D, 9, 5, 0x21e1cde6);
OP (FG, D, A, B, C, 14, 9, 0xc33707d6);
OP (FG, C, D, A, B, 3, 14, 0xf4d50d87);
OP (FG, B, C, D, A, 8, 20, 0x455a14ed);
OP (FG, A, B, C, D, 13, 5, 0xa9e3e905);
OP (FG, D, A, B, C, 2, 9, 0xfcefa3f8);
OP (FG, C, D, A, B, 7, 14, 0x676f02d9);
OP (FG, B, C, D, A, 12, 20, 0x8d2a4c8a);
/* Round 3. */
OP (FH, A, B, C, D, 5, 4, 0xfffa3942);
OP (FH, D, A, B, C, 8, 11, 0x8771f681);
OP (FH, C, D, A, B, 11, 16, 0x6d9d6122);
OP (FH, B, C, D, A, 14, 23, 0xfde5380c);
OP (FH, A, B, C, D, 1, 4, 0xa4beea44);
OP (FH, D, A, B, C, 4, 11, 0x4bdecfa9);
OP (FH, C, D, A, B, 7, 16, 0xf6bb4b60);
OP (FH, B, C, D, A, 10, 23, 0xbebfbc70);
OP (FH, A, B, C, D, 13, 4, 0x289b7ec6);
OP (FH, D, A, B, C, 0, 11, 0xeaa127fa);
OP (FH, C, D, A, B, 3, 16, 0xd4ef3085);
OP (FH, B, C, D, A, 6, 23, 0x04881d05);
OP (FH, A, B, C, D, 9, 4, 0xd9d4d039);
OP (FH, D, A, B, C, 12, 11, 0xe6db99e5);
OP (FH, C, D, A, B, 15, 16, 0x1fa27cf8);
OP (FH, B, C, D, A, 2, 23, 0xc4ac5665);
/* Round 4. */
OP (FI, A, B, C, D, 0, 6, 0xf4292244);
OP (FI, D, A, B, C, 7, 10, 0x432aff97);
OP (FI, C, D, A, B, 14, 15, 0xab9423a7);
OP (FI, B, C, D, A, 5, 21, 0xfc93a039);
OP (FI, A, B, C, D, 12, 6, 0x655b59c3);
OP (FI, D, A, B, C, 3, 10, 0x8f0ccc92);
OP (FI, C, D, A, B, 10, 15, 0xffeff47d);
OP (FI, B, C, D, A, 1, 21, 0x85845dd1);
OP (FI, A, B, C, D, 8, 6, 0x6fa87e4f);
OP (FI, D, A, B, C, 15, 10, 0xfe2ce6e0);
OP (FI, C, D, A, B, 6, 15, 0xa3014314);
OP (FI, B, C, D, A, 13, 21, 0x4e0811a1);
OP (FI, A, B, C, D, 4, 6, 0xf7537e82);
OP (FI, D, A, B, C, 11, 10, 0xbd3af235);
OP (FI, C, D, A, B, 2, 15, 0x2ad7d2bb);
OP (FI, B, C, D, A, 9, 21, 0xeb86d391);
/* Add the starting values of the context. */
A += A_save;
B += B_save;
C += C_save;
D += D_save;
}
/* Put checksum in context given as argument. */
ctx->A = A;
ctx->B = B;
ctx->C = C;
ctx->D = D;
}

@ -0,0 +1,148 @@
/* Declaration of functions and data types used for MD5 sum computing
library functions.
Copyright (C) 1995-1997,1999,2000,2001,2004,2005
Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#ifndef _MD5_H
#define _MD5_H 1
#include <stdio.h>
#if defined HAVE_LIMITS_H || _LIBC
# include <limits.h>
#endif
#define MD5_DIGEST_SIZE 16
#define MD5_BLOCK_SIZE 64
/* The following contortions are an attempt to use the C preprocessor
to determine an unsigned integral type that is 32 bits wide. An
alternative approach is to use autoconf's AC_CHECK_SIZEOF macro, but
doing that would require that the configure script compile and *run*
the resulting executable. Locally running cross-compiled executables
is usually not possible. */
#ifdef _LIBC
# include <stdint.h>
typedef uint32_t md5_uint32;
typedef uintptr_t md5_uintptr;
#else
# if defined __STDC__ && __STDC__
# define UINT_MAX_32_BITS 4294967295U
# else
# define UINT_MAX_32_BITS 0xFFFFFFFF
# endif
/* If UINT_MAX isn't defined, assume it's a 32-bit type.
This should be valid for all systems GNU cares about because
that doesn't include 16-bit systems, and only modern systems
(that certainly have <limits.h>) have 64+-bit integral types. */
# ifndef UINT_MAX
# define UINT_MAX UINT_MAX_32_BITS
# endif
# if UINT_MAX == UINT_MAX_32_BITS
typedef unsigned int md5_uint32;
# else
# if USHRT_MAX == UINT_MAX_32_BITS
typedef unsigned short md5_uint32;
# else
# if ULONG_MAX == UINT_MAX_32_BITS
typedef unsigned long md5_uint32;
# else
/* The following line is intended to evoke an error.
Using #error is not portable enough. */
"Cannot determine unsigned 32-bit data type."
# endif
# endif
# endif
/* We have to make a guess about the integer type equivalent in size
to pointers which should always be correct. */
typedef unsigned long int md5_uintptr;
#endif
/* Structure to save state of computation between the single steps. */
struct md5_ctx
{
md5_uint32 A;
md5_uint32 B;
md5_uint32 C;
md5_uint32 D;
md5_uint32 total[2];
md5_uint32 buflen;
char buffer[128] __attribute__ ((__aligned__ (__alignof__ (md5_uint32))));
};
/*
* The following three functions are build up the low level used in
* the functions `md5_stream' and `md5_buffer'.
*/
/* Initialize structure containing state of computation.
(RFC 1321, 3.3: Step 3) */
extern void __md5_init_ctx (struct md5_ctx *ctx) __THROW;
/* Starting with the result of former calls of this function (or the
initialization function update the context for the next LEN bytes
starting at BUFFER.
It is necessary that LEN is a multiple of 64!!! */
extern void __md5_process_block (const void *buffer, size_t len,
struct md5_ctx *ctx) __THROW;
/* Starting with the result of former calls of this function (or the
initialization function update the context for the next LEN bytes
starting at BUFFER.
It is NOT required that LEN is a multiple of 64. */
extern void __md5_process_bytes (const void *buffer, size_t len,
struct md5_ctx *ctx) __THROW;
/* Process the remaining bytes in the buffer and put result from CTX
in first 16 bytes following RESBUF. The result is always in little
endian byte order, so that a byte-wise output yields to the wanted
ASCII representation of the message digest.
IMPORTANT: On some systems it is required that RESBUF is correctly
aligned for a 32 bits value. */
extern void *__md5_finish_ctx (struct md5_ctx *ctx, void *resbuf) __THROW;
/* Put result from CTX in first 16 bytes following RESBUF. The result is
always in little endian byte order, so that a byte-wise output yields
to the wanted ASCII representation of the message digest.
IMPORTANT: On some systems it is required that RESBUF is correctly
aligned for a 32 bits value. */
extern void *__md5_read_ctx (const struct md5_ctx *ctx, void *resbuf) __THROW;
/* Compute MD5 message digest for bytes read from STREAM. The
resulting message digest number will be written into the 16 bytes
beginning at RESBLOCK. */
extern int __md5_stream (FILE *stream, void *resblock) __THROW;
/* Compute MD5 message digest for LEN bytes beginning at BUFFER. The
result is always in little endian byte order, so that a byte-wise
output yields to the wanted ASCII representation of the message
digest. */
extern void *__md5_buffer (const char *buffer, size_t len,
void *resblock) __THROW;
#endif /* md5.h */

@ -358,6 +358,14 @@ rfbNewTCPOrUDPClient(rfbScreenInfoPtr rfbScreen,
rfbScreen->clientHead = cl;
UNLOCK(rfbClientListMutex);
#ifdef LIBVNCSERVER_WITH_WEBSOCKETS
cl->webSockets = FALSE;
cl->webSocketsSSL = FALSE;
cl->webSocketsBase64 = FALSE;
cl->dblen= 0;
cl->carrylen = 0;
#endif
#if defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG)
cl->tightQualityLevel = -1;
#if defined(LIBVNCSERVER_HAVE_LIBJPEG) || defined(LIBVNCSERVER_HAVE_LIBPNG)
@ -404,6 +412,20 @@ rfbNewTCPOrUDPClient(rfbScreenInfoPtr rfbScreen,
cl->lastPtrX = -1;
#ifdef LIBVNCSERVER_WITH_WEBSOCKETS
/*
* Wait a few ms for the client to send one of:
* - Flash policy request
* - WebSockets connection (TLS/SSL or plain)
*/
if (!webSocketsCheck(cl)) {
/* Error reporting handled in webSocketsHandshake */
rfbCloseClient(cl);
rfbClientConnectionGone(cl);
return NULL;
}
#endif
sprintf(pv,rfbProtocolVersionFormat,rfbScreen->protocolMajorVersion,
rfbScreen->protocolMinorVersion);
@ -1817,6 +1839,16 @@ rfbProcessClientNormalMessage(rfbClientPtr cl)
char encBuf[64];
char encBuf2[64];
#ifdef LIBVNCSERVER_WITH_WEBSOCKETS
if (cl->webSockets && cl->webSocketsBase64) {
/* With Base64 encoding we need at least 4 bytes */
n = recv(cl->sock, encBuf, 4, MSG_PEEK);
if ((n > 0) && (n < 4)) {
return;
}
}
#endif
if ((n = rfbReadExact(cl, (char *)&msg, 1)) <= 0) {
if (n != 0)
rfbLogPerror("rfbProcessClientNormalMessage: read");
@ -2904,7 +2936,6 @@ rfbSendFramebufferUpdate(rfbClientPtr cl,
#endif
#ifdef LIBVNCSERVER_HAVE_LIBPNG
case rfbEncodingTightPng:
/* TODO */
if (!rfbSendRectEncodingTightPng(cl, x, y, w, h))
goto updateFailed;
break;

@ -457,7 +457,15 @@ rfbReadExactTimeout(rfbClientPtr cl, char* buf, int len, int timeout)
struct timeval tv;
while (len > 0) {
#ifdef LIBVNCSERVER_WITH_WEBSOCKETS
if (cl->webSockets) {
n = webSocketsDecode(cl, buf, len);
} else {
n = read(sock, buf, len);
}
#else
n = read(sock, buf, len);
#endif
if (n > 0) {
@ -517,6 +525,71 @@ int rfbReadExact(rfbClientPtr cl,char* buf,int len)
return(rfbReadExactTimeout(cl,buf,len,rfbMaxClientWait));
}
/*
* PeekExact peeks at an exact number of bytes from a client. Returns 1 if
* those bytes have been read, 0 if the other end has closed, or -1 if an
* error occurred (errno is set to ETIMEDOUT if it timed out).
*/
int
rfbPeekExactTimeout(rfbClientPtr cl, char* buf, int len, int timeout)
{
int sock = cl->sock;
int n;
fd_set fds;
struct timeval tv;
while (len > 0) {
n = recv(sock, buf, len, MSG_PEEK);
if (n == len) {
break;
} else if (n == 0) {
return 0;
} else {
#ifdef WIN32
errno = WSAGetLastError();
#endif
if (errno == EINTR)
continue;
#ifdef LIBVNCSERVER_ENOENT_WORKAROUND
if (errno != ENOENT)
#endif
if (errno != EWOULDBLOCK && errno != EAGAIN) {
return n;
}
FD_ZERO(&fds);
FD_SET(sock, &fds);
tv.tv_sec = timeout / 1000;
tv.tv_usec = (timeout % 1000) * 1000;
n = select(sock+1, &fds, NULL, &fds, &tv);
if (n < 0) {
rfbLogPerror("ReadExact: select");
return n;
}
if (n == 0) {
errno = ETIMEDOUT;
return -1;
}
}
}
#undef DEBUG_READ_EXACT
#ifdef DEBUG_READ_EXACT
rfbLog("ReadExact %d bytes\n",len);
for(n=0;n<len;n++)
fprintf(stderr,"%02x ",(unsigned char)buf[n]);
fprintf(stderr,"\n");
#endif
return 1;
}
/*
* WriteExact writes an exact number of bytes to a client. Returns 1 if
* those bytes have been written, or -1 if an error occurred (errno is set to
@ -543,6 +616,16 @@ rfbWriteExact(rfbClientPtr cl,
fprintf(stderr,"\n");
#endif
#ifdef LIBVNCSERVER_WITH_WEBSOCKETS
if (cl->webSockets) {
if ((len = webSocketsEncode(cl, buf, len)) < 0) {
rfbErr("WriteExact: WebSockets encode error\n");
return -1;
}
buf = cl->encodeBuf;
}
#endif
LOCK(cl->outputMutex);
while (len > 0) {
n = write(sock, buf, len);

@ -0,0 +1,448 @@
/*
* websockets.c - deal with WebSockets clients.
*
* This code should be independent of any changes in the RFB protocol. It is
* an additional handshake and framing of normal sockets:
* http://www.whatwg.org/specs/web-socket-protocol/
*
*/
/*
* Copyright (C) 2010 Joel Martin
*
* 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
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
* USA.
*/
#include <rfb/rfb.h>
#include <resolv.h> /* __b64_ntop */
/* errno */
#include <errno.h>
#include <md5.h>
#define FLASH_POLICY_RESPONSE "<cross-domain-policy><allow-access-from domain=\"*\" to-ports=\"*\" /></cross-domain-policy>\n"
#define SZ_FLASH_POLICY_RESPONSE 93
#define WEBSOCKETS_HANDSHAKE_RESPONSE "HTTP/1.1 101 Web Socket Protocol Handshake\r\n\
Upgrade: WebSocket\r\n\
Connection: Upgrade\r\n\
%sWebSocket-Origin: %s\r\n\
%sWebSocket-Location: %s://%s%s\r\n\
%sWebSocket-Protocol: sample\r\n\
\r\n%s"
#define WEBSOCKETS_CLIENT_CONNECT_WAIT_MS 100
#define WEBSOCKETS_CLIENT_SEND_WAIT_MS 20
#define WEBSOCKETS_MAX_HANDSHAKE_LEN 4096
#if defined(__linux__) && defined(NEED_TIMEVAL)
struct timeval
{
long int tv_sec,tv_usec;
}
;
#endif
static rfbBool webSocketsHandshake(rfbClientPtr cl, char *scheme);
void webSocketsGenMd5(char * target, char *key1, char *key2, char *key3);
static int
min (int a, int b) {
return a < b ? a : b;
}
/*
* rfbWebSocketsHandshake is called to handle new WebSockets connections
*/
rfbBool
webSocketsCheck (rfbClientPtr cl)
{
char bbuf[4], *scheme;
int ret;
ret = rfbPeekExactTimeout(cl, bbuf, 4,
WEBSOCKETS_CLIENT_CONNECT_WAIT_MS);
if ((ret < 0) && (errno == ETIMEDOUT)) {
rfbLog("Normal socket connection\n");
return TRUE;
} else if (ret <= 0) {
rfbErr("webSocketsHandshake: unknown connection error\n");
return FALSE;
}
if (strncmp(bbuf, "<", 1) == 0) {
rfbLog("Got Flash policy request, sending response\n");
if (rfbWriteExact(cl, FLASH_POLICY_RESPONSE,
SZ_FLASH_POLICY_RESPONSE) < 0) {
rfbErr("webSocketsHandshake: failed sending Flash policy response");
}
return FALSE;
} else if (strncmp(bbuf, "\x16", 1) == 0) {
cl->webSocketsSSL = TRUE;
rfbLog("Got TLS/SSL WebSockets connection\n");
scheme = "wss";
/* TODO */
/* bbuf = ... */
return FALSE;
} else {
cl->webSocketsSSL = FALSE;
scheme = "ws";
}
if (strncmp(bbuf, "GET ", 4) != 0) {
rfbErr("webSocketsHandshake: invalid client header\n");
return FALSE;
}
rfbLog("Got '%s' WebSockets handshake\n", scheme);
if (!webSocketsHandshake(cl, scheme)) {
return FALSE;
}
cl->webSockets = TRUE; /* Start WebSockets framing */
return TRUE;
}
static rfbBool
webSocketsHandshake(rfbClientPtr cl, char *scheme)
{
char *buf, *response, *line;
int n, linestart = 0, len = 0, llen;
char prefix[5], trailer[17];
char *path, *host, *origin;
char *key1 = NULL, *key2 = NULL, *key3 = NULL;
buf = (char *) malloc(WEBSOCKETS_MAX_HANDSHAKE_LEN);
if (!buf) {
rfbLogPerror("webSocketsHandshake: malloc");
return FALSE;
}
response = (char *) malloc(WEBSOCKETS_MAX_HANDSHAKE_LEN);
if (!response) {
free(buf);
rfbLogPerror("webSocketsHandshake: malloc");
return FALSE;
}
while (len < WEBSOCKETS_MAX_HANDSHAKE_LEN-1) {
if ((n = rfbReadExactTimeout(cl, buf+len, 1,
WEBSOCKETS_CLIENT_SEND_WAIT_MS)) <= 0) {
if ((n < 0) && (errno == ETIMEDOUT)) {
break;
}
if (n == 0)
rfbLog("webSocketsHandshake: client gone\n");
else
rfbLogPerror("webSocketsHandshake: read");
return FALSE;
}
len += 1;
llen = len - linestart;
if (((llen >= 2)) && (buf[len-1] == '\n')) {
line = buf+linestart;
if ((llen == 2) && ((strncmp("\r\n\r\n", buf+len-4, 4)) == 0)) {
if (key1 && key2) {
if ((n = rfbReadExact(cl, buf+len, 8)) <= 0) {
if ((n < 0) && (errno == ETIMEDOUT)) {
break;
}
if (n == 0)
rfbLog("webSocketsHandshake: client gone\n");
else
rfbLogPerror("webSocketsHandshake: read");
return FALSE;
}
rfbLog("Got key3\n");
key3 = buf+len;
len += 8;
} else {
buf[len] = '\0';
}
break;
} else if ((llen >= 16) && ((strncmp("GET ", line, min(llen,4))) == 0)) {
/* 16 = 4 ("GET ") + 1 ("/.*") + 11 (" HTTP/1.1\r\n") */
/* rfbLog("Got path\n"); */
path = line+4;
buf[len-11] = '\0'; /* Trim trailing " HTTP/1.1\r\n" */
if (strstr(path, "b64encode")) {
rfbLog(" - using base64 encoding\n");
cl->webSocketsBase64 = TRUE;
} else {
rfbLog(" - using UTF-8 encoding\n");
cl->webSocketsBase64 = FALSE;
}
} else if ((strncmp("Host: ", line, min(llen,6))) == 0) {
/* rfbLog("Got host\n"); */
host = line+6;
buf[len-2] = '\0';
} else if ((strncmp("Origin: ", line, min(llen,8))) == 0) {
/* rfbLog("Got origin\n"); */
origin = line+8;
buf[len-2] = '\0';
} else if ((strncmp("Sec-Websocket-Key1: ", line, min(llen,20))) == 0) {
/* rfbLog("Got key1\n"); */
key1 = line+20;
buf[len-2] = '\0';
} else if ((strncmp("Sec-Websocket-Key2: ", line, min(llen,20))) == 0) {
/* rfbLog("Got key2\n"); */
key2 = line+20;
buf[len-2] = '\0';
}
linestart = len;
}
}
if (!(path && host && origin)) {
rfbErr("webSocketsHandshake: incomplete client handshake\n");
free(response);
free(buf);
return FALSE;
}
/*
* Generate the WebSockets server response based on the the headers sent
* by the client.
*/
if (!(key1 && key2 && key3)) {
rfbLog(" - WebSockets client version 75\n");
prefix[0] = '\0';
trailer[0] = '\0';
} else {
rfbLog(" - WebSockets client version 76\n");
snprintf(prefix, 5, "Sec-");
webSocketsGenMd5(trailer, key1, key2, key3);
}
snprintf(response, WEBSOCKETS_MAX_HANDSHAKE_LEN,
WEBSOCKETS_HANDSHAKE_RESPONSE, prefix, origin, prefix, scheme,
host, path, prefix, trailer);
if (rfbWriteExact(cl, response, strlen(response)) < 0) {
rfbErr("webSocketsHandshake: failed sending WebSockets response\n");
free(response);
free(buf);
return FALSE;
}
/* rfbLog("webSocketsHandshake: handshake complete\n"); */
return TRUE;
}
void
webSocketsGenMd5(char * target, char *key1, char *key2, char *key3)
{
unsigned int i, spaces1 = 0, spaces2 = 0;
unsigned long num1 = 0, num2 = 0;
unsigned char buf[17];
for (i=0; i < strlen(key1); i++) {
if (key1[i] == ' ') {
spaces1 += 1;
}
if ((key1[i] >= 48) && (key1[i] <= 57)) {
num1 = num1 * 10 + (key1[i] - 48);
}
}
num1 = num1 / spaces1;
for (i=0; i < strlen(key2); i++) {
if (key2[i] == ' ') {
spaces2 += 1;
}
if ((key2[i] >= 48) && (key2[i] <= 57)) {
num2 = num2 * 10 + (key2[i] - 48);
}
}
num2 = num2 / spaces2;
/* Pack it big-endian */
buf[0] = (num1 & 0xff000000) >> 24;
buf[1] = (num1 & 0xff0000) >> 16;
buf[2] = (num1 & 0xff00) >> 8;
buf[3] = num1 & 0xff;
buf[4] = (num2 & 0xff000000) >> 24;
buf[5] = (num2 & 0xff0000) >> 16;
buf[6] = (num2 & 0xff00) >> 8;
buf[7] = num2 & 0xff;
strncpy((char *)buf+8, key3, 8);
buf[16] = '\0';
md5_buffer((char *)buf, 16, target);
target[16] = '\0';
return;
}
int
webSocketsEncode(rfbClientPtr cl, const char *src, int len)
{
int i, sz = 0;
unsigned char chr;
cl->encodeBuf[sz++] = '\x00';
if (cl->webSocketsBase64) {
len = __b64_ntop((unsigned char *)src, len, cl->encodeBuf+sz, UPDATE_BUF_SIZE*2);
if (len < 0) {
return len;
}
sz += len;
} else {
for (i=0; i < len; i++) {
chr = src[i];
if (chr < 128) {
if (chr == 0x00) {
cl->encodeBuf[sz++] = '\xc4';
cl->encodeBuf[sz++] = '\x80';
} else {
cl->encodeBuf[sz++] = chr;
}
} else {
if (chr < 192) {
cl->encodeBuf[sz++] = '\xc2';
cl->encodeBuf[sz++] = chr;
} else {
cl->encodeBuf[sz++] = '\xc3';
cl->encodeBuf[sz++] = chr - 64;
}
}
}
}
cl->encodeBuf[sz++] = '\xff';
/* rfbLog("<< webSocketsEncode: %d\n", len); */
return sz;
}
int
webSocketsDecode(rfbClientPtr cl, char *dst, int len)
{
int retlen = 0, n, i, avail, modlen, needlen;
char *buf, *end = NULL;
unsigned char chr;
buf = cl->decodeBuf;
n = recv(cl->sock, buf, len*2+2, MSG_PEEK);
if (n <= 0) {
rfbLog("recv of %d\n", n);
return n;
}
if (buf[0] == '\xff') {
i = read(cl->sock, buf, 1); /* Consume marker */
buf++;
n--;
}
if (buf[0] == '\x00') {
i = read(cl->sock, buf, 1); /* Consume marker */
buf++;
n--;
}
/* rfbLog(">> webSocketsDecode, len: %d, n: %d\n", len, n); */
end = memchr(buf, '\xff', len*2+2);
if (!end) {
end = buf + n;
}
avail = end - buf;
if (cl->webSocketsBase64) {
/* Base64 encoded WebSockets stream */
len -= cl->carrylen;
/* Determine how much base64 data we need */
modlen = len + (len+2)/3;
needlen = modlen;
if (needlen % 4) {
needlen += 4 - (needlen % 4);
}
if (needlen > avail) {
/* rfbLog("Waiting for more base64 data\n"); */
errno = EAGAIN;
return -1;
}
/* Any carryover from previous decode */
for (i=0; i < cl->carrylen; i++) {
/* rfbLog("Adding carryover %d\n", cl->carryBuf[i]); */
dst[i] = cl->carryBuf[i];
retlen += 1;
}
/* Decode the rest of what we need */
buf[needlen] = '\x00'; /* Replace end marker with end of string */
/* rfbLog("buf: %s\n", buf); */
n = __b64_pton(buf, (unsigned char *)dst+retlen, 2+len);
if (n < len) {
rfbErr("Base64 decode error\n");
errno = EIO;
return -1;
}
retlen += n;
/* Consume the data from socket */
/* rfbLog("here1, needlen: %d, n: %d, len: %d\n", needlen, n, len); */
i = read(cl->sock, buf, needlen);
cl->carrylen = n - len;
retlen -= cl->carrylen;
for (i=0; i < cl->carrylen; i++) {
/* rfbLog("Saving carryover %d\n", dst[retlen + i]); */
cl->carryBuf[i] = dst[retlen + i];
}
} else {
/* UTF-8 encoded WebSockets stream */
while (retlen < len) {
chr = *buf;
buf += 1;
if (chr < 128) {
dst[retlen++] = chr;
} else {
if (buf >= end) {
rfbErr("Not enough UTF-8 data to decode\n");
errno = EIO;
return -1;
}
chr = *buf;
buf += 1;
switch (chr) {
case (unsigned char) '\xc2':
dst[retlen++] = chr;
break;
case (unsigned char) '\xc3':
dst[retlen++] = chr + 64;
break;
case (unsigned char) '\xc4':
dst[retlen++] = 0;
break;
}
}
}
}
#if 0
sprintf(debug, "dst:");
for (i = 0; i < retlen; i++) {
sprintf(debug+strlen(debug), "%d,", dst[i]);
}
rfbLog("%s\n", debug);
rfbLog("<< webSocketsDecode, retlen: %d\n", retlen);
#endif
return retlen;
}

@ -631,6 +631,19 @@ typedef struct _rfbClientRec {
#if defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG)
uint32_t tightEncoding; /* rfbEncodingTight or rfbEncodingTightPng */
#endif
#ifdef LIBVNCSERVER_WITH_WEBSOCKETS
rfbBool webSockets;
rfbBool webSocketsSSL;
rfbBool webSocketsBase64;
char encodeBuf[UPDATE_BUF_SIZE*2 + 2]; /* UTF-8 could double it + framing */
char decodeBuf[8192]; /* TODO: what makes sense? */
int dblen;
char carryBuf[3]; /* For base64 carry-over */
int carrylen;
#endif
} rfbClientRec, *rfbClientPtr;
/**
@ -683,6 +696,7 @@ extern void rfbDisconnectUDPSock(rfbScreenInfoPtr rfbScreen);
extern void rfbCloseClient(rfbClientPtr cl);
extern int rfbReadExact(rfbClientPtr cl, char *buf, int len);
extern int rfbReadExactTimeout(rfbClientPtr cl, char *buf, int len,int timeout);
extern int rfbPeekExactTimeout(rfbClientPtr cl, char *buf, int len,int timeout);
extern int rfbWriteExact(rfbClientPtr cl, const char *buf, int len);
extern int rfbCheckFds(rfbScreenInfoPtr rfbScreen,long usec);
extern int rfbConnect(rfbScreenInfoPtr rfbScreen, char* host, int port);
@ -692,6 +706,14 @@ extern int rfbListenOnUDPPort(int port, in_addr_t iface);
extern int rfbStringToAddr(char* string,in_addr_t* addr);
extern rfbBool rfbSetNonBlocking(int sock);
#ifdef LIBVNCSERVER_WITH_WEBSOCKETS
/* websockets.c */
extern rfbBool webSocketsCheck(rfbClientPtr cl);
extern int webSocketsEncode(rfbClientPtr cl, const char *src, int len);
extern int webSocketsDecode(rfbClientPtr cl, char *dst, int len);
#endif
/* rfbserver.c */
/* Routines to iterate over the client list in a thread-safe way.

Loading…
Cancel
Save