rfb.h 48 KB
Newer Older
dscho's avatar
dscho committed
1 2
#ifndef RFB_H
#define RFB_H
3 4 5 6
/**
 * @defgroup libvncserver_api LibVNCServer API Reference
 * @{
 */
dscho's avatar
dscho committed
7

8 9
/**
 * @file rfb.h
dscho's avatar
dscho committed
10 11 12
 */

/*
dscho's avatar
dscho committed
13 14
 *  Copyright (C) 2005 Rohit Kumar <rokumar@novell.com>,
 *                     Johannes E. Schindelin <johannes.schindelin@gmx.de>
15
 *  Copyright (C) 2002 RealVNC Ltd.
dscho's avatar
dscho committed
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
 *  OSXvnc Copyright (C) 2001 Dan McGuirk <mcguirk@incompleteness.net>.
 *  Original Xvnc code Copyright (C) 1999 AT&T Laboratories Cambridge.  
 *  All Rights Reserved.
 *
 *  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.
 */

36 37 38 39 40
#if(defined __cplusplus)
extern "C"
{
#endif

41
#include <stdio.h>
42 43
#include <stdlib.h>
#include <string.h>
44
#include <rfb/rfbproto.h>
dscho's avatar
dscho committed
45

46
#if defined(ANDROID) || defined(LIBVNCSERVER_HAVE_ANDROID)
47 48 49 50
#include <arpa/inet.h>
#include <sys/select.h>
#endif

51
#ifdef LIBVNCSERVER_HAVE_SYS_TYPES_H
dscho's avatar
dscho committed
52
#include <sys/types.h>
53 54
#endif

dscho's avatar
dscho committed
55
#ifdef __MINGW32__
56
#undef SOCKET
dscho's avatar
dscho committed
57
#include <winsock2.h>
58 59 60 61
#ifdef LIBVNCSERVER_HAVE_WS2TCPIP_H
#undef socklen_t
#include <ws2tcpip.h>
#endif
dscho's avatar
dscho committed
62 63
#endif

64
#ifdef LIBVNCSERVER_HAVE_LIBPTHREAD
65
#include <pthread.h>
66
#if 0 /* debugging */
67 68
#define LOCK(mutex) (rfbLog("%s:%d LOCK(%s,0x%x)\n",__FILE__,__LINE__,#mutex,&(mutex)), pthread_mutex_lock(&(mutex)))
#define UNLOCK(mutex) (rfbLog("%s:%d UNLOCK(%s,0x%x)\n",__FILE__,__LINE__,#mutex,&(mutex)), pthread_mutex_unlock(&(mutex)))
69
#define MUTEX(mutex) pthread_mutex_t (mutex)
70 71 72 73
#define INIT_MUTEX(mutex) (rfbLog("%s:%d INIT_MUTEX(%s,0x%x)\n",__FILE__,__LINE__,#mutex,&(mutex)), pthread_mutex_init(&(mutex),NULL))
#define TINI_MUTEX(mutex) (rfbLog("%s:%d TINI_MUTEX(%s)\n",__FILE__,__LINE__,#mutex), pthread_mutex_destroy(&(mutex)))
#define TSIGNAL(cond) (rfbLog("%s:%d TSIGNAL(%s)\n",__FILE__,__LINE__,#cond), pthread_cond_signal(&(cond)))
#define WAIT(cond,mutex) (rfbLog("%s:%d WAIT(%s,%s)\n",__FILE__,__LINE__,#cond,#mutex), pthread_cond_wait(&(cond),&(mutex)))
74
#define COND(cond) pthread_cond_t (cond)
75 76
#define INIT_COND(cond) (rfbLog("%s:%d INIT_COND(%s)\n",__FILE__,__LINE__,#cond), pthread_cond_init(&(cond),NULL))
#define TINI_COND(cond) (rfbLog("%s:%d TINI_COND(%s)\n",__FILE__,__LINE__,#cond), pthread_cond_destroy(&(cond)))
77
#define IF_PTHREADS(x) x
78
#else
79
#if !NONETWORK
80 81
#define LOCK(mutex) pthread_mutex_lock(&(mutex));
#define UNLOCK(mutex) pthread_mutex_unlock(&(mutex));
82
#endif
83 84 85
#define MUTEX(mutex) pthread_mutex_t (mutex)
#define INIT_MUTEX(mutex) pthread_mutex_init(&(mutex),NULL)
#define TINI_MUTEX(mutex) pthread_mutex_destroy(&(mutex))
86
#define TSIGNAL(cond) pthread_cond_signal(&(cond))
87 88 89 90 91 92 93 94 95 96 97 98
#define WAIT(cond,mutex) pthread_cond_wait(&(cond),&(mutex))
#define COND(cond) pthread_cond_t (cond)
#define INIT_COND(cond) pthread_cond_init(&(cond),NULL)
#define TINI_COND(cond) pthread_cond_destroy(&(cond))
#define IF_PTHREADS(x) x
#endif
#else
#define LOCK(mutex)
#define UNLOCK(mutex)
#define MUTEX(mutex)
#define INIT_MUTEX(mutex)
#define TINI_MUTEX(mutex)
99
#define TSIGNAL(cond)
100 101 102 103 104 105 106
#define WAIT(cond,mutex) this_is_unsupported
#define COND(cond)
#define INIT_COND(cond)
#define TINI_COND(cond)
#define IF_PTHREADS(x)
#endif

107 108
/* end of stuff for autoconf */

109
/* if you use pthreads, but don't define LIBVNCSERVER_HAVE_LIBPTHREAD, the structs
110 111 112
   get all mixed up. So this gives a linker error reminding you to compile
   the library and your application (at least the parts including rfb.h)
   with the same support for pthreads. */
113
#ifdef LIBVNCSERVER_HAVE_LIBPTHREAD
dscho's avatar
dscho committed
114
#ifdef LIBVNCSERVER_HAVE_LIBZ
115 116 117 118 119
#define rfbInitServer rfbInitServerWithPthreadsAndZRLE
#else
#define rfbInitServer rfbInitServerWithPthreadsButWithoutZRLE
#endif
#else
dscho's avatar
dscho committed
120
#ifdef LIBVNCSERVER_HAVE_LIBZ
121
#define rfbInitServer rfbInitServerWithoutPthreadsButWithZRLE
122
#else
123 124
#define rfbInitServer rfbInitServerWithoutPthreadsAndZRLE
#endif
125 126
#endif

127 128
struct _rfbClientRec;
struct _rfbScreenInfo;
129 130
struct rfbCursor;

131 132 133 134 135 136
enum rfbNewClientAction {
	RFB_CLIENT_ACCEPT,
	RFB_CLIENT_ON_HOLD,
	RFB_CLIENT_REFUSE
};

dscho's avatar
dscho committed
137 138 139 140 141 142
enum rfbSocketState {
	RFB_SOCKET_INIT,
	RFB_SOCKET_READY,
	RFB_SOCKET_SHUTDOWN
};

143 144 145 146 147 148 149 150 151
typedef void (*rfbKbdAddEventProcPtr) (rfbBool down, rfbKeySym keySym, struct _rfbClientRec* cl);
typedef void (*rfbKbdReleaseAllKeysProcPtr) (struct _rfbClientRec* cl);
typedef void (*rfbPtrAddEventProcPtr) (int buttonMask, int x, int y, struct _rfbClientRec* cl);
typedef void (*rfbSetXCutTextProcPtr) (char* str,int len, struct _rfbClientRec* cl);
typedef struct rfbCursor* (*rfbGetCursorProcPtr) (struct _rfbClientRec* pScreen);
typedef rfbBool (*rfbSetTranslateFunctionProcPtr)(struct _rfbClientRec* cl);
typedef rfbBool (*rfbPasswordCheckProcPtr)(struct _rfbClientRec* cl,const char* encryptedPassWord,int len);
typedef enum rfbNewClientAction (*rfbNewClientHookPtr)(struct _rfbClientRec* cl);
typedef void (*rfbDisplayHookPtr)(struct _rfbClientRec* cl);
152
typedef void (*rfbDisplayFinishedHookPtr)(struct _rfbClientRec* cl, int result);
153
/** support the capability to view the caps/num/scroll states of the X server */
154
typedef int  (*rfbGetKeyboardLedStateHookPtr)(struct _rfbScreenInfo* screen);
155
typedef rfbBool (*rfbXvpHookPtr)(struct _rfbClientRec* cl, uint8_t, uint8_t);
156 157
/**
 * If x==1 and y==1 then set the whole display
158 159 160 161
 * else find the window underneath x and y and set the framebuffer to the dimensions
 * of that window
 */
typedef void (*rfbSetSingleWindowProcPtr) (struct _rfbClientRec* cl, int x, int y);
162 163
/**
 * Status determines if the X11 server permits input from the local user
164 165 166
 * status==0 or 1
 */
typedef void (*rfbSetServerInputProcPtr) (struct _rfbClientRec* cl, int status);
167 168
/**
 * Permit the server to allow or deny filetransfers.   This is defaulted to deny
169 170 171
 * It is called when a client initiates a connection to determine if it is permitted.
 */
typedef int  (*rfbFileTransferPermitted) (struct _rfbClientRec* cl);
172
/** Handle the textchat messages */
173
typedef void (*rfbSetTextChat) (struct _rfbClientRec* cl, int length, char *string);
dscho's avatar
dscho committed
174

175
typedef struct {
176
  uint32_t count;
177
  rfbBool is16; /**< is the data format short? */
178
  union {
179 180
    uint8_t* bytes;
    uint16_t* shorts;
181
  } data; /**< there have to be count*3 entries */
182 183
} rfbColourMap;

184
/**
185
 * Security handling (RFB protocol version 3.7)
dscho's avatar
dscho committed
186 187 188 189 190 191 192 193
 */

typedef struct _rfbSecurity {
	uint8_t type;
	void (*handler)(struct _rfbClientRec* cl);
	struct _rfbSecurity* next;
} rfbSecurityHandler;

194
/**
195 196 197 198
 * Protocol extension handling.
 */

typedef struct _rfbProtocolExtension {
199
	/** returns FALSE if extension should be deactivated for client.
200 201
	   if newClient == NULL, it is always deactivated. */
	rfbBool (*newClient)(struct _rfbClientRec* client, void** data);
202
	/** returns FALSE if extension should be deactivated for client.
203 204
	   if init == NULL, it stays activated. */
	rfbBool (*init)(struct _rfbClientRec* client, void* data);
205
	/** if pseudoEncodings is not NULL, it contains a 0 terminated
206 207
	   list of the pseudo encodings handled by this extension. */
	int *pseudoEncodings;
208
	/** returns TRUE if that pseudo encoding is handled by the extension.
209
	   encodingNumber==0 means "reset encodings". */
210
	rfbBool (*enablePseudoEncoding)(struct _rfbClientRec* client,
211
			void** data, int encodingNumber);
212
	/** returns TRUE if message was handled */
213 214
	rfbBool (*handleMessage)(struct _rfbClientRec* client,
				void* data,
215
				const rfbClientToServerMsg* message);
216 217
	void (*close)(struct _rfbClientRec* client, void* data);
	void (*usage)(void);
218
	/** processArguments returns the number of handled arguments */
219
	int (*processArgument)(int argc, char *argv[]);
220 221 222 223 224 225 226 227
	struct _rfbProtocolExtension* next;
} rfbProtocolExtension;

typedef struct _rfbExtensionData {
	rfbProtocolExtension* extension;
	void* data;
	struct _rfbExtensionData* next;
} rfbExtensionData;
dscho's avatar
dscho committed
228

229
/**
230 231 232
 * Per-screen (framebuffer) structure.  There can be as many as you wish,
 * each serving different clients. However, you have to call
 * rfbProcessEvents for each of these.
dscho's avatar
dscho committed
233 234
 */

235
typedef struct _rfbScreenInfo
dscho's avatar
dscho committed
236
{
237
    /** this structure has children that are scaled versions of this screen */
238 239 240
    struct _rfbScreenInfo *scaledScreenNext;
    int scaledScreenRefCount;

dscho's avatar
dscho committed
241 242 243 244 245 246 247
    int width;
    int paddedWidthInBytes;
    int height;
    int depth;
    int bitsPerPixel;
    int sizeInBytes;

248 249
    rfbPixel blackPixel;
    rfbPixel whitePixel;
dscho's avatar
dscho committed
250

251 252
    /**
     * some screen specific data can be put into a struct where screenData
253 254 255 256
     * points to. You need this if you have more than one screen at the
     * same time while using the same functions.
     */
    void* screenData;
257

dscho's avatar
dscho committed
258
    /* additions by libvncserver */
259

260
    rfbPixelFormat serverFormat;
261
    rfbColourMap colourMap; /**< set this if rfbServerFormat.trueColour==FALSE */
dscho's avatar
dscho committed
262
    const char* desktopName;
263
    char thisHost[255];
264

265
    rfbBool autoPort;
266 267
    int port;
    SOCKET listenSock;
dscho's avatar
dscho committed
268 269
    int maxSock;
    int maxFd;
270
#ifdef __MINGW32__
dscho's avatar
dscho committed
271
    struct fd_set allFds;
272 273 274
#else
    fd_set allFds;
#endif
275

dscho's avatar
dscho committed
276
    enum rfbSocketState socketState;
277
    SOCKET inetdSock;
278
    rfbBool inetdInitDone;
279

dscho's avatar
dscho committed
280
    int udpPort;
281
    SOCKET udpSock;
282
    struct _rfbClientRec* udpClient;
283
    rfbBool udpSockConnected;
dscho's avatar
dscho committed
284
    struct sockaddr_in udpRemoteAddr;
285

286
    int maxClientWait;
287 288

    /* http stuff */
289 290
    rfbBool httpInitDone;
    rfbBool httpEnableProxyConnect;
dscho's avatar
dscho committed
291 292
    int httpPort;
    char* httpDir;
293 294
    SOCKET httpListenSock;
    SOCKET httpSock;
dscho's avatar
dscho committed
295

296 297
    rfbPasswordCheckProcPtr passwordCheck;
    void* authPasswdData;
298 299
    /** If rfbAuthPasswdData is given a list, this is the first
        view only password. */
300
    int authPasswdFirstViewOnly;
301

302
    /** send only this many rectangles in one update */
dscho's avatar
dscho committed
303
    int maxRectsPerUpdate;
304
    /** this is the amount of milliseconds to wait at least before sending
dscho's avatar
dscho committed
305
     * an update. */
306 307 308 309 310 311 312 313
    int deferUpdateTime;
#ifdef TODELETE
    char* screen;
#endif
    rfbBool alwaysShared;
    rfbBool neverShared;
    rfbBool dontDisconnect;
    struct _rfbClientRec* clientHead;
314
    struct _rfbClientRec* pointerClient;  /**< "Mutex" for pointer events */
dscho's avatar
dscho committed
315

316 317

    /* cursor */
dscho's avatar
dscho committed
318
    int cursorX, cursorY,underCursorBufferLen;
319
    char* underCursorBuffer;
320
    rfbBool dontConvertRichCursorToXCursor;
321
    struct rfbCursor* cursor;
322

323 324 325
    /**
     * the frameBuffer has to be supplied by the serving process.
     * The buffer will not be freed by
dscho's avatar
dscho committed
326
     */
dscho's avatar
dscho committed
327
    char* frameBuffer;
328 329 330 331 332 333
    rfbKbdAddEventProcPtr kbdAddEvent;
    rfbKbdReleaseAllKeysProcPtr kbdReleaseAllKeys;
    rfbPtrAddEventProcPtr ptrAddEvent;
    rfbSetXCutTextProcPtr setXCutText;
    rfbGetCursorProcPtr getCursorPtr;
    rfbSetTranslateFunctionProcPtr setTranslateFunction;
334 335 336 337
    rfbSetSingleWindowProcPtr setSingleWindow;
    rfbSetServerInputProcPtr  setServerInput;
    rfbFileTransferPermitted  getFileTransferPermission;
    rfbSetTextChat            setTextChat;
338 339

    /** newClientHook is called just after a new client is created */
340
    rfbNewClientHookPtr newClientHook;
341
    /** displayHook is called just before a frame buffer update */
342
    rfbDisplayHookPtr displayHook;
dscho's avatar
dscho committed
343

344
    /** These hooks are called to pass keyboard state back to the client */
dscho's avatar
dscho committed
345 346
    rfbGetKeyboardLedStateHookPtr getKeyboardLedStateHook;

347
#ifdef LIBVNCSERVER_HAVE_LIBPTHREAD
348
    MUTEX(cursorMutex);
349
    rfbBool backgroundLoop;
dscho's avatar
dscho committed
350 351
#endif

352
    /** if TRUE, an ignoring signal handler is installed for SIGPIPE */
353
    rfbBool ignoreSIGPIPE;
354

355
    /** if not zero, only a slice of this height is processed every time
356 357 358
     * an update should be sent. This should make working on a slow
     * link more interactive. */
    int progressiveSliceHeight;
359

runge's avatar
runge committed
360
    in_addr_t listenInterface;
361
    int deferPtrUpdateTime;
362

363
    /** handle as many input events as possible (default off) */
364
    rfbBool handleEventsEagerly;
365

366
    /** rfbEncodingServerIdentity */
367
    char *versionString;
368

369
    /** What does the server tell the new clients which version it supports */
370 371
    int protocolMajorVersion;
    int protocolMinorVersion;
372

373
    /** command line authorization of file transfers */
374
    rfbBool permitFileTransfer;
375

376
    /** displayFinishedHook is called just after a frame buffer update */
377
    rfbDisplayFinishedHookPtr displayFinishedHook;
378
    /** xvpHook is called to handle an xvp client message */
379
    rfbXvpHookPtr xvpHook;
380 381 382 383
#ifdef LIBVNCSERVER_WITH_WEBSOCKETS
    char *sslkeyfile;
    char *sslcertfile;
#endif
384 385 386 387 388 389
    int ipv6port; /**< The port to listen on when using IPv6.  */
    char* listen6Interface;
    /* We have an additional IPv6 listen socket since there are systems that
       don't support dual binding sockets under *any* circumstances, for
       instance OpenBSD */
    SOCKET listen6Sock;
390 391
    int http6Port;
    SOCKET httpListen6Sock;
dscho's avatar
dscho committed
392 393 394
} rfbScreenInfo, *rfbScreenInfoPtr;


395
/**
dscho's avatar
dscho committed
396 397 398 399 400 401 402 403 404 405
 * rfbTranslateFnType is the type of translation functions.
 */

typedef void (*rfbTranslateFnType)(char *table, rfbPixelFormat *in,
                                   rfbPixelFormat *out,
                                   char *iptr, char *optr,
                                   int bytesBetweenInputLines,
                                   int width, int height);


406 407
/* region stuff */

408 409
struct sraRegion;
typedef struct sraRegion* sraRegionPtr;
410

dscho's avatar
dscho committed
411 412 413 414
/*
 * Per-client structure.
 */

415
typedef void (*ClientGoneHookPtr)(struct _rfbClientRec* cl);
dscho's avatar
dscho committed
416

417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
typedef struct _rfbFileTransferData {
  int fd;
  int compressionEnabled;
  int fileSize;
  int numPackets;
  int receiving;
  int sending;
} rfbFileTransferData;


typedef struct _rfbStatList {
    uint32_t type;
    uint32_t sentCount;
    uint32_t bytesSent;
    uint32_t bytesSentIfRaw;
    uint32_t rcvdCount;
    uint32_t bytesRcvd;
    uint32_t bytesRcvdIfRaw;
    struct _rfbStatList *Next;
} rfbStatList;

438
typedef struct _rfbSslCtx rfbSslCtx;
439
typedef struct _wsCtx wsCtx;
440

441
typedef struct _rfbClientRec {
442 443

    /** back pointer to the screen */
dscho's avatar
dscho committed
444
    rfbScreenInfoPtr screen;
445

446
     /** points to a scaled version of the screen buffer in cl->scaledScreenList */
447
     rfbScreenInfoPtr scaledScreen;
448
     /** how did the client tell us it wanted the screen changed?  Ultra style or palm style? */
449
     rfbBool PalmVNC;
450 451 452


    /** private data. You should put any application client specific data
453 454
     * into a struct and let clientData point to it. Don't forget to
     * free the struct via clientGoneHook!
455 456
     *
     * This is useful if the IO functions have to behave client specific.
457
     */
dscho's avatar
dscho committed
458 459
    void* clientData;
    ClientGoneHookPtr clientGoneHook;
460

461
    SOCKET sock;
dscho's avatar
dscho committed
462
    char *host;
463

dscho's avatar
dscho committed
464
    /* RFB protocol minor version number */
465
    int protocolMajorVersion;
dscho's avatar
dscho committed
466 467
    int protocolMinorVersion;

468
#ifdef LIBVNCSERVER_HAVE_LIBPTHREAD
469 470
    pthread_t client_thread;
#endif
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496

    /* Note that the RFB_INITIALISATION_SHARED state is provided to support
       clients that under some circumstances do not send a ClientInit message.
       In particular the Mac OS X built-in VNC client (with protocolMinorVersion
       == 889) is one of those.  However, it only requires this support under
       special circumstances that can only be determined during the initial
       authentication.  If the right conditions are met this state will be
       set (see the auth.c file) when rfbProcessClientInitMessage is called.

       If the state is RFB_INITIALISATION_SHARED we should not expect to recieve
       any ClientInit message, but instead should proceed to the next stage
       of initialisation as though an implicit ClientInit message was received
       with a shared-flag of true.  (There is currently no corresponding
       RFB_INITIALISATION_NOTSHARED state to represent an implicit ClientInit
       message with a shared-flag of false because no known existing client
       requires such support at this time.)

       Note that software using LibVNCServer to provide a VNC server will only
       ever have a chance to see the state field set to
       RFB_INITIALISATION_SHARED if the software is multi-threaded and manages
       to examine the state field during the extremely brief window after the
       'None' authentication type selection has been received from the built-in
       OS X VNC client and before the rfbProcessClientInitMessage function is
       called -- control cannot return to the caller during this brief window
       while the state field is set to RFB_INITIALISATION_SHARED. */

497
                                /** Possible client states: */
dscho's avatar
dscho committed
498
    enum {
499 500 501 502
        RFB_PROTOCOL_VERSION,   /**< establishing protocol version */
	RFB_SECURITY_TYPE,      /**< negotiating security (RFB v.3.7) */
        RFB_AUTHENTICATION,     /**< authenticating */
        RFB_INITIALISATION,     /**< sending initialisation messages */
503 504 505 506 507 508
        RFB_NORMAL,             /**< normal protocol messages */

        /* Ephemeral internal-use states that will never be seen by software
         * using LibVNCServer to provide services: */

        RFB_INITIALISATION_SHARED /**< sending initialisation messages with implicit shared-flag already true */
dscho's avatar
dscho committed
509 510
    } state;

511 512 513 514
    rfbBool reverseConnection;
    rfbBool onHold;
    rfbBool readyForSetColourMapEntries;
    rfbBool useCopyRect;
dscho's avatar
dscho committed
515 516 517
    int preferredEncoding;
    int correMaxWidth, correMaxHeight;

518
    rfbBool viewOnly;
dscho's avatar
dscho committed
519

dscho's avatar
dscho committed
520
    /* The following member is only used during VNC authentication */
521
    uint8_t authChallenge[CHALLENGESIZE];
dscho's avatar
dscho committed
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545

    /* The following members represent the update needed to get the client's
       framebuffer from its present state to the current state of our
       framebuffer.

       If the client does not accept CopyRect encoding then the update is
       simply represented as the region of the screen which has been modified
       (modifiedRegion).

       If the client does accept CopyRect encoding, then the update consists of
       two parts.  First we have a single copy from one region of the screen to
       another (the destination of the copy is copyRegion), and second we have
       the region of the screen which has been modified in some other way
       (modifiedRegion).

       Although the copy is of a single region, this region may have many
       rectangles.  When sending an update, the copyRegion is always sent
       before the modifiedRegion.  This is because the modifiedRegion may
       overlap parts of the screen which are in the source of the copy.

       In fact during normal processing, the modifiedRegion may even overlap
       the destination copyRegion.  Just before an update is sent we remove
       from the copyRegion anything in the modifiedRegion. */

546 547
    sraRegionPtr copyRegion;	/**< the destination region of the copy */
    int copyDX, copyDY;		/**< the translation by which the copy happens */
dscho's avatar
dscho committed
548

549
    sraRegionPtr modifiedRegion;
dscho's avatar
dscho committed
550

551
    /** As part of the FramebufferUpdateRequest, a client can express interest
dscho's avatar
dscho committed
552 553 554 555
       in a subrectangle of the whole framebuffer.  This is stored in the
       requestedRegion member.  In the normal case this is the whole
       framebuffer if the client is ready, empty if it's not. */

556
    sraRegionPtr requestedRegion;
dscho's avatar
dscho committed
557

558
    /** The following member represents the state of the "deferred update" timer
dscho's avatar
dscho committed
559 560 561 562 563
       - when the framebuffer is modified and the client is ready, in most
       cases it is more efficient to defer sending the update by a few
       milliseconds so that several changes to the framebuffer can be combined
       into a single update. */

dscho's avatar
dscho committed
564
      struct timeval startDeferring;
565 566 567 568
      struct timeval startPtrDeferring;
      int lastPtrX;
      int lastPtrY;
      int lastPtrButtons;
dscho's avatar
dscho committed
569

570
    /** translateFn points to the translation function which is used to copy
dscho's avatar
dscho committed
571 572 573 574 575 576
       and translate a rectangle from the framebuffer to an output buffer. */

    rfbTranslateFnType translateFn;
    char *translateLookupTable;
    rfbPixelFormat format;

577
    /**
578 579 580 581
     * UPDATE_BUF_SIZE must be big enough to send at least one whole line of the
     * framebuffer.  So for a max screen width of say 2K with 32-bit pixels this
     * means 8K minimum.
     */
dscho's avatar
dscho committed
582 583 584 585 586 587 588

#define UPDATE_BUF_SIZE 30000

    char updateBuf[UPDATE_BUF_SIZE];
    int ublen;

    /* statistics */
589 590
    struct _rfbStatList *statEncList;
    struct _rfbStatList *statMsgList;
591
    int rawBytesEquivalent;
592
    int bytesSent;
593

594
#ifdef LIBVNCSERVER_HAVE_LIBZ
dscho's avatar
dscho committed
595 596 597
    /* zlib encoding -- necessary compression state info per client */

    struct z_stream_s compStream;
598
    rfbBool compStreamInited;
599
    uint32_t zlibCompressLevel;
600 601 602
#endif
#if defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG)
    /** the quality level is also used by ZYWRLE and TightPng */
603
    int tightQualityLevel;
dscho's avatar
dscho committed
604

605
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
dscho's avatar
dscho committed
606 607
    /* tight encoding -- preserve zlib streams' state for each client */
    z_stream zsStruct[4];
608
    rfbBool zsActive[4];
dscho's avatar
dscho committed
609 610
    int zsLevel[4];
    int tightCompressLevel;
dscho's avatar
dscho committed
611 612
#endif
#endif
613 614 615 616 617

    /* Ultra Encoding support */
    rfbBool compStreamInitedLZO;
    char *lzoWrkMem;

618
    rfbFileTransferData fileTransfer;
619

620 621 622 623 624 625 626 627 628 629 630 631
    int     lastKeyboardLedState;     /**< keep track of last value so we can send *change* events */
    rfbBool enableSupportedMessages;  /**< client supports SupportedMessages encoding */
    rfbBool enableSupportedEncodings; /**< client supports SupportedEncodings encoding */
    rfbBool enableServerIdentity;     /**< client supports ServerIdentity encoding */
    rfbBool enableKeyboardLedState;   /**< client supports KeyboardState encoding */
    rfbBool enableLastRectEncoding;   /**< client supports LastRect encoding */
    rfbBool enableCursorShapeUpdates; /**< client supports cursor shape updates */
    rfbBool enableCursorPosUpdates;   /**< client supports cursor position updates */
    rfbBool useRichCursorEncoding;    /**< rfbEncodingRichCursor is preferred */
    rfbBool cursorWasChanged;         /**< cursor shape update should be sent */
    rfbBool cursorWasMoved;           /**< cursor position update should be sent */
    int cursorX,cursorY;	      /**< the coordinates of the cursor,
dscho's avatar
dscho committed
632
					 if enableCursorShapeUpdates = FALSE */
dscho's avatar
dscho committed
633

634 635
    rfbBool useNewFBSize;             /**< client supports NewFBSize encoding */
    rfbBool newFBSizePending;         /**< framebuffer size was changed */
dscho's avatar
dscho committed
636

637 638
    struct _rfbClientRec *prev;
    struct _rfbClientRec *next;
dscho's avatar
dscho committed
639

640
#ifdef LIBVNCSERVER_HAVE_LIBPTHREAD
641
    /** whenever a client is referenced, the refCount has to be incremented
642 643
       and afterwards decremented, so that the client is not cleaned up
       while being referenced.
dscho's avatar
dscho committed
644 645 646 647 648 649 650 651 652 653 654
       Use the functions rfbIncrClientRef(cl) and rfbDecrClientRef(cl);
    */
    int refCount;
    MUTEX(refCountMutex);
    COND(deleteCond);

    MUTEX(outputMutex);
    MUTEX(updateMutex);
    COND(updateCond);
#endif

dscho's avatar
dscho committed
655
#ifdef LIBVNCSERVER_HAVE_LIBZ
656
    void* zrleData;
657 658
    int zywrleLevel;
    int zywrleBuf[rfbZRLETileWidth * rfbZRLETileHeight];
659 660
#endif

661
    /** if progressive updating is on, this variable holds the current
662 663
     * y coordinate of the progressive slice. */
    int progressiveSliceY;
664 665

    rfbExtensionData* extensions;
666

667
    /** for threaded zrle */
668 669 670
    char *zrleBeforeBuf;
    void *paletteHelper;

671
    /** for thread safety for rfbSendFBUpdate() */
672 673 674 675 676
#ifdef LIBVNCSERVER_HAVE_LIBPTHREAD
#define LIBVNCSERVER_SEND_MUTEX
    MUTEX(sendMutex);
#endif

677 678 679 680 681 682 683
  /* buffers to hold pixel data before and after encoding.
     per-client for thread safety */
  char *beforeEncBuf;
  int beforeEncBufSize;
  char *afterEncBuf;
  int afterEncBufSize;
  int afterEncBufLen;
684 685
#if defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG)
    uint32_t tightEncoding;  /* rfbEncodingTight or rfbEncodingTightPng */
686
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
687
    /* TurboVNC Encoding support (extends TightVNC) */
688 689
    int turboSubsampLevel;
    int turboQualityLevel;  // 1-100 scale
690
#endif
691
#endif
692 693

#ifdef LIBVNCSERVER_WITH_WEBSOCKETS
694
    rfbSslCtx *sslctx;
695
    wsCtx     *wsctx;
696
    char *wspath;                          /* Requests path component */
697
#endif
dscho's avatar
dscho committed
698 699
} rfbClientRec, *rfbClientPtr;

700
/**
dscho's avatar
dscho committed
701 702 703 704
 * This macro is used to test whether there is a framebuffer update needing to
 * be sent to the client.
 */

dscho's avatar
dscho committed
705
#define FB_UPDATE_PENDING(cl)                                              \
dscho's avatar
dscho committed
706 707 708 709
     (((cl)->enableCursorShapeUpdates && (cl)->cursorWasChanged) ||        \
     (((cl)->enableCursorShapeUpdates == FALSE &&                          \
       ((cl)->cursorX != (cl)->screen->cursorX ||                          \
	(cl)->cursorY != (cl)->screen->cursorY))) ||                       \
dscho's avatar
dscho committed
710
     ((cl)->useNewFBSize && (cl)->newFBSizePending) ||                     \
711
     ((cl)->enableCursorPosUpdates && (cl)->cursorWasMoved) ||             \
712 713
     !sraRgnEmpty((cl)->copyRegion) || !sraRgnEmpty((cl)->modifiedRegion))

dscho's avatar
dscho committed
714 715 716 717 718 719
/*
 * Macros for endian swapping.
 */

#define Swap16(s) ((((s) & 0xff) << 8) | (((s) >> 8) & 0xff))

720 721 722
#define Swap24(l) ((((l) & 0xff) << 16) | (((l) >> 16) & 0xff) | \
                   (((l) & 0x00ff00)))

