add libvncserver
[presencevnc] / libvnc / rfb / rfb.h
1 #ifndef RFB_H
2 #define RFB_H
3
4 /*
5  * rfb.h - header file for RFB DDX implementation.
6  */
7
8 /*
9  *  Copyright (C) 2005 Rohit Kumar <rokumar@novell.com>,
10  *                     Johannes E. Schindelin <johannes.schindelin@gmx.de>
11  *  Copyright (C) 2002 RealVNC Ltd.
12  *  OSXvnc Copyright (C) 2001 Dan McGuirk <mcguirk@incompleteness.net>.
13  *  Original Xvnc code Copyright (C) 1999 AT&T Laboratories Cambridge.  
14  *  All Rights Reserved.
15  *
16  *  This is free software; you can redistribute it and/or modify
17  *  it under the terms of the GNU General Public License as published by
18  *  the Free Software Foundation; either version 2 of the License, or
19  *  (at your option) any later version.
20  *
21  *  This software is distributed in the hope that it will be useful,
22  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
23  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24  *  GNU General Public License for more details.
25  *
26  *  You should have received a copy of the GNU General Public License
27  *  along with this software; if not, write to the Free Software
28  *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,
29  *  USA.
30  */
31
32 #if(defined __cplusplus)
33 extern "C"
34 {
35 #endif
36
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <rfb/rfbproto.h>
41
42 #ifdef LIBVNCSERVER_HAVE_SYS_TYPES_H
43 #include <sys/types.h>
44 #endif
45
46 #ifdef __MINGW32__
47 #include <winsock2.h>
48 #endif
49
50 #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD
51 #include <pthread.h>
52 #if 0 /* debugging */
53 #define LOCK(mutex) (rfbLog("%s:%d LOCK(%s,0x%x)\n",__FILE__,__LINE__,#mutex,&(mutex)), pthread_mutex_lock(&(mutex)))
54 #define UNLOCK(mutex) (rfbLog("%s:%d UNLOCK(%s,0x%x)\n",__FILE__,__LINE__,#mutex,&(mutex)), pthread_mutex_unlock(&(mutex)))
55 #define MUTEX(mutex) pthread_mutex_t (mutex)
56 #define INIT_MUTEX(mutex) (rfbLog("%s:%d INIT_MUTEX(%s,0x%x)\n",__FILE__,__LINE__,#mutex,&(mutex)), pthread_mutex_init(&(mutex),NULL))
57 #define TINI_MUTEX(mutex) (rfbLog("%s:%d TINI_MUTEX(%s)\n",__FILE__,__LINE__,#mutex), pthread_mutex_destroy(&(mutex)))
58 #define TSIGNAL(cond) (rfbLog("%s:%d TSIGNAL(%s)\n",__FILE__,__LINE__,#cond), pthread_cond_signal(&(cond)))
59 #define WAIT(cond,mutex) (rfbLog("%s:%d WAIT(%s,%s)\n",__FILE__,__LINE__,#cond,#mutex), pthread_cond_wait(&(cond),&(mutex)))
60 #define COND(cond) pthread_cond_t (cond)
61 #define INIT_COND(cond) (rfbLog("%s:%d INIT_COND(%s)\n",__FILE__,__LINE__,#cond), pthread_cond_init(&(cond),NULL))
62 #define TINI_COND(cond) (rfbLog("%s:%d TINI_COND(%s)\n",__FILE__,__LINE__,#cond), pthread_cond_destroy(&(cond)))
63 #define IF_PTHREADS(x) x
64 #else
65 #if !NONETWORK
66 #define LOCK(mutex) pthread_mutex_lock(&(mutex));
67 #define UNLOCK(mutex) pthread_mutex_unlock(&(mutex));
68 #endif
69 #define MUTEX(mutex) pthread_mutex_t (mutex)
70 #define INIT_MUTEX(mutex) pthread_mutex_init(&(mutex),NULL)
71 #define TINI_MUTEX(mutex) pthread_mutex_destroy(&(mutex))
72 #define TSIGNAL(cond) pthread_cond_signal(&(cond))
73 #define WAIT(cond,mutex) pthread_cond_wait(&(cond),&(mutex))
74 #define COND(cond) pthread_cond_t (cond)
75 #define INIT_COND(cond) pthread_cond_init(&(cond),NULL)
76 #define TINI_COND(cond) pthread_cond_destroy(&(cond))
77 #define IF_PTHREADS(x) x
78 #endif
79 #else
80 #define LOCK(mutex)
81 #define UNLOCK(mutex)
82 #define MUTEX(mutex)
83 #define INIT_MUTEX(mutex)
84 #define TINI_MUTEX(mutex)
85 #define TSIGNAL(cond)
86 #define WAIT(cond,mutex) this_is_unsupported
87 #define COND(cond)
88 #define INIT_COND(cond)
89 #define TINI_COND(cond)
90 #define IF_PTHREADS(x)
91 #endif
92
93 /* end of stuff for autoconf */
94
95 /* if you use pthreads, but don't define LIBVNCSERVER_HAVE_LIBPTHREAD, the structs
96    get all mixed up. So this gives a linker error reminding you to compile
97    the library and your application (at least the parts including rfb.h)
98    with the same support for pthreads. */
99 #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD
100 #ifdef LIBVNCSERVER_HAVE_LIBZ
101 #define rfbInitServer rfbInitServerWithPthreadsAndZRLE
102 #else
103 #define rfbInitServer rfbInitServerWithPthreadsButWithoutZRLE
104 #endif
105 #else
106 #ifdef LIBVNCSERVER_HAVE_LIBZ
107 #define rfbInitServer rfbInitServerWithoutPthreadsButWithZRLE
108 #else
109 #define rfbInitServer rfbInitServerWithoutPthreadsAndZRLE
110 #endif
111 #endif
112
113 struct _rfbClientRec;
114 struct _rfbScreenInfo;
115 struct rfbCursor;
116
117 enum rfbNewClientAction {
118         RFB_CLIENT_ACCEPT,
119         RFB_CLIENT_ON_HOLD,
120         RFB_CLIENT_REFUSE
121 };
122
123 enum rfbSocketState {
124         RFB_SOCKET_INIT,
125         RFB_SOCKET_READY,
126         RFB_SOCKET_SHUTDOWN
127 };
128
129 typedef void (*rfbKbdAddEventProcPtr) (rfbBool down, rfbKeySym keySym, struct _rfbClientRec* cl);
130 typedef void (*rfbKbdReleaseAllKeysProcPtr) (struct _rfbClientRec* cl);
131 typedef void (*rfbPtrAddEventProcPtr) (int buttonMask, int x, int y, struct _rfbClientRec* cl);
132 typedef void (*rfbSetXCutTextProcPtr) (char* str,int len, struct _rfbClientRec* cl);
133 typedef struct rfbCursor* (*rfbGetCursorProcPtr) (struct _rfbClientRec* pScreen);
134 typedef rfbBool (*rfbSetTranslateFunctionProcPtr)(struct _rfbClientRec* cl);
135 typedef rfbBool (*rfbPasswordCheckProcPtr)(struct _rfbClientRec* cl,const char* encryptedPassWord,int len);
136 typedef enum rfbNewClientAction (*rfbNewClientHookPtr)(struct _rfbClientRec* cl);
137 typedef void (*rfbDisplayHookPtr)(struct _rfbClientRec* cl);
138 /* support the capability to view the caps/num/scroll states of the X server */
139 typedef int  (*rfbGetKeyboardLedStateHookPtr)(struct _rfbScreenInfo* screen);
140 /* If x==1 and y==1 then set the whole display
141  * else find the window underneath x and y and set the framebuffer to the dimensions
142  * of that window
143  */
144 typedef void (*rfbSetSingleWindowProcPtr) (struct _rfbClientRec* cl, int x, int y);
145 /* Status determines if the X11 server permits input from the local user 
146  * status==0 or 1
147  */
148 typedef void (*rfbSetServerInputProcPtr) (struct _rfbClientRec* cl, int status);
149 /* Permit the server to allow or deny filetransfers.   This is defaulted to deny
150  * It is called when a client initiates a connection to determine if it is permitted.
151  */
152 typedef int  (*rfbFileTransferPermitted) (struct _rfbClientRec* cl);
153 /* Handle the textchat messages */
154 typedef void (*rfbSetTextChat) (struct _rfbClientRec* cl, int length, char *string);
155
156 typedef struct {
157   uint32_t count;
158   rfbBool is16; /* is the data format short? */
159   union {
160     uint8_t* bytes;
161     uint16_t* shorts;
162   } data; /* there have to be count*3 entries */
163 } rfbColourMap;
164
165 /*
166  * Security handling (RFB protocol version 3.7)
167  */
168
169 typedef struct _rfbSecurity {
170         uint8_t type;
171         void (*handler)(struct _rfbClientRec* cl);
172         struct _rfbSecurity* next;
173 } rfbSecurityHandler;
174
175 /*
176  * Protocol extension handling.
177  */
178
179 typedef struct _rfbProtocolExtension {
180         /* returns FALSE if extension should be deactivated for client.
181            if newClient == NULL, it is always deactivated. */
182         rfbBool (*newClient)(struct _rfbClientRec* client, void** data);
183         /* returns FALSE if extension should be deactivated for client.
184            if init == NULL, it stays activated. */
185         rfbBool (*init)(struct _rfbClientRec* client, void* data);
186         /* if pseudoEncodings is not NULL, it contains a 0 terminated
187            list of the pseudo encodings handled by this extension. */
188         int *pseudoEncodings;
189         /* returns TRUE if that pseudo encoding is handled by the extension.
190            encodingNumber==0 means "reset encodings". */
191         rfbBool (*enablePseudoEncoding)(struct _rfbClientRec* client,
192                         void** data, int encodingNumber);
193         /* returns TRUE if message was handled */
194         rfbBool (*handleMessage)(struct _rfbClientRec* client,
195                                 void* data,
196                                 const rfbClientToServerMsg* message);
197         void (*close)(struct _rfbClientRec* client, void* data);
198         void (*usage)(void);
199         /* processArguments returns the number of handled arguments */
200         int (*processArgument)(int argc, char *argv[]);
201         struct _rfbProtocolExtension* next;
202 } rfbProtocolExtension;
203
204 typedef struct _rfbExtensionData {
205         rfbProtocolExtension* extension;
206         void* data;
207         struct _rfbExtensionData* next;
208 } rfbExtensionData;
209
210 /*
211  * Per-screen (framebuffer) structure.  There can be as many as you wish,
212  * each serving different clients. However, you have to call
213  * rfbProcessEvents for each of these.
214  */
215
216 typedef struct _rfbScreenInfo
217 {
218     /* this structure has children that are scaled versions of this screen */
219     struct _rfbScreenInfo *scaledScreenNext;
220     int scaledScreenRefCount;
221
222     int width;
223     int paddedWidthInBytes;
224     int height;
225     int depth;
226     int bitsPerPixel;
227     int sizeInBytes;
228
229     rfbPixel blackPixel;
230     rfbPixel whitePixel;
231
232     /* some screen specific data can be put into a struct where screenData
233      * points to. You need this if you have more than one screen at the
234      * same time while using the same functions.
235      */
236     void* screenData;
237   
238     /* additions by libvncserver */
239
240     rfbPixelFormat serverFormat;
241     rfbColourMap colourMap; /* set this if rfbServerFormat.trueColour==FALSE */
242     const char* desktopName;
243     char thisHost[255];
244
245     rfbBool autoPort;
246     int port;
247     SOCKET listenSock;
248     int maxSock;
249     int maxFd;
250 #ifdef __MINGW32__
251     struct fd_set allFds;
252 #else
253     fd_set allFds;
254 #endif
255
256     enum rfbSocketState socketState;
257     SOCKET inetdSock;
258     rfbBool inetdInitDone;
259
260     int udpPort;
261     SOCKET udpSock;
262     struct _rfbClientRec* udpClient;
263     rfbBool udpSockConnected;
264     struct sockaddr_in udpRemoteAddr;
265
266     int maxClientWait;
267
268     /* http stuff */
269     rfbBool httpInitDone;
270     rfbBool httpEnableProxyConnect;
271     int httpPort;
272     char* httpDir;
273     SOCKET httpListenSock;
274     SOCKET httpSock;
275
276     rfbPasswordCheckProcPtr passwordCheck;
277     void* authPasswdData;
278     /* If rfbAuthPasswdData is given a list, this is the first
279        view only password. */
280     int authPasswdFirstViewOnly;
281
282     /* send only this many rectangles in one update */
283     int maxRectsPerUpdate;
284     /* this is the amount of milliseconds to wait at least before sending
285      * an update. */
286     int deferUpdateTime;
287 #ifdef TODELETE
288     char* screen;
289 #endif
290     rfbBool alwaysShared;
291     rfbBool neverShared;
292     rfbBool dontDisconnect;
293     struct _rfbClientRec* clientHead;
294     struct _rfbClientRec* pointerClient;  /* "Mutex" for pointer events */
295
296
297     /* cursor */
298     int cursorX, cursorY,underCursorBufferLen;
299     char* underCursorBuffer;
300     rfbBool dontConvertRichCursorToXCursor;
301     struct rfbCursor* cursor;
302
303     /* the frameBufferhas to be supplied by the serving process.
304      * The buffer will not be freed by 
305      */
306     char* frameBuffer;
307     rfbKbdAddEventProcPtr kbdAddEvent;
308     rfbKbdReleaseAllKeysProcPtr kbdReleaseAllKeys;
309     rfbPtrAddEventProcPtr ptrAddEvent;
310     rfbSetXCutTextProcPtr setXCutText;
311     rfbGetCursorProcPtr getCursorPtr;
312     rfbSetTranslateFunctionProcPtr setTranslateFunction;
313     rfbSetSingleWindowProcPtr setSingleWindow;
314     rfbSetServerInputProcPtr  setServerInput;
315     rfbFileTransferPermitted  getFileTransferPermission;
316     rfbSetTextChat            setTextChat;
317     
318     /* newClientHook is called just after a new client is created */
319     rfbNewClientHookPtr newClientHook;
320     /* displayHook is called just before a frame buffer update */
321     rfbDisplayHookPtr displayHook;
322
323     /* These hooks are called to pass keyboard state back to the client */
324     rfbGetKeyboardLedStateHookPtr getKeyboardLedStateHook;
325
326 #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD
327     MUTEX(cursorMutex);
328     rfbBool backgroundLoop;
329 #endif
330
331     /* if TRUE, an ignoring signal handler is installed for SIGPIPE */
332     rfbBool ignoreSIGPIPE;
333
334     /* if not zero, only a slice of this height is processed every time
335      * an update should be sent. This should make working on a slow
336      * link more interactive. */
337     int progressiveSliceHeight;
338
339     in_addr_t listenInterface;
340     int deferPtrUpdateTime;
341
342     /* handle as many input events as possible (default off) */
343     rfbBool handleEventsEagerly;
344
345     /* rfbEncodingServerIdentity */
346     char *versionString;
347
348     /* What does the server tell the new clients which version it supports */
349     int protocolMajorVersion;
350     int protocolMinorVersion;
351
352     /* command line authorization of file transfers */
353     rfbBool permitFileTransfer;
354 } rfbScreenInfo, *rfbScreenInfoPtr;
355
356
357 /*
358  * rfbTranslateFnType is the type of translation functions.
359  */
360
361 typedef void (*rfbTranslateFnType)(char *table, rfbPixelFormat *in,
362                                    rfbPixelFormat *out,
363                                    char *iptr, char *optr,
364                                    int bytesBetweenInputLines,
365                                    int width, int height);
366
367
368 /* region stuff */
369
370 struct sraRegion;
371 typedef struct sraRegion* sraRegionPtr;
372
373 /*
374  * Per-client structure.
375  */
376
377 typedef void (*ClientGoneHookPtr)(struct _rfbClientRec* cl);
378
379 typedef struct _rfbFileTransferData {
380   int fd;
381   int compressionEnabled;
382   int fileSize;
383   int numPackets;
384   int receiving;
385   int sending;
386 } rfbFileTransferData;
387
388
389 typedef struct _rfbStatList {
390     uint32_t type;
391     uint32_t sentCount;
392     uint32_t bytesSent;
393     uint32_t bytesSentIfRaw;
394     uint32_t rcvdCount;
395     uint32_t bytesRcvd;
396     uint32_t bytesRcvdIfRaw;
397     struct _rfbStatList *Next;
398 } rfbStatList;
399
400 typedef struct _rfbClientRec {
401   
402     /* back pointer to the screen */
403     rfbScreenInfoPtr screen;
404
405      /* points to a scaled version of the screen buffer in cl->scaledScreenList */
406      rfbScreenInfoPtr scaledScreen;
407      /* how did the client tell us it wanted the screen changed?  Ultra style or palm style? */
408      rfbBool PalmVNC;
409     
410   
411     /* private data. You should put any application client specific data
412      * into a struct and let clientData point to it. Don't forget to
413      * free the struct via clientGoneHook!
414      *
415      * This is useful if the IO functions have to behave client specific.
416      */
417     void* clientData;
418     ClientGoneHookPtr clientGoneHook;
419
420     SOCKET sock;
421     char *host;
422
423     /* RFB protocol minor version number */
424     int protocolMajorVersion;
425     int protocolMinorVersion;
426
427 #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD
428     pthread_t client_thread;
429 #endif
430                                 /* Possible client states: */
431     enum {
432         RFB_PROTOCOL_VERSION,   /* establishing protocol version */
433         RFB_SECURITY_TYPE,      /* negotiating security (RFB v.3.7) */
434         RFB_AUTHENTICATION,     /* authenticating */
435         RFB_INITIALISATION,     /* sending initialisation messages */
436         RFB_NORMAL              /* normal protocol messages */
437     } state;
438
439     rfbBool reverseConnection;
440     rfbBool onHold;
441     rfbBool readyForSetColourMapEntries;
442     rfbBool useCopyRect;
443     int preferredEncoding;
444     int correMaxWidth, correMaxHeight;
445
446     rfbBool viewOnly;
447
448     /* The following member is only used during VNC authentication */
449     uint8_t authChallenge[CHALLENGESIZE];
450
451     /* The following members represent the update needed to get the client's
452        framebuffer from its present state to the current state of our
453        framebuffer.
454
455        If the client does not accept CopyRect encoding then the update is
456        simply represented as the region of the screen which has been modified
457        (modifiedRegion).
458
459        If the client does accept CopyRect encoding, then the update consists of
460        two parts.  First we have a single copy from one region of the screen to
461        another (the destination of the copy is copyRegion), and second we have
462        the region of the screen which has been modified in some other way
463        (modifiedRegion).
464
465        Although the copy is of a single region, this region may have many
466        rectangles.  When sending an update, the copyRegion is always sent
467        before the modifiedRegion.  This is because the modifiedRegion may
468        overlap parts of the screen which are in the source of the copy.
469
470        In fact during normal processing, the modifiedRegion may even overlap
471        the destination copyRegion.  Just before an update is sent we remove
472        from the copyRegion anything in the modifiedRegion. */
473
474     sraRegionPtr copyRegion;    /* the destination region of the copy */
475     int copyDX, copyDY;         /* the translation by which the copy happens */
476
477     sraRegionPtr modifiedRegion;
478
479     /* As part of the FramebufferUpdateRequest, a client can express interest
480        in a subrectangle of the whole framebuffer.  This is stored in the
481        requestedRegion member.  In the normal case this is the whole
482        framebuffer if the client is ready, empty if it's not. */
483
484     sraRegionPtr requestedRegion;
485
486     /* The following member represents the state of the "deferred update" timer
487        - when the framebuffer is modified and the client is ready, in most
488        cases it is more efficient to defer sending the update by a few
489        milliseconds so that several changes to the framebuffer can be combined
490        into a single update. */
491
492       struct timeval startDeferring;
493       struct timeval startPtrDeferring;
494       int lastPtrX;
495       int lastPtrY;
496       int lastPtrButtons;
497
498     /* translateFn points to the translation function which is used to copy
499        and translate a rectangle from the framebuffer to an output buffer. */
500
501     rfbTranslateFnType translateFn;
502     char *translateLookupTable;
503     rfbPixelFormat format;
504
505     /*
506      * UPDATE_BUF_SIZE must be big enough to send at least one whole line of the
507      * framebuffer.  So for a max screen width of say 2K with 32-bit pixels this
508      * means 8K minimum.
509      */
510
511 #define UPDATE_BUF_SIZE 30000
512
513     char updateBuf[UPDATE_BUF_SIZE];
514     int ublen;
515
516     /* statistics */
517     struct _rfbStatList *statEncList;
518     struct _rfbStatList *statMsgList;
519     int rawBytesEquivalent;
520     int bytesSent;
521         
522 #ifdef LIBVNCSERVER_HAVE_LIBZ
523     /* zlib encoding -- necessary compression state info per client */
524
525     struct z_stream_s compStream;
526     rfbBool compStreamInited;
527     uint32_t zlibCompressLevel;
528     /* the quality level is also used by ZYWRLE */
529     int tightQualityLevel;
530
531 #ifdef LIBVNCSERVER_HAVE_LIBJPEG
532     /* tight encoding -- preserve zlib streams' state for each client */
533     z_stream zsStruct[4];
534     rfbBool zsActive[4];
535     int zsLevel[4];
536     int tightCompressLevel;
537 #endif
538 #endif
539
540     /* Ultra Encoding support */
541     rfbBool compStreamInitedLZO;
542     char *lzoWrkMem;
543
544     rfbFileTransferData fileTransfer;
545
546     int     lastKeyboardLedState;     /* keep track of last value so we can send *change* events */
547     rfbBool enableSupportedMessages;  /* client supports SupportedMessages encoding */
548     rfbBool enableSupportedEncodings; /* client supports SupportedEncodings encoding */
549     rfbBool enableServerIdentity;     /* client supports ServerIdentity encoding */
550     rfbBool enableKeyboardLedState;   /* client supports KeyboardState encoding */
551     rfbBool enableLastRectEncoding;   /* client supports LastRect encoding */
552     rfbBool enableCursorShapeUpdates; /* client supports cursor shape updates */
553     rfbBool enableCursorPosUpdates;   /* client supports cursor position updates */
554     rfbBool useRichCursorEncoding;    /* rfbEncodingRichCursor is preferred */
555     rfbBool cursorWasChanged;         /* cursor shape update should be sent */
556     rfbBool cursorWasMoved;           /* cursor position update should be sent */
557     int cursorX,cursorY;              /* the coordinates of the cursor,
558                                          if enableCursorShapeUpdates = FALSE */
559
560     rfbBool useNewFBSize;             /* client supports NewFBSize encoding */
561     rfbBool newFBSizePending;         /* framebuffer size was changed */
562
563     struct _rfbClientRec *prev;
564     struct _rfbClientRec *next;
565
566 #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD
567     /* whenever a client is referenced, the refCount has to be incremented
568        and afterwards decremented, so that the client is not cleaned up
569        while being referenced.
570        Use the functions rfbIncrClientRef(cl) and rfbDecrClientRef(cl);
571     */
572     int refCount;
573     MUTEX(refCountMutex);
574     COND(deleteCond);
575
576     MUTEX(outputMutex);
577     MUTEX(updateMutex);
578     COND(updateCond);
579 #endif
580
581 #ifdef LIBVNCSERVER_HAVE_LIBZ
582     void* zrleData;
583     int zywrleLevel;
584     int zywrleBuf[rfbZRLETileWidth * rfbZRLETileHeight];
585 #endif
586
587     /* if progressive updating is on, this variable holds the current
588      * y coordinate of the progressive slice. */
589     int progressiveSliceY;
590
591     rfbExtensionData* extensions;
592 } rfbClientRec, *rfbClientPtr;
593
594 /*
595  * This macro is used to test whether there is a framebuffer update needing to
596  * be sent to the client.
597  */
598
599 #define FB_UPDATE_PENDING(cl)                                              \
600      (((cl)->enableCursorShapeUpdates && (cl)->cursorWasChanged) ||        \
601      (((cl)->enableCursorShapeUpdates == FALSE &&                          \
602        ((cl)->cursorX != (cl)->screen->cursorX ||                          \
603         (cl)->cursorY != (cl)->screen->cursorY))) ||                       \
604      ((cl)->useNewFBSize && (cl)->newFBSizePending) ||                     \
605      ((cl)->enableCursorPosUpdates && (cl)->cursorWasMoved) ||             \
606      !sraRgnEmpty((cl)->copyRegion) || !sraRgnEmpty((cl)->modifiedRegion))
607
608 /*
609  * Macros for endian swapping.
610  */
611
612 #define Swap16(s) ((((s) & 0xff) << 8) | (((s) >> 8) & 0xff))
613
614 #define Swap24(l) ((((l) & 0xff) << 16) | (((l) >> 16) & 0xff) | \
615                    (((l) & 0x00ff00)))
616
617 #define Swap32(l) (((l) >> 24) | \
618                    (((l) & 0x00ff0000) >> 8)  | \
619                    (((l) & 0x0000ff00) << 8)  | \
620                    ((l) << 24))
621
622
623 extern char rfbEndianTest;
624
625 #define Swap16IfLE(s) (rfbEndianTest ? Swap16(s) : (s))
626 #define Swap24IfLE(l) (rfbEndianTest ? Swap24(l) : (l))
627 #define Swap32IfLE(l) (rfbEndianTest ? Swap32(l) : (l))
628
629 /* UltraVNC uses some windows structures unmodified, so the viewer expects LittleEndian Data */
630 #define Swap16IfBE(s) (rfbEndianTest ? (s) : Swap16(s))
631 #define Swap24IfBE(l) (rfbEndianTest ? (l) : Swap24(l))
632 #define Swap32IfBE(l) (rfbEndianTest ? (l) : Swap32(l))
633
634 /* sockets.c */
635
636 extern int rfbMaxClientWait;
637
638 extern void rfbInitSockets(rfbScreenInfoPtr rfbScreen);
639 extern void rfbShutdownSockets(rfbScreenInfoPtr rfbScreen);
640 extern void rfbDisconnectUDPSock(rfbScreenInfoPtr rfbScreen);
641 extern void rfbCloseClient(rfbClientPtr cl);
642 extern int rfbReadExact(rfbClientPtr cl, char *buf, int len);
643 extern int rfbReadExactTimeout(rfbClientPtr cl, char *buf, int len,int timeout);
644 extern int rfbWriteExact(rfbClientPtr cl, const char *buf, int len);
645 extern int rfbCheckFds(rfbScreenInfoPtr rfbScreen,long usec);
646 extern int rfbConnect(rfbScreenInfoPtr rfbScreen, char* host, int port);
647 extern int rfbConnectToTcpAddr(char* host, int port);
648 extern int rfbListenOnTCPPort(int port, in_addr_t iface);
649 extern int rfbListenOnUDPPort(int port, in_addr_t iface);
650 extern int rfbStringToAddr(char* string,in_addr_t* addr);
651
652 /* rfbserver.c */
653
654 /* Routines to iterate over the client list in a thread-safe way.
655    Only a single iterator can be in use at a time process-wide. */
656 typedef struct rfbClientIterator *rfbClientIteratorPtr;
657
658 extern void rfbClientListInit(rfbScreenInfoPtr rfbScreen);
659 extern rfbClientIteratorPtr rfbGetClientIterator(rfbScreenInfoPtr rfbScreen);
660 extern rfbClientPtr rfbClientIteratorNext(rfbClientIteratorPtr iterator);
661 extern void rfbReleaseClientIterator(rfbClientIteratorPtr iterator);
662 extern void rfbIncrClientRef(rfbClientPtr cl);
663 extern void rfbDecrClientRef(rfbClientPtr cl);
664
665 extern void rfbNewClientConnection(rfbScreenInfoPtr rfbScreen,int sock);
666 extern rfbClientPtr rfbNewClient(rfbScreenInfoPtr rfbScreen,int sock);
667 extern rfbClientPtr rfbNewUDPClient(rfbScreenInfoPtr rfbScreen);
668 extern rfbClientPtr rfbReverseConnection(rfbScreenInfoPtr rfbScreen,char *host, int port);
669 extern void rfbClientConnectionGone(rfbClientPtr cl);
670 extern void rfbProcessClientMessage(rfbClientPtr cl);
671 extern void rfbClientConnFailed(rfbClientPtr cl, char *reason);
672 extern void rfbNewUDPConnection(rfbScreenInfoPtr rfbScreen,int sock);
673 extern void rfbProcessUDPInput(rfbScreenInfoPtr rfbScreen);
674 extern rfbBool rfbSendFramebufferUpdate(rfbClientPtr cl, sraRegionPtr updateRegion);
675 extern rfbBool rfbSendRectEncodingRaw(rfbClientPtr cl, int x,int y,int w,int h);
676 extern rfbBool rfbSendUpdateBuf(rfbClientPtr cl);
677 extern void rfbSendServerCutText(rfbScreenInfoPtr rfbScreen,char *str, int len);
678 extern rfbBool rfbSendCopyRegion(rfbClientPtr cl,sraRegionPtr reg,int dx,int dy);
679 extern rfbBool rfbSendLastRectMarker(rfbClientPtr cl);
680 extern rfbBool rfbSendNewFBSize(rfbClientPtr cl, int w, int h);
681 extern rfbBool rfbSendSetColourMapEntries(rfbClientPtr cl, int firstColour, int nColours);
682 extern void rfbSendBell(rfbScreenInfoPtr rfbScreen);
683
684 extern char *rfbProcessFileTransferReadBuffer(rfbClientPtr cl, uint32_t length);
685 extern rfbBool rfbSendFileTransferChunk(rfbClientPtr cl);
686 extern rfbBool rfbSendDirContent(rfbClientPtr cl, int length, char *buffer);
687 extern rfbBool rfbSendFileTransferMessage(rfbClientPtr cl, uint8_t contentType, uint8_t contentParam, uint32_t size, uint32_t length, char *buffer);
688 extern char *rfbProcessFileTransferReadBuffer(rfbClientPtr cl, uint32_t length);
689 extern rfbBool rfbProcessFileTransfer(rfbClientPtr cl, uint8_t contentType, uint8_t contentParam, uint32_t size, uint32_t length);
690
691 void rfbGotXCutText(rfbScreenInfoPtr rfbScreen, char *str, int len);
692
693 /* translate.c */
694
695 extern rfbBool rfbEconomicTranslate;
696
697 extern void rfbTranslateNone(char *table, rfbPixelFormat *in,
698                              rfbPixelFormat *out,
699                              char *iptr, char *optr,
700                              int bytesBetweenInputLines,
701                              int width, int height);
702 extern rfbBool rfbSetTranslateFunction(rfbClientPtr cl);
703 extern rfbBool rfbSetClientColourMap(rfbClientPtr cl, int firstColour, int nColours);
704 extern void rfbSetClientColourMaps(rfbScreenInfoPtr rfbScreen, int firstColour, int nColours);
705
706 /* httpd.c */
707
708 extern void rfbHttpInitSockets(rfbScreenInfoPtr rfbScreen);
709 extern void rfbHttpShutdownSockets(rfbScreenInfoPtr rfbScreen);
710 extern void rfbHttpCheckFds(rfbScreenInfoPtr rfbScreen);
711
712
713
714 /* auth.c */
715
716 extern void rfbAuthNewClient(rfbClientPtr cl);
717 extern void rfbProcessClientSecurityType(rfbClientPtr cl);
718 extern void rfbAuthProcessClientMessage(rfbClientPtr cl);
719 extern void rfbRegisterSecurityHandler(rfbSecurityHandler* handler);
720 extern void rfbUnregisterSecurityHandler(rfbSecurityHandler* handler);
721
722 /* rre.c */
723
724 extern rfbBool rfbSendRectEncodingRRE(rfbClientPtr cl, int x,int y,int w,int h);
725
726
727 /* corre.c */
728
729 extern rfbBool rfbSendRectEncodingCoRRE(rfbClientPtr cl, int x,int y,int w,int h);
730
731
732 /* hextile.c */
733
734 extern rfbBool rfbSendRectEncodingHextile(rfbClientPtr cl, int x, int y, int w,
735                                        int h);
736
737 /* ultra.c */
738
739 /* Set maximum ultra rectangle size in pixels.  Always allow at least
740  * two scan lines.
741  */
742 #define ULTRA_MAX_RECT_SIZE (128*256)
743 #define ULTRA_MAX_SIZE(min) ((( min * 2 ) > ULTRA_MAX_RECT_SIZE ) ? \
744                             ( min * 2 ) : ULTRA_MAX_RECT_SIZE )
745
746 extern rfbBool rfbSendRectEncodingUltra(rfbClientPtr cl, int x,int y,int w,int h);
747
748
749 #ifdef LIBVNCSERVER_HAVE_LIBZ
750 /* zlib.c */
751
752 /* Minimum zlib rectangle size in bytes.  Anything smaller will
753  * not compress well due to overhead.
754  */
755 #define VNC_ENCODE_ZLIB_MIN_COMP_SIZE (17)
756
757 /* Set maximum zlib rectangle size in pixels.  Always allow at least
758  * two scan lines.
759  */
760 #define ZLIB_MAX_RECT_SIZE (128*256)
761 #define ZLIB_MAX_SIZE(min) ((( min * 2 ) > ZLIB_MAX_RECT_SIZE ) ? \
762                             ( min * 2 ) : ZLIB_MAX_RECT_SIZE )
763
764 extern rfbBool rfbSendRectEncodingZlib(rfbClientPtr cl, int x, int y, int w,
765                                     int h);
766
767 #ifdef LIBVNCSERVER_HAVE_LIBJPEG
768 /* tight.c */
769
770 #define TIGHT_DEFAULT_COMPRESSION  6
771
772 extern rfbBool rfbTightDisableGradient;
773
774 extern int rfbNumCodedRectsTight(rfbClientPtr cl, int x,int y,int w,int h);
775 extern rfbBool rfbSendRectEncodingTight(rfbClientPtr cl, int x,int y,int w,int h);
776
777 #endif
778 #endif
779
780
781 /* cursor.c */
782
783 typedef struct rfbCursor {
784     /* set this to true if LibVNCServer has to free this cursor */
785     rfbBool cleanup, cleanupSource, cleanupMask, cleanupRichSource;
786     unsigned char *source;                      /* points to bits */
787     unsigned char *mask;                        /* points to bits */
788     unsigned short width, height, xhot, yhot;   /* metrics */
789     unsigned short foreRed, foreGreen, foreBlue; /* device-independent colour */
790     unsigned short backRed, backGreen, backBlue; /* device-independent colour */
791     unsigned char *richSource; /* source bytes for a rich cursor */
792     unsigned char *alphaSource; /* source for alpha blending info */
793     rfbBool alphaPreMultiplied; /* if richSource already has alpha applied */
794 } rfbCursor, *rfbCursorPtr;
795 extern unsigned char rfbReverseByte[0x100];
796
797 extern rfbBool rfbSendCursorShape(rfbClientPtr cl/*, rfbScreenInfoPtr pScreen*/);
798 extern rfbBool rfbSendCursorPos(rfbClientPtr cl);
799 extern void rfbConvertLSBCursorBitmapOrMask(int width,int height,unsigned char* bitmap);
800 extern rfbCursorPtr rfbMakeXCursor(int width,int height,char* cursorString,char* maskString);
801 extern char* rfbMakeMaskForXCursor(int width,int height,char* cursorString);
802 extern char* rfbMakeMaskFromAlphaSource(int width,int height,unsigned char* alphaSource);
803 extern void rfbMakeXCursorFromRichCursor(rfbScreenInfoPtr rfbScreen,rfbCursorPtr cursor);
804 extern void rfbMakeRichCursorFromXCursor(rfbScreenInfoPtr rfbScreen,rfbCursorPtr cursor);
805 extern void rfbFreeCursor(rfbCursorPtr cursor);
806 extern void rfbSetCursor(rfbScreenInfoPtr rfbScreen,rfbCursorPtr c);
807
808 /* cursor handling for the pointer */
809 extern void rfbDefaultPtrAddEvent(int buttonMask,int x,int y,rfbClientPtr cl);
810
811 /* zrle.c */
812 #ifdef LIBVNCSERVER_HAVE_LIBZ
813 extern rfbBool rfbSendRectEncodingZRLE(rfbClientPtr cl, int x, int y, int w,int h);
814 #endif
815
816 /* stats.c */
817
818 extern void rfbResetStats(rfbClientPtr cl);
819 extern void rfbPrintStats(rfbClientPtr cl);
820
821 /* font.c */
822
823 typedef struct rfbFontData {
824   unsigned char* data;
825   /*
826     metaData is a 256*5 array:
827     for each character
828     (offset,width,height,x,y)
829   */
830   int* metaData;
831 } rfbFontData,* rfbFontDataPtr;
832
833 int rfbDrawChar(rfbScreenInfoPtr rfbScreen,rfbFontDataPtr font,int x,int y,unsigned char c,rfbPixel colour);
834 void rfbDrawString(rfbScreenInfoPtr rfbScreen,rfbFontDataPtr font,int x,int y,const char* string,rfbPixel colour);
835 /* if colour==backColour, background is transparent */
836 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);
837 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);
838 int rfbWidthOfString(rfbFontDataPtr font,const char* string);
839 int rfbWidthOfChar(rfbFontDataPtr font,unsigned char c);
840 void rfbFontBBox(rfbFontDataPtr font,unsigned char c,int* x1,int* y1,int* x2,int* y2);
841 /* this returns the smallest box enclosing any character of font. */
842 void rfbWholeFontBBox(rfbFontDataPtr font,int *x1, int *y1, int *x2, int *y2);
843
844 /* dynamically load a linux console font (4096 bytes, 256 glyphs a 8x16 */
845 rfbFontDataPtr rfbLoadConsoleFont(char *filename);
846 /* free a dynamically loaded font */
847 void rfbFreeFont(rfbFontDataPtr font);
848
849 /* draw.c */
850
851 void rfbFillRect(rfbScreenInfoPtr s,int x1,int y1,int x2,int y2,rfbPixel col);
852 void rfbDrawPixel(rfbScreenInfoPtr s,int x,int y,rfbPixel col);
853 void rfbDrawLine(rfbScreenInfoPtr s,int x1,int y1,int x2,int y2,rfbPixel col);
854
855 /* selbox.c */
856
857 /* this opens a modal select box. list is an array of strings, the end marked
858    with a NULL.
859    It returns the index in the list or -1 if cancelled or something else
860    wasn't kosher. */
861 typedef void (*SelectionChangedHookPtr)(int _index);
862 extern int rfbSelectBox(rfbScreenInfoPtr rfbScreen,
863                         rfbFontDataPtr font, char** list,
864                         int x1, int y1, int x2, int y2,
865                         rfbPixel foreColour, rfbPixel backColour,
866                         int border,SelectionChangedHookPtr selChangedHook);
867
868 /* cargs.c */
869
870 extern void rfbUsage(void);
871 extern void rfbPurgeArguments(int* argc,int* position,int count,char *argv[]);
872 extern rfbBool rfbProcessArguments(rfbScreenInfoPtr rfbScreen,int* argc, char *argv[]);
873 extern rfbBool rfbProcessSizeArguments(int* width,int* height,int* bpp,int* argc, char *argv[]);
874
875 /* main.c */
876
877 extern void rfbLogEnable(int enabled);
878 typedef void (*rfbLogProc)(const char *format, ...);
879 extern rfbLogProc rfbLog, rfbErr;
880 extern void rfbLogPerror(const char *str);
881
882 void rfbScheduleCopyRect(rfbScreenInfoPtr rfbScreen,int x1,int y1,int x2,int y2,int dx,int dy);
883 void rfbScheduleCopyRegion(rfbScreenInfoPtr rfbScreen,sraRegionPtr copyRegion,int dx,int dy);
884
885 void rfbDoCopyRect(rfbScreenInfoPtr rfbScreen,int x1,int y1,int x2,int y2,int dx,int dy);
886 void rfbDoCopyRegion(rfbScreenInfoPtr rfbScreen,sraRegionPtr copyRegion,int dx,int dy);
887
888 void rfbMarkRectAsModified(rfbScreenInfoPtr rfbScreen,int x1,int y1,int x2,int y2);
889 void rfbMarkRegionAsModified(rfbScreenInfoPtr rfbScreen,sraRegionPtr modRegion);
890 void rfbDoNothingWithClient(rfbClientPtr cl);
891 enum rfbNewClientAction defaultNewClientHook(rfbClientPtr cl);
892 void rfbRegisterProtocolExtension(rfbProtocolExtension* extension);
893 void rfbUnregisterProtocolExtension(rfbProtocolExtension* extension);
894 struct _rfbProtocolExtension* rfbGetExtensionIterator();
895 void rfbReleaseExtensionIterator();
896 rfbBool rfbEnableExtension(rfbClientPtr cl, rfbProtocolExtension* extension,
897         void* data);
898 rfbBool rfbDisableExtension(rfbClientPtr cl, rfbProtocolExtension* extension);
899 void* rfbGetExtensionClientData(rfbClientPtr cl, rfbProtocolExtension* extension);
900
901 /* to check against plain passwords */
902 rfbBool rfbCheckPasswordByList(rfbClientPtr cl,const char* response,int len);
903
904 /* functions to make a vnc server */
905 extern rfbScreenInfoPtr rfbGetScreen(int* argc,char** argv,
906  int width,int height,int bitsPerSample,int samplesPerPixel,
907  int bytesPerPixel);
908 extern void rfbInitServer(rfbScreenInfoPtr rfbScreen);
909 extern void rfbShutdownServer(rfbScreenInfoPtr rfbScreen,rfbBool disconnectClients);
910 extern void rfbNewFramebuffer(rfbScreenInfoPtr rfbScreen,char *framebuffer,
911  int width,int height, int bitsPerSample,int samplesPerPixel,
912  int bytesPerPixel);
913
914 extern void rfbScreenCleanup(rfbScreenInfoPtr screenInfo);
915 extern void rfbSetServerVersionIdentity(rfbScreenInfoPtr screen, char *fmt, ...);
916
917 /* functions to accept/refuse a client that has been put on hold
918    by a NewClientHookPtr function. Must not be called in other
919    situations. */
920 extern void rfbStartOnHoldClient(rfbClientPtr cl);
921 extern void rfbRefuseOnHoldClient(rfbClientPtr cl);
922
923 /* call one of these two functions to service the vnc clients.
924  usec are the microseconds the select on the fds waits.
925  if you are using the event loop, set this to some value > 0, so the
926  server doesn't get a high load just by listening.
927  rfbProcessEvents() returns TRUE if an update was pending. */
928
929 extern void rfbRunEventLoop(rfbScreenInfoPtr screenInfo, long usec, rfbBool runInBackground);
930 extern rfbBool rfbProcessEvents(rfbScreenInfoPtr screenInfo,long usec);
931 extern rfbBool rfbIsActive(rfbScreenInfoPtr screenInfo);
932
933 /* TightVNC file transfer extension */
934 void rfbRegisterTightVNCFileTransferExtension();
935 void rfbUnregisterTightVNCFileTransferExtension(); 
936
937 /* Statistics */
938 extern char *messageNameServer2Client(uint32_t type, char *buf, int len);
939 extern char *messageNameClient2Server(uint32_t type, char *buf, int len);
940 extern char *encodingName(uint32_t enc, char *buf, int len);
941
942 extern rfbStatList *rfbStatLookupEncoding(rfbClientPtr cl, uint32_t type);
943 extern rfbStatList *rfbStatLookupMessage(rfbClientPtr cl, uint32_t type);
944
945 /* Each call to rfbStatRecord* adds one to the rect count for that type */
946 extern void rfbStatRecordEncodingSent(rfbClientPtr cl, uint32_t type, int byteCount, int byteIfRaw);
947 extern void rfbStatRecordEncodingSentAdd(rfbClientPtr cl, uint32_t type, int byteCount); /* Specifically for tight encoding */
948 extern void rfbStatRecordEncodingRcvd(rfbClientPtr cl, uint32_t type, int byteCount, int byteIfRaw);
949 extern void rfbStatRecordMessageSent(rfbClientPtr cl, uint32_t type, int byteCount, int byteIfRaw);
950 extern void rfbStatRecordMessageRcvd(rfbClientPtr cl, uint32_t type, int byteCount, int byteIfRaw);
951 extern void rfbResetStats(rfbClientPtr cl);
952 extern void rfbPrintStats(rfbClientPtr cl);
953
954 extern int rfbStatGetSentBytes(rfbClientPtr cl);
955 extern int rfbStatGetSentBytesIfRaw(rfbClientPtr cl);
956 extern int rfbStatGetRcvdBytes(rfbClientPtr cl);
957 extern int rfbStatGetRcvdBytesIfRaw(rfbClientPtr cl);
958 extern int rfbStatGetMessageCountSent(rfbClientPtr cl, uint32_t type);
959 extern int rfbStatGetMessageCountRcvd(rfbClientPtr cl, uint32_t type);
960 extern int rfbStatGetEncodingCountSent(rfbClientPtr cl, uint32_t type);
961 extern int rfbStatGetEncodingCountRcvd(rfbClientPtr cl, uint32_t type);
962
963 /* Set which version you want to advertise 3.3, 3.6, 3.7 and 3.8 are currently supported*/
964 extern void rfbSetProtocolVersion(rfbScreenInfoPtr rfbScreen, int major_, int minor_);
965
966 /* send a TextChat message to a client */
967 extern rfbBool rfbSendTextChatMessage(rfbClientPtr cl, uint32_t length, char *buffer);
968
969
970
971
972 #if(defined __cplusplus)
973 }
974 #endif
975
976 #endif
977