dscho's avatar
dscho committed
723 724 725 726 727 728
#define Swap32(l) (((l) >> 24) | \
                   (((l) & 0x00ff0000) >> 8)  | \
                   (((l) & 0x0000ff00) << 8)  | \
                   ((l) << 24))


729
extern char rfbEndianTest;
dscho's avatar
dscho committed
730

731
#define Swap16IfLE(s) (rfbEndianTest ? Swap16(s) : (s))
732
#define Swap24IfLE(l) (rfbEndianTest ? Swap24(l) : (l))
733
#define Swap32IfLE(l) (rfbEndianTest ? Swap32(l) : (l))
dscho's avatar
dscho committed
734

735 736 737 738 739
/* UltraVNC uses some windows structures unmodified, so the viewer expects LittleEndian Data */
#define Swap16IfBE(s) (rfbEndianTest ? (s) : Swap16(s))
#define Swap24IfBE(l) (rfbEndianTest ? (l) : Swap24(l))
#define Swap32IfBE(l) (rfbEndianTest ? (l) : Swap32(l))

dscho's avatar
dscho committed
740 741 742 743
/* sockets.c */

extern int rfbMaxClientWait;

744
extern void rfbInitSockets(rfbScreenInfoPtr rfbScreen);
dscho's avatar
dscho committed
745
extern void rfbShutdownSockets(rfbScreenInfoPtr rfbScreen);
746
extern void rfbDisconnectUDPSock(rfbScreenInfoPtr rfbScreen);
dscho's avatar
dscho committed
747
extern void rfbCloseClient(rfbClientPtr cl);
748 749
extern int rfbReadExact(rfbClientPtr cl, char *buf, int len);
extern int rfbReadExactTimeout(rfbClientPtr cl, char *buf, int len,int timeout);
750
extern int rfbPeekExactTimeout(rfbClientPtr cl, char *buf, int len,int timeout);
751
extern int rfbWriteExact(rfbClientPtr cl, const char *buf, int len);
752
extern int rfbCheckFds(rfbScreenInfoPtr rfbScreen,long usec);
dscho's avatar
dscho committed
753
extern int rfbConnect(rfbScreenInfoPtr rfbScreen, char* host, int port);
754
extern int rfbConnectToTcpAddr(char* host, int port);
runge's avatar
runge committed
755
extern int rfbListenOnTCPPort(int port, in_addr_t iface);
756
extern int rfbListenOnTCP6Port(int port, const char* iface);
runge's avatar
runge committed
757
extern int rfbListenOnUDPPort(int port, in_addr_t iface);
758
extern int rfbStringToAddr(char* string,in_addr_t* addr);
759
extern rfbBool rfbSetNonBlocking(int sock);
dscho's avatar
dscho committed
760

761 762 763 764
#ifdef LIBVNCSERVER_WITH_WEBSOCKETS
/* websockets.c */

extern rfbBool webSocketsCheck(rfbClientPtr cl);
765
extern rfbBool webSocketCheckDisconnect(rfbClientPtr cl);
766
extern int webSocketsEncode(rfbClientPtr cl, const char *src, int len, char **dst);
767 768 769
extern int webSocketsDecode(rfbClientPtr cl, char *dst, int len);
#endif

dscho's avatar
dscho committed
770 771 772 773 774 775 776 777 778 779
/* rfbserver.c */

/* Routines to iterate over the client list in a thread-safe way.
   Only a single iterator can be in use at a time process-wide. */
typedef struct rfbClientIterator *rfbClientIteratorPtr;

extern void rfbClientListInit(rfbScreenInfoPtr rfbScreen);
extern rfbClientIteratorPtr rfbGetClientIterator(rfbScreenInfoPtr rfbScreen);
extern rfbClientPtr rfbClientIteratorNext(rfbClientIteratorPtr iterator);
extern void rfbReleaseClientIterator(rfbClientIteratorPtr iterator);
780 781
extern void rfbIncrClientRef(rfbClientPtr cl);
extern void rfbDecrClientRef(rfbClientPtr cl);
dscho's avatar
dscho committed
782 783 784

extern void rfbNewClientConnection(rfbScreenInfoPtr rfbScreen,int sock);
extern rfbClientPtr rfbNewClient(rfbScreenInfoPtr rfbScreen,int sock);
785
extern rfbClientPtr rfbNewUDPClient(rfbScreenInfoPtr rfbScreen);
dscho's avatar
dscho committed
786
extern rfbClientPtr rfbReverseConnection(rfbScreenInfoPtr rfbScreen,char *host, int port);
dscho's avatar
dscho committed
787 788
extern void rfbClientConnectionGone(rfbClientPtr cl);
extern void rfbProcessClientMessage(rfbClientPtr cl);
789
extern void rfbClientConnFailed(rfbClientPtr cl, const char *reason);
dscho's avatar
dscho committed
790
extern void rfbNewUDPConnection(rfbScreenInfoPtr rfbScreen,int sock);
791
extern void rfbProcessUDPInput(rfbScreenInfoPtr rfbScreen);
792 793 794
extern rfbBool rfbSendFramebufferUpdate(rfbClientPtr cl, sraRegionPtr updateRegion);
extern rfbBool rfbSendRectEncodingRaw(rfbClientPtr cl, int x,int y,int w,int h);
extern rfbBool rfbSendUpdateBuf(rfbClientPtr cl);
dscho's avatar
dscho committed
795
extern void rfbSendServerCutText(rfbScreenInfoPtr rfbScreen,char *str, int len);
796 797 798 799
extern rfbBool rfbSendCopyRegion(rfbClientPtr cl,sraRegionPtr reg,int dx,int dy);
extern rfbBool rfbSendLastRectMarker(rfbClientPtr cl);
extern rfbBool rfbSendNewFBSize(rfbClientPtr cl, int w, int h);
extern rfbBool rfbSendSetColourMapEntries(rfbClientPtr cl, int firstColour, int nColours);
dscho's avatar
dscho committed
800
extern void rfbSendBell(rfbScreenInfoPtr rfbScreen);
dscho's avatar
dscho committed
801

802 803 804
extern char *rfbProcessFileTransferReadBuffer(rfbClientPtr cl, uint32_t length);
extern rfbBool rfbSendFileTransferChunk(rfbClientPtr cl);
extern rfbBool rfbSendDirContent(rfbClientPtr cl, int length, char *buffer);
805
extern rfbBool rfbSendFileTransferMessage(rfbClientPtr cl, uint8_t contentType, uint8_t contentParam, uint32_t size, uint32_t length, const char *buffer);
806 807 808
extern char *rfbProcessFileTransferReadBuffer(rfbClientPtr cl, uint32_t length);
extern rfbBool rfbProcessFileTransfer(rfbClientPtr cl, uint8_t contentType, uint8_t contentParam, uint32_t size, uint32_t length);

dscho's avatar
dscho committed
809 810 811 812
void rfbGotXCutText(rfbScreenInfoPtr rfbScreen, char *str, int len);

/* translate.c */

813
extern rfbBool rfbEconomicTranslate;
dscho's avatar
dscho committed
814 815 816 817 818 819

extern void rfbTranslateNone(char *table, rfbPixelFormat *in,
                             rfbPixelFormat *out,
                             char *iptr, char *optr,
                             int bytesBetweenInputLines,
                             int width, int height);
820 821
extern rfbBool rfbSetTranslateFunction(rfbClientPtr cl);
extern rfbBool rfbSetClientColourMap(rfbClientPtr cl, int firstColour, int nColours);
822
extern void rfbSetClientColourMaps(rfbScreenInfoPtr rfbScreen, int firstColour, int nColours);
dscho's avatar
dscho committed
823 824 825

/* httpd.c */

826
extern void rfbHttpInitSockets(rfbScreenInfoPtr rfbScreen);
dscho's avatar
dscho committed
827
extern void rfbHttpShutdownSockets(rfbScreenInfoPtr rfbScreen);
828
extern void rfbHttpCheckFds(rfbScreenInfoPtr rfbScreen);
dscho's avatar
dscho committed
829 830 831 832 833 834



/* auth.c */

extern void rfbAuthNewClient(rfbClientPtr cl);
835
extern void rfbProcessClientSecurityType(rfbClientPtr cl);
dscho's avatar
dscho committed
836
extern void rfbAuthProcessClientMessage(rfbClientPtr cl);
837
extern void rfbRegisterSecurityHandler(rfbSecurityHandler* handler);
838
extern void rfbUnregisterSecurityHandler(rfbSecurityHandler* handler);
dscho's avatar
dscho committed
839 840 841

/* rre.c */

842
extern rfbBool rfbSendRectEncodingRRE(rfbClientPtr cl, int x,int y,int w,int h);
dscho's avatar
dscho committed
843 844 845 846


/* corre.c */

847
extern rfbBool rfbSendRectEncodingCoRRE(rfbClientPtr cl, int x,int y,int w,int h);
dscho's avatar
dscho committed
848 849 850 851


/* hextile.c */

852
extern rfbBool rfbSendRectEncodingHextile(rfbClientPtr cl, int x, int y, int w,
dscho's avatar
dscho committed
853 854
                                       int h);

855 856 857 858 859 860 861 862 863 864 865
/* ultra.c */

/* Set maximum ultra rectangle size in pixels.  Always allow at least
 * two scan lines.
 */
#define ULTRA_MAX_RECT_SIZE (128*256)
#define ULTRA_MAX_SIZE(min) ((( min * 2 ) > ULTRA_MAX_RECT_SIZE ) ? \
                            ( min * 2 ) : ULTRA_MAX_RECT_SIZE )

extern rfbBool rfbSendRectEncodingUltra(rfbClientPtr cl, int x,int y,int w,int h);

dscho's avatar
dscho committed
866

867
#ifdef LIBVNCSERVER_HAVE_LIBZ
dscho's avatar
dscho committed
868 869
/* zlib.c */

870
/** Minimum zlib rectangle size in bytes.  Anything smaller will
dscho's avatar
dscho committed
871 872 873 874 875 876 877 878 879 880 881
 * not compress well due to overhead.
 */
#define VNC_ENCODE_ZLIB_MIN_COMP_SIZE (17)

/* Set maximum zlib rectangle size in pixels.  Always allow at least
 * two scan lines.
 */
#define ZLIB_MAX_RECT_SIZE (128*256)
#define ZLIB_MAX_SIZE(min) ((( min * 2 ) > ZLIB_MAX_RECT_SIZE ) ? \
			    ( min * 2 ) : ZLIB_MAX_RECT_SIZE )

882
extern rfbBool rfbSendRectEncodingZlib(rfbClientPtr cl, int x, int y, int w,
dscho's avatar
dscho committed
883 884
				    int h);

885
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
dscho's avatar
dscho committed
886 887 888
/* tight.c */

#define TIGHT_DEFAULT_COMPRESSION  6
889
#define TURBO_DEFAULT_SUBSAMP 0
DRC's avatar
DRC committed
890

891
extern rfbBool rfbTightDisableGradient;
dscho's avatar
dscho committed
892 893

extern int rfbNumCodedRectsTight(rfbClientPtr cl, int x,int y,int w,int h);
894

895
extern rfbBool rfbSendRectEncodingTight(rfbClientPtr cl, int x,int y,int w,int h);
896

897 898 899
#if defined(LIBVNCSERVER_HAVE_LIBPNG)
extern rfbBool rfbSendRectEncodingTightPng(rfbClientPtr cl, int x,int y,int w,int h);
#endif
900

dscho's avatar
dscho committed
901 902
#endif
#endif
dscho's avatar
dscho committed
903 904 905 906


/* cursor.c */

907
typedef struct rfbCursor {
908
    /** set this to true if LibVNCServer has to free this cursor */
909
    rfbBool cleanup, cleanupSource, cleanupMask, cleanupRichSource;
910 911 912 913 914 915 916 917
    unsigned char *source;			/**< points to bits */
    unsigned char *mask;			/**< points to bits */
    unsigned short width, height, xhot, yhot;	/**< metrics */
    unsigned short foreRed, foreGreen, foreBlue; /**< device-independent colour */
    unsigned short backRed, backGreen, backBlue; /**< device-independent colour */
    unsigned char *richSource; /**< source bytes for a rich cursor */
    unsigned char *alphaSource; /**< source for alpha blending info */
    rfbBool alphaPreMultiplied; /**< if richSource already has alpha applied */
918
} rfbCursor, *rfbCursorPtr;
919
extern unsigned char rfbReverseByte[0x100];
920

921 922
extern rfbBool rfbSendCursorShape(rfbClientPtr cl/*, rfbScreenInfoPtr pScreen*/);
extern rfbBool rfbSendCursorPos(rfbClientPtr cl);
923 924 925
extern void rfbConvertLSBCursorBitmapOrMask(int width,int height,unsigned char* bitmap);
extern rfbCursorPtr rfbMakeXCursor(int width,int height,char* cursorString,char* maskString);
extern char* rfbMakeMaskForXCursor(int width,int height,char* cursorString);
926
extern char* rfbMakeMaskFromAlphaSource(int width,int height,unsigned char* alphaSource);
927 928
extern void rfbMakeXCursorFromRichCursor(rfbScreenInfoPtr rfbScreen,rfbCursorPtr cursor);
extern void rfbMakeRichCursorFromXCursor(rfbScreenInfoPtr rfbScreen,rfbCursorPtr cursor);
929
extern void rfbFreeCursor(rfbCursorPtr cursor);
dscho's avatar
dscho committed
930
extern void rfbSetCursor(rfbScreenInfoPtr rfbScreen,rfbCursorPtr c);
dscho's avatar
dscho committed
931

932
/** cursor handling for the pointer */
933
extern void rfbDefaultPtrAddEvent(int buttonMask,int x,int y,rfbClientPtr cl);
dscho's avatar
dscho committed
934

935
/* zrle.c */
dscho's avatar
dscho committed
936
#ifdef LIBVNCSERVER_HAVE_LIBZ
937
extern rfbBool rfbSendRectEncodingZRLE(rfbClientPtr cl, int x, int y, int w,int h);
938
#endif
939

dscho's avatar
dscho committed
940 941 942 943 944
/* stats.c */

extern void rfbResetStats(rfbClientPtr cl);
extern void rfbPrintStats(rfbClientPtr cl);

945 946 947
/* font.c */

typedef struct rfbFontData {
dscho's avatar
dscho committed
948
  unsigned char* data;
949
  /**
950 951 952 953 954 955 956
    metaData is a 256*5 array:
    for each character
    (offset,width,height,x,y)
  */
  int* metaData;
} rfbFontData,* rfbFontDataPtr;

957 958
int rfbDrawChar(rfbScreenInfoPtr rfbScreen,rfbFontDataPtr font,int x,int y,unsigned char c,rfbPixel colour);
void rfbDrawString(rfbScreenInfoPtr rfbScreen,rfbFontDataPtr font,int x,int y,const char* string,rfbPixel colour);
959
/** if colour==backColour, background is transparent */
960 961
int rfbDrawCharWithClip(rfbScreenInfoPtr rfbScreen,rfbFontDataPtr font,int x,int y,unsigned char c,int x1,int y1,int x2,int y2,rfbPixel colour,rfbPixel backColour);
void rfbDrawStringWithClip(rfbScreenInfoPtr rfbScreen,rfbFontDataPtr font,int x,int y,const char* string,int x1,int y1,int x2,int y2,rfbPixel colour,rfbPixel backColour);
dscho's avatar
dscho committed
962
int rfbWidthOfString(rfbFontDataPtr font,const char* string);
dscho's avatar
dscho committed
963 964
int rfbWidthOfChar(rfbFontDataPtr font,unsigned char c);
void rfbFontBBox(rfbFontDataPtr font,unsigned char c,int* x1,int* y1,int* x2,int* y2);
965
/** this returns the smallest box enclosing any character of font. */
966 967
void rfbWholeFontBBox(rfbFontDataPtr font,int *x1, int *y1, int *x2, int *y2);

968
/** dynamically load a linux console font (4096 bytes, 256 glyphs a 8x16 */
969
rfbFontDataPtr rfbLoadConsoleFont(char *filename);
970
/** free a dynamically loaded font */
971 972 973 974
void rfbFreeFont(rfbFontDataPtr font);

/* draw.c */

975 976 977
void rfbFillRect(rfbScreenInfoPtr s,int x1,int y1,int x2,int y2,rfbPixel col);
void rfbDrawPixel(rfbScreenInfoPtr s,int x,int y,rfbPixel col);
void rfbDrawLine(rfbScreenInfoPtr s,int x1,int y1,int x2,int y2,rfbPixel col);
978 979 980

/* selbox.c */

981
/** this opens a modal select box. list is an array of strings, the end marked
982 983 984
   with a NULL.
   It returns the index in the list or -1 if cancelled or something else
   wasn't kosher. */
985
typedef void (*SelectionChangedHookPtr)(int _index);
986 987 988
extern int rfbSelectBox(rfbScreenInfoPtr rfbScreen,
			rfbFontDataPtr font, char** list,
			int x1, int y1, int x2, int y2,
989
			rfbPixel foreColour, rfbPixel backColour,
990
			int border,SelectionChangedHookPtr selChangedHook);
991

dscho's avatar
dscho committed
992 993
/* cargs.c */

dscho's avatar
dscho committed
994
extern void rfbUsage(void);
dscho's avatar
dscho committed
995
extern void rfbPurgeArguments(int* argc,int* position,int count,char *argv[]);
996 997
extern rfbBool rfbProcessArguments(rfbScreenInfoPtr rfbScreen,int* argc, char *argv[]);
extern rfbBool rfbProcessSizeArguments(int* width,int* height,int* bpp,int* argc, char *argv[]);
dscho's avatar
dscho committed
998

999 1000
/* main.c */

dscho's avatar
dscho committed
1001
extern void rfbLogEnable(int enabled);
1002
typedef void (*rfbLogProc)(const char *format, ...);
dscho's avatar
dscho committed
1003
extern rfbLogProc rfbLog, rfbErr;
1004
extern void rfbLogPerror(const char *str);
1005 1006 1007 1008 1009 1010 1011

void rfbScheduleCopyRect(rfbScreenInfoPtr rfbScreen,int x1,int y1,int x2,int y2,int dx,int dy);
void rfbScheduleCopyRegion(rfbScreenInfoPtr rfbScreen,sraRegionPtr copyRegion,int dx,int dy);

void rfbDoCopyRect(rfbScreenInfoPtr rfbScreen,int x1,int y1,int x2,int y2,int dx,int dy);
void rfbDoCopyRegion(rfbScreenInfoPtr rfbScreen,sraRegionPtr copyRegion,int dx,int dy);

dscho's avatar
dscho committed
1012
void rfbMarkRectAsModified(rfbScreenInfoPtr rfbScreen,int x1,int y1,int x2,int y2);
1013
void rfbMarkRegionAsModified(rfbScreenInfoPtr rfbScreen,sraRegionPtr modRegion);
1014
void rfbDoNothingWithClient(rfbClientPtr cl);
1015
enum rfbNewClientAction defaultNewClientHook(rfbClientPtr cl);
1016
void rfbRegisterProtocolExtension(rfbProtocolExtension* extension);
1017
void rfbUnregisterProtocolExtension(rfbProtocolExtension* extension);
1018 1019
struct _rfbProtocolExtension* rfbGetExtensionIterator();
void rfbReleaseExtensionIterator();
1020 1021 1022
rfbBool rfbEnableExtension(rfbClientPtr cl, rfbProtocolExtension* extension,
	void* data);
rfbBool rfbDisableExtension(rfbClientPtr cl, rfbProtocolExtension* extension);
1023
void* rfbGetExtensionClientData(rfbClientPtr cl, rfbProtocolExtension* extension);
dscho's avatar
dscho committed
1024

1025
/** to check against plain passwords */
1026
rfbBool rfbCheckPasswordByList(rfbClientPtr cl,const char* response,int len);
dscho's avatar
dscho committed
1027

1028
/* functions to make a vnc server */
dscho's avatar
dscho committed
1029
extern rfbScreenInfoPtr rfbGetScreen(int* argc,char** argv,
1030 1031
 int width,int height,int bitsPerSample,int samplesPerPixel,
 int bytesPerPixel);
dscho's avatar
dscho committed
1032
extern void rfbInitServer(rfbScreenInfoPtr rfbScreen);
dscho's avatar
dscho committed
1033
extern void rfbShutdownServer(rfbScreenInfoPtr rfbScreen,rfbBool disconnectClients);
dscho's avatar
dscho committed
1034 1035 1036 1037
extern void rfbNewFramebuffer(rfbScreenInfoPtr rfbScreen,char *framebuffer,
 int width,int height, int bitsPerSample,int samplesPerPixel,
 int bytesPerPixel);

dscho's avatar
dscho committed
1038
extern void rfbScreenCleanup(rfbScreenInfoPtr screenInfo);
1039
extern void rfbSetServerVersionIdentity(rfbScreenInfoPtr screen, char *fmt, ...);
dscho's avatar
dscho committed
1040

1041 1042 1043 1044 1045 1046
/* functions to accept/refuse a client that has been put on hold
   by a NewClientHookPtr function. Must not be called in other
   situations. */
extern void rfbStartOnHoldClient(rfbClientPtr cl);
extern void rfbRefuseOnHoldClient(rfbClientPtr cl);

dscho's avatar
dscho committed
1047 1048
/* call one of these two functions to service the vnc clients.
 usec are the microseconds the select on the fds waits.
dscho's avatar
dscho committed
1049
 if you are using the event loop, set this to some value > 0, so the
1050 1051
 server doesn't get a high load just by listening.
 rfbProcessEvents() returns TRUE if an update was pending. */
dscho's avatar
dscho committed
1052

1053
extern void rfbRunEventLoop(rfbScreenInfoPtr screenInfo, long usec, rfbBool runInBackground);
1054
extern rfbBool rfbProcessEvents(rfbScreenInfoPtr screenInfo,long usec);
dscho's avatar
dscho committed
1055
extern rfbBool rfbIsActive(rfbScreenInfoPtr screenInfo);
dscho's avatar
dscho committed
1056

1057 1058
/* TightVNC file transfer extension */
void rfbRegisterTightVNCFileTransferExtension();
1059
void rfbUnregisterTightVNCFileTransferExtension();
1060

1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
/* Statistics */
extern char *messageNameServer2Client(uint32_t type, char *buf, int len);
extern char *messageNameClient2Server(uint32_t type, char *buf, int len);
extern char *encodingName(uint32_t enc, char *buf, int len);

extern rfbStatList *rfbStatLookupEncoding(rfbClientPtr cl, uint32_t type);
extern rfbStatList *rfbStatLookupMessage(rfbClientPtr cl, uint32_t type);

/* Each call to rfbStatRecord* adds one to the rect count for that type */
extern void rfbStatRecordEncodingSent(rfbClientPtr cl, uint32_t type, int byteCount, int byteIfRaw);
extern void rfbStatRecordEncodingSentAdd(rfbClientPtr cl, uint32_t type, int byteCount); /* Specifically for tight encoding */
extern void rfbStatRecordEncodingRcvd(rfbClientPtr cl, uint32_t type, int byteCount, int byteIfRaw);
extern void rfbStatRecordMessageSent(rfbClientPtr cl, uint32_t type, int byteCount, int byteIfRaw);
extern void rfbStatRecordMessageRcvd(rfbClientPtr cl, uint32_t type, int byteCount, int byteIfRaw);
extern void rfbResetStats(rfbClientPtr cl);
extern void rfbPrintStats(rfbClientPtr cl);

extern int rfbStatGetSentBytes(rfbClientPtr cl);
extern int rfbStatGetSentBytesIfRaw(rfbClientPtr cl);
extern int rfbStatGetRcvdBytes(rfbClientPtr cl);
extern int rfbStatGetRcvdBytesIfRaw(rfbClientPtr cl);
extern int rfbStatGetMessageCountSent(rfbClientPtr cl, uint32_t type);
extern int rfbStatGetMessageCountRcvd(rfbClientPtr cl, uint32_t type);
extern int rfbStatGetEncodingCountSent(rfbClientPtr cl, uint32_t type);
extern int rfbStatGetEncodingCountRcvd(rfbClientPtr cl, uint32_t type);

1087
/** Set which version you want to advertise 3.3, 3.6, 3.7 and 3.8 are currently supported*/
1088 1089
extern void rfbSetProtocolVersion(rfbScreenInfoPtr rfbScreen, int major_, int minor_);

1090
/** send a TextChat message to a client */
1091
extern rfbBool rfbSendTextChatMessage(rfbClientPtr cl, uint32_t length, char *buffer);
1092 1093


1094 1095 1096 1097
/*
 * Additions for Qt event loop integration
 * Original idea taken from vino.
 */
1098
rfbBool rfbProcessNewConnection(rfbScreenInfoPtr rfbScreen);
1099
rfbBool rfbUpdateClient(rfbClientPtr cl);
1100

1101 1102 1103 1104

#if(defined __cplusplus)
}
#endif
dscho's avatar
dscho committed
1105

1106 1107 1108 1109
/**
 * @}
 */

dscho's avatar
dscho committed
1110

1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
/**
 @page libvncserver_doc LibVNCServer Documentation
 @section create_server Creating a server instance
 To make a server, you just have to initialise a server structure using the
 function rfbGetScreen(), like
 @code
   rfbScreenInfoPtr screen =
     rfbGetScreen(argc,argv,screenwidth,screenheight,8,3,bpp);
 @endcode
 where byte per pixel should be 1, 2 or 4. If performance doesn't matter,
 you may try bpp=3 (internally one cannot use native data types in this
 case; if you want to use this, look at pnmshow24.c).

 You then can set hooks and io functions (see @ref making_it_interactive) or other
 options (see @ref server_options).

 And you allocate the frame buffer like this:
 @code
     screen->frameBuffer = (char*)malloc(screenwidth*screenheight*bpp);
 @endcode
 After that, you initialize the server, like
 @code
   rfbInitServer(screen);
 @endcode
 You can use a blocking event loop, a background (pthread based) event loop,
 or implement your own using the rfbProcessEvents() function.

 @subsection server_options Optional Server Features

 These options have to be set between rfbGetScreen() and rfbInitServer().

 If you already have a socket to talk to, just set rfbScreenInfo::inetdSock
 (originally this is for inetd handling, but why not use it for your purpose?).

 To also start an HTTP server (running on port 5800+display_number), you have
 to set rfbScreenInfo::httpDir to a directory containing vncviewer.jar and
1147
 index.vnc (like the included "webclients" directory).
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276

 @section making_it_interactive Making it interactive

 Whenever you draw something, you have to call
 @code
  rfbMarkRectAsModified(screen,x1,y1,x2,y2).
 @endcode
 This tells LibVNCServer to send updates to all connected clients.

 There exist the following IO functions as members of rfbScreen:
 rfbScreenInfo::kbdAddEvent(), rfbScreenInfo::kbdReleaseAllKeys(), rfbScreenInfo::ptrAddEvent() and rfbScreenInfo::setXCutText()

 rfbScreenInfo::kbdAddEvent()
   is called when a key is pressed.
 rfbScreenInfo::kbdReleaseAllKeys()
   is not called at all (maybe in the future).
 rfbScreenInfo::ptrAddEvent()
   is called when the mouse moves or a button is pressed.
   WARNING: if you want to have proper cursor handling, call
	rfbDefaultPtrAddEvent()
   in your own function. This sets the coordinates of the cursor.
 rfbScreenInfo::setXCutText()
   is called when the selection changes.

 There are only two hooks:
 rfbScreenInfo::newClientHook()
   is called when a new client has connected.
 rfbScreenInfo::displayHook()
   is called just before a frame buffer update is sent.

 You can also override the following methods:
 rfbScreenInfo::getCursorPtr()
   This could be used to make an animated cursor (if you really want ...)
 rfbScreenInfo::setTranslateFunction()
   If you insist on colour maps or something more obscure, you have to
   implement this. Default is a trueColour mapping.

 @section cursor_handling Cursor handling

 The screen holds a pointer
  rfbScreenInfo::cursor
 to the current cursor. Whenever you set it, remember that any dynamically
 created cursor (like return value from rfbMakeXCursor()) is not free'd!

 The rfbCursor structure consists mainly of a mask and a source. The rfbCursor::mask
 describes, which pixels are drawn for the cursor (a cursor needn't be
 rectangular). The rfbCursor::source describes, which colour those pixels should have.

 The standard is an XCursor: a cursor with a foreground and a background
 colour (stored in backRed,backGreen,backBlue and the same for foreground
 in a range from 0-0xffff). Therefore, the arrays "mask" and "source"
 contain pixels as single bits stored in bytes in MSB order. The rows are
 padded, such that each row begins with a new byte (i.e. a 10x4
 cursor's mask has 2x4 bytes, because 2 bytes are needed to hold 10 bits).

 It is however very easy to make a cursor like this:
 @code
 char* cur="    "
           " xx "
	   " x  "
	   "    ";
 char* mask="xxxx"
            "xxxx"
            "xxxx"
            "xxx ";
 rfbCursorPtr c=rfbMakeXCursor(4,4,cur,mask);
 @endcode
 You can even set rfbCursor::mask to NULL in this call and LibVNCServer will calculate
 a mask for you (dynamically, so you have to free it yourself).

 There is also an array named rfbCursor::richSource for colourful cursors. They have
 the same format as the frameBuffer (i.e. if the server is 32 bit,
 a 10x4 cursor has 4x10x4 bytes).

 @section screen_client_difference What is the difference between rfbScreenInfoPtr and rfbClientPtr?

 The rfbScreenInfoPtr is a pointer to a rfbScreenInfo structure, which
 holds information about the server, like pixel format, io functions,
 frame buffer etc. The rfbClientPtr is a pointer to an rfbClientRec structure, which holds
 information about a client, like pixel format, socket of the
 connection, etc. A server can have several clients, but needn't have any. So, if you
 have a server and three clients are connected, you have one instance
 of a rfbScreenInfo and three instances of rfbClientRec's.

 The rfbClientRec structure holds a member rfbClientRec::screen which points to the server.
 So, to access the server from the client structure, you use client->screen.

 To access all clients from a server be sure to use the provided iterator
  rfbGetClientIterator()
 with
  rfbClientIteratorNext()
 and
  rfbReleaseClientIterator()
 to prevent thread clashes.

 @section example_code Example Code

 There are two documented examples included:
  - example.c, a shared scribble sheet
  - pnmshow.c, a program to show PNMs (pictures) over the net.

 The examples are not too well documented, but easy straight forward and a
 good starting point.

 Try example.c: it outputs on which port it listens (default: 5900), so it is
 display 0. To view, call @code	vncviewer :0 @endcode
 You should see a sheet with a gradient and "Hello World!" written on it. Try
 to paint something. Note that everytime you click, there is some bigger blot,
 whereas when you drag the mouse while clicked you draw a line. The size of the
 blot depends on the mouse button you click. Open a second vncviewer with
 the same parameters and watch it as you paint in the other window. This also
 works over internet. You just have to know either the name or the IP of your
 machine. Then it is @code vncviewer machine.where.example.runs.com:0 @endcode
 or similar for the remote client. Now you are ready to type something. Be sure
 that your mouse sits still, because everytime the mouse moves, the cursor is
 reset to the position of the pointer! If you are done with that demo, press
 the down or up arrows. If your viewer supports it, then the dimensions of the
 sheet change. Just press Escape in the viewer. Note that the server still
 runs, even if you closed both windows. When you reconnect now, everything you
 painted and wrote is still there. You can press "Page Up" for a blank page.

 The demo pnmshow.c is much simpler: you either provide a filename as argument
 or pipe a file through stdin. Note that the file has to be a raw pnm/ppm file,
 i.e. a truecolour graphics. Only the Escape key is implemented. This may be
 the best starting point if you want to learn how to use LibVNCServer. You
 are confronted with the fact that the bytes per pixel can only be 8, 16 or 32.
*/

#endif