// AmiVNC - Amiga experimental VNC server - Protocol ORL version 3.3

// Includes ***********************************************
// Needed to compile : SDK Cybergraphx 4.1 & SDK AmiTCP 4.3
#include <exec/types.h>
#include <exec/memory.h>
#include <devices/input.h>
#include <devices/inputevent.h>
#include <libraries/commodities.h>
#include <proto/all.h>
#include <proto/socket.h>

#include <cybergraphx/cybergraphics.h>
#include <proto/cybergraphics.h>

#include <dos/dostags.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <netdb.h>

#include <intuition/intuitionbase.h>
#include <intuition/intuition.h>
#include <graphics/displayinfo.h>
#include <graphics/gfxbase.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <fcntl.h>
#include <ctype.h>

// Specific Inculdes ***********************************************
#include "rfbproto.h"                   // Structures & constants for VNC protocol
#include "vncauth.h"                    // Prototypes for authentication

// Constants ***********************************************
#define XDC_PORT 5900                   // Port # for bind()
#define FALSE 0
#define TRUE 1
#define XDC_TILE 32                     // Tile size

#define XDC_C_VBUF      (1L << 0)
#define XDC_C_MSOCK     (1L << 1)
#define XDC_C_CSOCK     (1L << 2)

#define XDC_C_MAXDEPTH  4               // Max. raster depth : 4 bytes / pixel

#undef PARANO

// Common messages
char XDC_ID[] = "AmiVNC 0.0.11b4 May 28 1999";
char XDC_SEND[] = "main.c / main : send() error";
char XDC_RECV[] = "main.c / main : recv() error";

// Global variables ***********************************************
LONG    iDuplicateSocketKey;            // Client socket key for transmitting to child process
ULONG   uOpened = NULL;                 // Opened resources, to be closed on exit
BOOL    bDie = FALSE, *pDie = &bDie;    // TRUE : processes are to exit (Argh, very trashy)
char    cPassword[MAXPWLEN + 1];
LONG    iMasterSocket,                  // Listening socket for incoming connections
        iClientSocket;                  // Client socket accept()ed
UBYTE   *pBuffer = NULL;                // Reference buffer for screen change detection
char    *sPWFile = "S:AmiVNC.pwd";      // Password file name

// Free all resources allocated to a client session ***********************************************
void vCleanSession(char *cMsg, long lCode)
{
    // Tell the child process to exit (as we are the main process,
    // we can use bDie, which is in our address space)
    if (!bDie)
    {
        bDie = TRUE;
        Delay(125);
    }
    
    // Close everything opened
    if (uOpened & XDC_C_VBUF) free(pBuffer);
    if (uOpened & XDC_C_CSOCK) CloseSocket(iClientSocket);
    
    printf("AmiVNC - %s (%ld)\nAmiVNC session closed\n", cMsg, lCode);
}

// Free all resources allocated to main process and exit ***********************************************
void vCleanExit(char *cMsg, long lCode)
{
    vCleanSession(cMsg, lCode);
    
    if (uOpened & XDC_C_MSOCK) CloseSocket(iMasterSocket);
    
    printf("AmiVNC halted\n");
    
    exit(0L);
}

// Authentication ***********************************************
BOOL bAuthentify(void)
{
        char cChallenge[16], cResponse[16];
        CARD32 c32Value;
        BOOL bAuthenticated = TRUE;
        int iCnt, iFile;

        // Read encoded password in s:AmiVNC.pwd
        if (!(iFile = open(sPWFile, O_RDONLY, 0)))
           return(FALSE);
                
        iCnt = read(iFile, cPassword, sizeof(cPassword));
        
        close(iFile);
        
        if (iCnt != sizeof(cPassword))
           return(FALSE);

        // Decode password
        vncDecryptPasswd(cPassword, cPassword);
        
        // Authenticate the connection, if required
        if (!strlen(cPassword))
        {
                // Send no-auth-required message
                c32Value = rfbNoAuth;
                if (!(-1 == (send(iClientSocket,(char *)&c32Value, sizeof(c32Value), 0))))
                        return FALSE;

                return(TRUE);
        }
        else
        {
                // Send auth-required message
                c32Value = rfbVncAuth;
                if (-1 == (send(iClientSocket,(char *)&c32Value, sizeof(c32Value), 0)))
                        return FALSE;

                // Now create a 16-byte challenge
                vncRandomBytes((BYTE *)cChallenge);

                // Send the challenge to the client
                if (-1 == (send(iClientSocket, cChallenge, sizeof(cChallenge), 0)))
                        return FALSE;

                // Read the response
                if (-1 == (recv(iClientSocket, cResponse, sizeof(cResponse), 0)))
                        return FALSE;

                // Encrypt the challenge bytes
                vncEncryptBytes((BYTE *)cChallenge, cPassword);

                // Compare them to the response
                for (iCnt = 0; iCnt < sizeof(cChallenge); iCnt++)
                {
                        if (cChallenge[iCnt] != cResponse[iCnt])
                        {
                                bAuthenticated = FALSE;
                                break;
                        }
                }

                // Did the authentication work?
                if (!bAuthenticated)
                {
                        c32Value = rfbVncAuthFailed;
                        send(iClientSocket, (char *)&c32Value, sizeof(c32Value), 0);
                        return FALSE;

                }
                else
                {
                        // Tell the client we're ok
                        c32Value = rfbVncAuthOK;
                        if (-1 == (send(iClientSocket, (char *)&c32Value, sizeof(c32Value), 0)))
                                return FALSE;
                
                        return(TRUE);
                }
        }
}

// Incoming messages management thread ***********************************************
void __saveds vProcessIncomes(void)
{
    struct IOStdReq *inputReqBlk;
    struct MsgPort *inputPort;
    struct InputEvent eEvent, *VNCEvent = &eEvent;
    UWORD uQualifier = 0;
    rfbClientToServerMsg sCMsg;
    BOOL bLClick = FALSE, bMClick = FALSE, bRClick = FALSE;
    struct Library *SocketBase;
    LONG iSocketChild;

    // We have to reopen bsdsocket.library, because it can not be shared between processes
    // OpenLibrary can not fail since it would have halted the father before creating us.
    SocketBase = OpenLibrary("bsdsocket.library", 4L);

    // Obtain the client socket descriptor from the key saved for us by our father
    if (-1 == (iSocketChild = ObtainSocket(iDuplicateSocketKey, AF_INET, SOCK_STREAM, 0)))
    {
        printf("main.c / vProcessIncomes : ObtainSocket() error %d\n", Errno());
        *pDie = TRUE;
        goto _Nosock;
    }
    
    printf("main.c / vProcessIncomes runs on socket %d\n", iSocketChild);

    // Create input.device message structure
    inputPort = CreatePort(NULL, NULL);
    inputReqBlk = (struct IOStdReq *) CreateExtIO(inputPort, sizeof(struct IOStdReq));
    OpenDevice("input.device", NULL, (struct IORequest *) inputReqBlk, NULL);
    inputReqBlk -> io_Data = (APTR) VNCEvent;
    inputReqBlk -> io_Command = IND_WRITEEVENT;
    inputReqBlk -> io_Flags = 0;
    inputReqBlk -> io_Length = sizeof(struct InputEvent);
    
    // Process incoming messages until main process tells to die.
    // Use pointer to bDie because it is not in our address space...
    while (!*pDie) // VERY VERY dirty way to know we have to exit...
    {
       if (-1 == recv(iSocketChild, (UBYTE *) &sCMsg, 1, 0))
       {
           printf("main.c / vProcessIncomes : recv() error, errno = %d\n", Errno());
           *pDie  = TRUE;
           continue;
       }
       
       Forbid(); // Leave us handle properly our input event
       switch(sCMsg.type)
       {
           case rfbSetPixelFormat : // 0
           if (sz_rfbSetPixelFormatMsg - 1 == recv(iSocketChild, 1 + (UBYTE *) & sCMsg, sz_rfbSetPixelFormatMsg - 1, 0))
           {
#ifdef PARANO
               printf("C -> S : rfbSetPixelFormat lanbpp %d depth %d bigE %d tc %d redM %d redS %d GreM %d GreS %d BluM %d BluS %d\n",
                  sCMsg.spf.format.bitsPerPixel,
                  sCMsg.spf.format.depth,
                  sCMsg.spf.format.bigEndian,
                  sCMsg.spf.format.trueColour,
                  sCMsg.spf.format.redMax,
                  sCMsg.spf.format.redShift,
                  sCMsg.spf.format.greenMax,
                  sCMsg.spf.format.greenShift,
                  sCMsg.spf.format.blueMax,
                  sCMsg.spf.format.blueShift
                  );
#endif // PARANO
               break;
           }
           
           case rfbFixColourMapEntries : // 1
           if (sz_rfbFixColourMapEntriesMsg - 1 == recv(iSocketChild, 1 + (UBYTE *) & sCMsg, sz_rfbFixColourMapEntriesMsg - 1, 0))
           {
#ifdef PARANO
               printf("C -> S : rfbFixColourMapEntries\n");
#endif // PARANO
               break;
           }
           
           case rfbSetEncodings : // 2
           if (sz_rfbSetEncodingsMsg - 1 == recv(iSocketChild, 1 + (UBYTE *) & sCMsg, sz_rfbSetEncodingsMsg - 1, 0))
           {
#ifdef PARANO
               printf("C -> S : rfbSetEncodings\n");
#endif // PARANO
               break;
           }
           
           case rfbFramebufferUpdateRequest : // 3
           if (sz_rfbFramebufferUpdateRequestMsg - 1 == recv(iSocketChild, 1 + (UBYTE *) & sCMsg, sz_rfbFramebufferUpdateRequestMsg - 1, 0))
           {
#ifdef PARANO            
               printf("C -> S : rfbFramebufferUpdateRequest inc %d x %d y %d w %d h %d\n",
                  sCMsg.fur.incremental,
                  sCMsg.fur.x,
                  sCMsg.fur.y,
                  sCMsg.fur.w,
                  sCMsg.fur.h
                  );
#endif // PARANO            
               break;
           }
           
           case rfbKeyEvent : // 4
           if (sz_rfbKeyEventMsg - 1 == recv(iSocketChild, 1 + (UBYTE *) & sCMsg, sz_rfbKeyEventMsg - 1, 0))
           {
#ifdef PARANO
               printf("C -> S : rfbKeyEvent down %d key %d ('%c')\n",
                  sCMsg.ke.down,
                  sCMsg.ke.key,
                  sCMsg.ke.key
                 );
#endif // PARANO
               // Process special keys
               if ((sCMsg.ke.down) && (0xFFE0 == (sCMsg.ke.key & 0xFFE0)))
               {
                   if (sCMsg.ke.key == 0xFFE1) uQualifier |= IEQUALIFIER_LSHIFT;  // Left Shift
                   if (sCMsg.ke.key == 0xFFE2) uQualifier |= IEQUALIFIER_RSHIFT;  // Right Shift
                   if (sCMsg.ke.key == 0xFFE3) uQualifier |= IEQUALIFIER_CONTROL; // Left Control
                   if (sCMsg.ke.key == 0xFFE4) uQualifier |= IEQUALIFIER_CONTROL; // Right Control
                   if (sCMsg.ke.key == 0xFFE9) uQualifier |= IEQUALIFIER_LALT;    // Left Alt
                   if (sCMsg.ke.key == 0xFFEA) uQualifier |= IEQUALIFIER_RALT;    // Right Alt
                   break;
               }
               if ((!sCMsg.ke.down) && (0xFFE0 == (sCMsg.ke.key & 0xFFE0)))
               {
                   if (sCMsg.ke.key == 0xFFE1) uQualifier &= ~IEQUALIFIER_LSHIFT; // Left Shift
                   if (sCMsg.ke.key == 0xFFE2) uQualifier &= ~IEQUALIFIER_RSHIFT; // Right Shift
                   if (sCMsg.ke.key == 0xFFE3) uQualifier &= ~IEQUALIFIER_CONTROL; // Left Control
                   if (sCMsg.ke.key == 0xFFE4) uQualifier &= ~IEQUALIFIER_CONTROL; // Right Control
                   if (sCMsg.ke.key == 0xFFE9) uQualifier &= ~IEQUALIFIER_LALT;    // Left Alt
                   if (sCMsg.ke.key == 0xFFEA) uQualifier &= ~IEQUALIFIER_RALT;    // Right Alt
                   break;
               }

               // Do nothing on key release
               if (!sCMsg.ke.down) break;

               // Process cursor-related keys
               if (0xFF50 == (sCMsg.ke.key & 0xFF50))
               {
                   VNCEvent -> ie_Class = IECLASS_RAWKEY;
                   VNCEvent -> ie_Qualifier = 0;
                   switch(sCMsg.ke.key & 0x000F)
                   {
                       case 0 : // Home
                           VNCEvent -> ie_Code = 0x3D;
                           break;
                       case 1 : // Left
                           VNCEvent -> ie_Code = 0x4F;
                           break;
                       case 2 : // Up
                           VNCEvent -> ie_Code = 0x4C;
                           break;
                       case 3 : // Right
                           VNCEvent -> ie_Code = 0x4E;
                           break;
                       case 4 : // Down
                           VNCEvent -> ie_Code = 0x4D;
                           break;
                       case 5 : // Page up
                           VNCEvent -> ie_Code = 0x3F;
                           break;
                       case 6 : // Page down
                           VNCEvent -> ie_Code = 0x1F;
                           break;
                       case 7 : // End
                           VNCEvent -> ie_Code = 0x1D;
                           break;
                       default :
                           break;
                   }
               }
               else
               {
                   // Map out other 0xFF'ed keys
                   sCMsg.ke.key &= 0xFF;
                   
                   // Find rawkey event out of key ; if we can not, reject key
                   if (!InvertKeyMap((ULONG) sCMsg.ke.key, VNCEvent, NULL))
                   break;
               }
               
               // Apply qualifier if possible
               if (!strchr("~`£µ¨", (int) sCMsg.ke.key)) switch(uQualifier)
               {
                   case IEQUALIFIER_CONTROL :
                   case IEQUALIFIER_LSHIFT :
                   case IEQUALIFIER_RSHIFT :
                       VNCEvent -> ie_Qualifier = uQualifier;
                       break;
                           
                   case IEQUALIFIER_LALT :
                       VNCEvent -> ie_Qualifier = IEQUALIFIER_LCOMMAND;
                       break;
                           
                   case IEQUALIFIER_RALT | IEQUALIFIER_CONTROL :
                       VNCEvent -> ie_Qualifier = IEQUALIFIER_RCOMMAND;
                       break;
               }
               
               // Send key into input.device
               DoIO((struct IORequest *) inputReqBlk);
           break;
           }
           
           case rfbPointerEvent : // 5
           if (sz_rfbPointerEventMsg - 1 == recv(iSocketChild, 1 + (UBYTE *) & sCMsg, sz_rfbPointerEventMsg - 1, 0))
           {
#ifdef PARANO
               printf("C -> S : rfbPointerEvent button %d x %d y %d\r",
                  sCMsg.pe.buttonMask,
                  sCMsg.pe.x,
                  sCMsg.pe.y
                 );
#endif // PARANO
               VNCEvent -> ie_NextEvent = NULL;
               VNCEvent -> ie_Class = IECLASS_POINTERPOS;
               VNCEvent -> ie_Qualifier = uQualifier;
               
               // Process mouse X & Y
               VNCEvent -> ie_X = sCMsg.pe.x;
               VNCEvent -> ie_Y = sCMsg.pe.y;

               // Process mouse buttons...
               VNCEvent -> ie_Code = IECODE_NOBUTTON;
               
               // Left button
               if ((sCMsg.pe.buttonMask) & 1)
               switch(bLClick)
               {
                   case FALSE : bLClick = TRUE; VNCEvent -> ie_Code = IECODE_LBUTTON; uQualifier |= IEQUALIFIER_LEFTBUTTON; break;
                   case TRUE : VNCEvent -> ie_Code = IECODE_NOBUTTON; break;
               }
               else if (bLClick) { bLClick = FALSE; VNCEvent -> ie_Code = IECODE_LBUTTON | IECODE_UP_PREFIX; uQualifier &= ~IEQUALIFIER_LEFTBUTTON; }

               // Middle button
               if ((sCMsg.pe.buttonMask) & 2)
               switch(bMClick)
               {
                   case FALSE : bMClick = TRUE; VNCEvent -> ie_Code = IECODE_MBUTTON;  uQualifier |= IEQUALIFIER_MIDBUTTON; break;
                   case TRUE : VNCEvent -> ie_Code = IECODE_NOBUTTON; break;
               }
               else if (bMClick) { bMClick = FALSE; VNCEvent -> ie_Code = IECODE_MBUTTON | IECODE_UP_PREFIX; uQualifier &= ~IEQUALIFIER_MIDBUTTON; }

               // Right button
               if ((sCMsg.pe.buttonMask) & 4)
               switch(bRClick)
               {
                   case FALSE : bRClick = TRUE; VNCEvent -> ie_Code = IECODE_RBUTTON;  uQualifier |= IEQUALIFIER_RBUTTON; break;
                   case TRUE : VNCEvent -> ie_Code = IECODE_NOBUTTON; break;
               }
               else if (bRClick) { bRClick = FALSE; VNCEvent -> ie_Code = IECODE_RBUTTON | IECODE_UP_PREFIX; uQualifier &= ~IEQUALIFIER_RBUTTON; }

               // Insert event into input.device stream
               DoIO((struct IORequest *) inputReqBlk);
               break;
           }
           
           case rfbClientCutText : // 6
           if (sz_rfbClientCutTextMsg - 1 == recv(iSocketChild, 1 + (UBYTE *) & sCMsg, sz_rfbClientCutTextMsg - 1, 0))
           {
               char *cText = malloc((size_t) (sCMsg.cct.length + 1));
               recv(iSocketChild, cText, sCMsg.cct.length, 0);
               cText[sCMsg.cct.length] = 0;
#ifdef PARANO
               printf("C -> S : rfbClientCutText '%s'\n", cText);
#endif // PARANO
               break;
           }
           
           default :
#ifdef PARANO
           printf("main.c / vProcessIncomes : msg type %d unknown\n", sCMsg.type);
#endif // PARANO
           break;
       }
       Permit();
    }
    
    CloseSocket(iSocketChild);

    if (inputReqBlk)
    {
        CloseDevice((struct IORequest *) inputReqBlk);
        DeleteExtIO((struct IORequest *) inputReqBlk);
    }
    
    if (inputPort) DeletePort(inputPort);

_Nosock:
    CloseLibrary(SocketBase);
    printf("main.c / vProcessIncomes halted\n");   
}

// Main entry point  ***********************************************
int main(int argc, char **argv)
{
    register int iCnt, jCnt;
    int iMajor, iMinor, iWidth, iHeight, iDepth, iSize, iMode, iPort, iRShift = 8, iGShift = 16, iBShift = 24;
    unsigned long uLimit = 0xFFFFFFFF, uSize, uCnt;
    struct sockaddr_in sAddr;                  // Local address for bind()
    struct Screen *pActiveScreen;
    rfbProtocolVersionMsg mProtVerMsg;
    rfbServerInitMsg mSerInitMsg;
    rfbFramebufferUpdateMsg mFBUpdMsg;
    rfbFramebufferUpdateRectHeader mFBRMsg;
    CARD8 c8;
    BOOL bBig = FALSE, bFast;
    struct Library *CGXlib = OpenLibrary("cgxsystem.library", 40L);
    register UBYTE *pRaster;                    // True WB screen raster
    static UBYTE uTile[XDC_TILE * XDC_TILE * XDC_C_MAXDEPTH];    // 3 Byte/pixel RGB Raster tile for client screen updates
    
    // Welcome...
    printf("%s\n(c) 1999 stephane.guillard@steria.fr\n", XDC_ID);
    printf("Options :\n -p<pwd> to store password\n");
    printf(" -s<port> to set listen port (default %d)\n", XDC_PORT);
    printf(" -e to force big endian (default little)\n");
    printf(" -l<size> to limit net block size (default unlimited\n");
    printf(" -(r|g|b)<value> to force color encoding r|g|b bitshift (defaults 8|16|24)\n");
    
    iPort = XDC_PORT;
    
    // Process command line arguments (if any)
    if (argc > 1) while (*++argv)
    {
        char *pC;
        
        switch(tolower((*argv)[1]))
        {
            // *** Force password change and exit
            case 'p' :
                strncpy(cPassword, *argv + 2, MAXPWLEN);
                cPassword[MAXPWLEN] = '\0';
                
                pC = strchr(cPassword, ' ');
                if (pC) *pC = '\0';
                
                for (iCnt = strlen(cPassword) ; iCnt < MAXPWLEN ; iCnt++)
                   cPassword[iCnt] = '\0';
                
                vncEncryptPasswd(cPassword, cPassword);
                
                if (-1 == (iCnt = creat(sPWFile, S_IREAD | S_IWRITE)))
                    vCleanExit("main.c / main : creat('s:AmiVNC.pwd') error", 0);
                write(iCnt, cPassword, sizeof(cPassword));
                close(iCnt);
                
                vCleanExit("main.c / main : Passwd stored", 0);
                break;
            
            // *** Force another port than the default 5900
            case 's' :
                iPort = atoi(*argv + 2);
                break;
            
            // *** Force BigEndian flag in mSerInitMsg
            case 'e' :
                bBig = TRUE;
                break;
            
            // *** Limit netblocksize for initial screen update
            case 'l' :
                uLimit = atoi(*argv + 2);
                break;
                
            // *** Force Red / Green / Blue bitshifts in mSerInitMsg
            // (play with this if you have color problems, legal values
            // for shifts are 0, 8, 16 and 24)
            case 'r' :
                iRShift = atoi(*argv + 2);
                break;
                
            case 'g' :
                iGShift = atoi(*argv + 2);
                break;
                
            case 'b' :
                iBShift = atoi(*argv + 2);
                break;
                
            default :
                printf("main.c / main : Arg [%s] ignored\n", *argv);
                break;
        }
    }
    
    // Print configurable parameter values
    printf("main.c / main : parameter values :\n");
    printf(" - listen port set to %d\n", iPort);
    printf(" - endian set to %s\n", bBig ? "big" : "little");
    printf(" - initial xfer limit set to %ul\n", uLimit);
    printf(" - color bitshifts : red %d, green %d, blue %d\n", iRShift, iGShift, iBShift);
    
    // Prepare listener socket
    printf("main.c / main : Creating listener socket\n");
    if (-1 == (iMasterSocket = socket(AF_INET, SOCK_STREAM, 0)))
        vCleanExit("main.c / main : socket() error", Errno());
    
    uOpened |= XDC_C_MSOCK;
    
    sAddr.sin_family=AF_INET;
    sAddr.sin_addr.s_addr = 0;
    sAddr.sin_port = htons(iPort);
    
    printf("main.c / main : Binding socket on port %d\n", sAddr.sin_port);
    if (-1 == (bind(iMasterSocket, (struct sockaddr *) &sAddr, sizeof(sAddr))))
        vCleanExit("main.c / main : bind() error", Errno());
    
    printf("main.c / main : Listening set on port %d\n", sAddr.sin_port);
    if (-1 == (listen(iMasterSocket, 4)))
        vCleanExit("main.c / main : listen() error", Errno()); 

_NewSession:

    bDie = FALSE;
    
    // Wait for incoming connections
    printf("main.c / main : Waiting for client connection\n");
    if (-1 == (iClientSocket = accept(iMasterSocket, NULL, NULL)))
        vCleanExit("main.c / main : accept() error", Errno());
    
    uOpened |= XDC_C_CSOCK;
    
    printf("main.c / main : accept()ed socket %d\n", iClientSocket);

    // NegociateProtocolVersion
    printf("main.c / main : Negociating protocol version\n");
    sprintf((char *) mProtVerMsg, rfbProtocolVersionFormat,
    rfbProtocolMajorVersion,
    rfbProtocolMinorVersion);
    if (-1 == (send(iClientSocket, (UBYTE *) mProtVerMsg, sz_rfbProtocolVersionMsg, 0)))
    { vCleanSession(XDC_SEND, Errno()); goto _NewSession; }
    
    mProtVerMsg[12] = 0;

    if (-1 == (recv(iClientSocket, mProtVerMsg, sz_rfbProtocolVersionMsg, 0)))
    { vCleanSession(XDC_RECV, Errno()); goto _NewSession; }

    sscanf((char *) mProtVerMsg, rfbProtocolVersionFormat, &iMajor, &iMinor);
    printf("main.c / main : Protocol supported by server : %d.%d, by client : %d.%d\n", rfbProtocolMajorVersion, rfbProtocolMinorVersion, iMajor, iMinor);

    // If major == minor == 0, fake client asks to exit
    if ((!iMajor) && (!iMinor))
        vCleanExit("main.c / main : Exit asked", 0);
        
    // Check protocol version
    if (iMajor > rfbProtocolMajorVersion)
    { vCleanSession("main.c / main : unknown protocol", 0); goto _NewSession; }
    
    // Authenticate DES
    printf("main.c / main : Authentication\n");
    if (FALSE == bAuthentify())
    { vCleanSession("main.c / main : Authenticate error", 0); goto _NewSession; }
    
    // ClientInit
    printf("main.c / main : ClientInitialisation\n");
    if (-1 == (recv(iClientSocket, &c8, sizeof(c8), 0)))
    { vCleanSession(XDC_RECV, Errno()); goto _NewSession; }
    
    printf("main.c / main : SharedFlag = %d (multiple clients : %s)\n", c8, c8 ? "Yes" : "No");

    // Grab active screen
    pActiveScreen = IntuitionBase -> FirstScreen;
    printf("main.c / main : Screen set to [%s]\n", pActiveScreen -> Title);

    // Grab raster pointer (dirty but EFFICIENT !)
    UnLockBitMap(LockBitMapTags(pActiveScreen -> RastPort.BitMap,
                 LBMI_BASEADDRESS, (ULONG *) &uCnt,
                 TAG_DONE));
    pRaster = (UBYTE *) uCnt;

    // Prepare VNC pixel encoding from screen info (if not forced on command line)
    if (GetCyberMapAttr(pActiveScreen -> RastPort.BitMap, CYBRMATTR_ISCYBERGFX)
     && GetCyberMapAttr(pActiveScreen -> RastPort.BitMap, CYBRMATTR_ISLINEARMEM))
    {
        iMode = GetCyberMapAttr(pActiveScreen -> RastPort.BitMap, CYBRMATTR_PIXFMT);
        iWidth = GetCyberMapAttr(pActiveScreen -> RastPort.BitMap, CYBRMATTR_WIDTH); // X size
        iHeight = GetCyberMapAttr(pActiveScreen -> RastPort.BitMap, CYBRMATTR_HEIGHT); // Y size
        iDepth = GetCyberMapAttr(pActiveScreen -> RastPort.BitMap, CYBRMATTR_BPPIX); // Bytes / pixel
        printf("main.c / main : RTG mode %s/%ld\nmain.c / main : ", CGXlib ? "CGFx" : "Pic96", iMode);
    }
    else
    { vCleanSession("main.c / main : Screenmode not supported", 0); goto _NewSession; }

    iSize = iWidth * iHeight * iDepth; // Actual total byte size of screen raster 

    printf("main.c / main : @ 0x%08lX, %dx%d, %d Bpp, size %d\n", pRaster, iWidth, iHeight, iDepth, iSize);    

    // Fast mode : 2 byte pixel screens under Picasso96
    bFast = ((!CGXlib) && (iDepth == 2));
    // Allocate pBuffer (reference buffer for screen compare)
    // - with 4 byte / pixel size if under CGFx or Depth >= 3
    // - with just the screen size if under P96 and Depth < 3
    // (to send initial screen)
    if (!(pBuffer = malloc(iWidth * iHeight * (bFast ? iDepth : XDC_C_MAXDEPTH))))
    { vCleanSession("main.c / main : malloc() error", 0); goto _NewSession; }
   
    uOpened |= XDC_C_VBUF;

    // ServerInit
    if (bFast)
    {
        switch(iMode)
        {
            case PIXFMT_RGB16PC : // TESTED OK /* HiColor16 (5 bit R, 6 bit G, 5 bit B), format: gggbbbbbrrrrrggg */
                mSerInitMsg.format.bitsPerPixel = 16;
                mSerInitMsg.format.depth = 16;
                mSerInitMsg.format.bigEndian = TRUE;
                mSerInitMsg.format.trueColour = TRUE;
                mSerInitMsg.format.redMax = 31;
                mSerInitMsg.format.greenMax = 63;
                mSerInitMsg.format.blueMax = 31;
                mSerInitMsg.format.redShift = 11;
                mSerInitMsg.format.greenShift = 5;
                mSerInitMsg.format.blueShift = 0;
                break;
            case PIXFMT_RGB15PC :        /* HiColor15 (5 bit each), format: gggbbbbb0rrrrrgg */
                mSerInitMsg.format.bitsPerPixel = 16;
                mSerInitMsg.format.depth = 15;
                mSerInitMsg.format.bigEndian = TRUE;
                mSerInitMsg.format.trueColour = TRUE;
                mSerInitMsg.format.redMax = 31;
                mSerInitMsg.format.greenMax = 31;
                mSerInitMsg.format.blueMax = 31;
                mSerInitMsg.format.redShift = 10;
                mSerInitMsg.format.greenShift = 5;
                mSerInitMsg.format.blueShift = 0;
                break;
            case PIXFMT_RGB16 :          /* HiColor16 (5 bit R, 6 bit G, 5 bit B), format: rrrrrggggggbbbbb */
                mSerInitMsg.format.bitsPerPixel = 16;
                mSerInitMsg.format.depth = 16;
                mSerInitMsg.format.bigEndian = FALSE;
                mSerInitMsg.format.trueColour = TRUE;
                mSerInitMsg.format.redMax = 31;
                mSerInitMsg.format.greenMax = 63;
                mSerInitMsg.format.blueMax = 31;
                mSerInitMsg.format.redShift = 11;
                mSerInitMsg.format.greenShift = 5;
                mSerInitMsg.format.blueShift = 0;
                break;
            case PIXFMT_RGB15 :          /* HiColor15 (5 bit each), format: 0rrrrrgggggbbbbb */
                mSerInitMsg.format.bitsPerPixel = 16;
                mSerInitMsg.format.depth = 15;
                mSerInitMsg.format.bigEndian = TRUE;
                mSerInitMsg.format.trueColour = TRUE;
                mSerInitMsg.format.redMax = 31;
                mSerInitMsg.format.greenMax = 31;
                mSerInitMsg.format.blueMax = 31;
                mSerInitMsg.format.redShift = 10;
                mSerInitMsg.format.greenShift = 5;
                mSerInitMsg.format.blueShift = 0;
                break;
            case PIXFMT_BGR16PC :        /* HiColor16 (5 bit R, 6 bit G, 5 bit B), format: gggrrrrrbbbbbggg */
                mSerInitMsg.format.bitsPerPixel = 16;
                mSerInitMsg.format.depth = 16;
                mSerInitMsg.format.bigEndian = TRUE;
                mSerInitMsg.format.trueColour = TRUE;
                mSerInitMsg.format.redMax = 31;
                mSerInitMsg.format.greenMax = 63;
                mSerInitMsg.format.blueMax = 31;
                mSerInitMsg.format.redShift = 0;
                mSerInitMsg.format.greenShift = 5;
                mSerInitMsg.format.blueShift = 11;
                break;
            case PIXFMT_BGR15PC :        /* HiColor15 (5 bit each), format: gggrrrrr0bbbbbbgg */
                mSerInitMsg.format.bitsPerPixel = 16;
                mSerInitMsg.format.depth = 15;
                mSerInitMsg.format.bigEndian = TRUE;
                mSerInitMsg.format.trueColour = TRUE;
                mSerInitMsg.format.redMax = 31;
                mSerInitMsg.format.greenMax = 31;
                mSerInitMsg.format.blueMax = 31;
                mSerInitMsg.format.redShift = 0;
                mSerInitMsg.format.greenShift = 5;
                mSerInitMsg.format.blueShift = 10;
                break;
            case PIXFMT_BGR16 :        /* HiColor16 (5 bit R, 6 bit G, 5 bit B), format: bbbbbggggggrrrrr */
                mSerInitMsg.format.bitsPerPixel = 16;
                mSerInitMsg.format.depth = 16;
                mSerInitMsg.format.bigEndian = FALSE;
                mSerInitMsg.format.trueColour = TRUE;
                mSerInitMsg.format.redMax = 31;
                mSerInitMsg.format.greenMax = 63;
                mSerInitMsg.format.blueMax = 31;
                mSerInitMsg.format.redShift = 0;
                mSerInitMsg.format.greenShift = 5;
                mSerInitMsg.format.blueShift = 11;
                break;
            case PIXFMT_BGR15 :        /* HiColor15 (5 bit each), format: 0bbbbbbgggggrrrrr */
                mSerInitMsg.format.bitsPerPixel = 16;
                mSerInitMsg.format.depth = 15;
                mSerInitMsg.format.bigEndian = FALSE;
                mSerInitMsg.format.trueColour = TRUE;
                mSerInitMsg.format.redMax = 31;
                mSerInitMsg.format.greenMax = 31;
                mSerInitMsg.format.blueMax = 31;
                mSerInitMsg.format.redShift = 0;
                mSerInitMsg.format.greenShift = 5;
                mSerInitMsg.format.blueShift = 10;
                break;
            default :
                { vCleanSession("main.c / main : RGB mode not supported", 0); goto _NewSession; }
                break;
         }
    }
    else // CGFx ou Depth != 2
    {
        mSerInitMsg.format.bitsPerPixel = 32;
        mSerInitMsg.format.depth = 24;
        mSerInitMsg.format.bigEndian = bBig;
        mSerInitMsg.format.trueColour = TRUE;
        mSerInitMsg.format.redMax =
        mSerInitMsg.format.greenMax =
        mSerInitMsg.format.blueMax = 255;
        mSerInitMsg.format.redShift = iRShift;
        mSerInitMsg.format.greenShift = iGShift;
        mSerInitMsg.format.blueShift = iBShift;
    }
    
    mSerInitMsg.framebufferWidth = iWidth;
    mSerInitMsg.framebufferHeight = iHeight;
    mSerInitMsg.nameLength = sizeof(XDC_ID);
 
    if (-1 == (send(iClientSocket, (UBYTE *) &mSerInitMsg, sizeof(mSerInitMsg), 0)))
    { vCleanSession(XDC_SEND, Errno()); goto _NewSession; }    

    if (-1 == (send(iClientSocket, (UBYTE *) XDC_ID, sizeof(XDC_ID), 0)))
    { vCleanSession(XDC_SEND, Errno()); goto _NewSession; }

    // Initial Screen update : header...
    mFBUpdMsg.type = rfbFramebufferUpdate;
    mFBUpdMsg.nRects = 1;
    if (-1 == (send(iClientSocket, (UBYTE *) &mFBUpdMsg, sizeof(mFBUpdMsg), 0)))
    { vCleanSession(XDC_SEND, Errno()); goto _NewSession; }
    
    // Initial Screen update : 1 rectangle for whole screen...
    mFBRMsg.r.x = 0;
    mFBRMsg.r.y = 0;
    mFBRMsg.r.w = iWidth;
    mFBRMsg.r.h = iHeight;
    mFBRMsg.encoding = rfbEncodingRaw;

    if (-1 == (send(iClientSocket, (UBYTE *) &mFBRMsg, sizeof(mFBRMsg), 0)))
    { vCleanSession(XDC_SEND, Errno()); goto _NewSession; }

    // Copy raster into buffer for send() and for ulterior compares
    if (bFast)
    {
        // simply send raster memory size (as 16 bit pixels)
        memcpy(pBuffer, pRaster, iSize);
        uSize = uLimit < iSize ? uLimit : iSize;
    }
    else
    {
        // We have to make 4 byte pixels out of the raster
        ReadPixelArray(pBuffer,     // Buffer
               0, 0,        // Dest X/Y in buffer
               iWidth * XDC_C_MAXDEPTH,     // Byte width of buffer
               &(pActiveScreen -> RastPort),
               0, 0,         // Source X/Y
               iWidth, iHeight,  // Source w/h
               RECTFMT_ARGB
               );
                   
        uSize = uLimit < iWidth * iHeight * XDC_C_MAXDEPTH ? uLimit : iWidth * iHeight * XDC_C_MAXDEPTH;
    }

    // Send buffer (by uLimit packet size if set)
    uCnt = 0;
    while (uCnt < ((bFast) ? iSize : iWidth * iHeight * XDC_C_MAXDEPTH))
    {
        if (-1 == (send(iClientSocket, (UBYTE *) pBuffer + uCnt, uSize, 0)))
        { vCleanSession(XDC_SEND, Errno()); goto _NewSession; }
     
        uCnt += uSize;
    }

    if (!bFast)
    {
        // Reallocate the buffer, resizing it to what's really necessary
        if (!(pBuffer = realloc(pBuffer, iWidth * iHeight * (CGXlib ? iDepth : ((iDepth != 3) ? iDepth : 4)))))
        { vCleanSession("main.c / main : realloc() error", 0); goto _NewSession; }
       
        // Byte copy the screen into the buffer for fast compare
        memcpy(pBuffer, pRaster, iSize);

    }

    // Preset framebuffer update message X and Y size to XDC_TILE
    mFBRMsg.r.w =
    mFBRMsg.r.h = XDC_TILE;

    // Release a key to the client socket so that child process can grab it
    if (-1 == (iDuplicateSocketKey = ReleaseCopyOfSocket(iClientSocket, UNIQUE_ID)))
    { vCleanSession("main.c / main : ReleaseCopyOfSocket() error", Errno()); goto _NewSession; }
    
    // Create incoming messages handling child process
    if (!CreateNewProcTags(
          NP_Entry, vProcessIncomes,
          NP_StackSize, 32000,
          NP_Name, "AmiVNC handler",
          TAG_DONE
       ))
    { vCleanSession("main.c / main : CreateNewProcTags() error", 0); goto _NewSession; }
        
    // While not end of session (by child or by ourself)
    while (!bDie)
    {
    // Search for active screen change
    if (IntuitionBase -> FirstScreen != pActiveScreen)
    {
        // Check if new screen has same geometry as previous one
        if (GetCyberMapAttr(IntuitionBase -> FirstScreen -> RastPort.BitMap, CYBRMATTR_ISCYBERGFX)
         && GetCyberMapAttr(IntuitionBase -> FirstScreen -> RastPort.BitMap, CYBRMATTR_ISLINEARMEM)
         && iWidth == GetCyberMapAttr(IntuitionBase -> FirstScreen -> RastPort.BitMap, CYBRMATTR_WIDTH)
         && iHeight == GetCyberMapAttr(IntuitionBase -> FirstScreen -> RastPort.BitMap, CYBRMATTR_HEIGHT)
         && iDepth == GetCyberMapAttr(IntuitionBase -> FirstScreen -> RastPort.BitMap, CYBRMATTR_BPPIX))
        {
            
            // Grab new raster pointer
            pActiveScreen = IntuitionBase -> FirstScreen;
            printf("main.c / main : Screen set to [%s]\n", pActiveScreen -> Title);
            UnLockBitMap(LockBitMapTags(pActiveScreen -> RastPort.BitMap,
                 LBMI_BASEADDRESS, (ULONG *) &uCnt,
                 TAG_DONE));
            pRaster = (UBYTE *) uCnt;
        }
        else
        { vCleanSession("main.c / main : screenmode changed", 0); goto _NewSession; }
    }
                
    // Search for changes in screen...
    for (jCnt = 0 ; jCnt < iHeight; jCnt += XDC_TILE)
    {
        for (iCnt = 0 ; iCnt < iWidth ; iCnt += XDC_TILE)
        {
            register int iYtile;
            BOOL bChange = FALSE;
    
            for (iYtile = 0 ; iYtile < XDC_TILE ; iYtile ++)
            {
                if (memcmp((UBYTE *) (pBuffer) + iDepth * (iCnt + (jCnt + iYtile) * iWidth),
                   (UBYTE *) (pRaster) + iDepth * (iCnt + (jCnt + iYtile) * iWidth),
                   XDC_TILE * iDepth))
                {
                    memcpy((UBYTE *) (pBuffer) + iDepth * (iCnt + (jCnt + iYtile) * iWidth),
                       (UBYTE *) (pRaster) + iDepth * (iCnt + (jCnt + iYtile) * iWidth),
                       XDC_TILE * iDepth);
                    bChange = TRUE;
                }
            }
        
        // If change found, send the tile
        if (bChange)
        {
            if (-1 == (send(iClientSocket, (UBYTE *) &mFBUpdMsg, sizeof(mFBUpdMsg), 0)))
            { vCleanSession(XDC_SEND, Errno()); goto _NewSession; }

            mFBRMsg.r.x = iCnt;
            mFBRMsg.r.y = jCnt;
       
            // Send framebuffer update header
            if (-1 == (send(iClientSocket, (UBYTE *) &mFBRMsg, sizeof(mFBRMsg), 0)))
            { vCleanSession(XDC_SEND, Errno()); goto _NewSession; }

            // Send update data
            if (bFast) // 2 byte pixels under Pic96 : send directly from buffer (2 is idepth)
            {
                for (iYtile = 0 ; iYtile < XDC_TILE ; iYtile ++)
                   memcpy(uTile + XDC_TILE * iYtile * 2,
                          pRaster + 2 * (iCnt + (jCnt + iYtile) * iWidth),
                          XDC_TILE * 2);
            
                // Send framebuffer update pixel data
                if (-1 == (send(iClientSocket, (UBYTE *) uTile, (LONG) XDC_TILE * XDC_TILE * 2, 0)))
                { vCleanSession(XDC_SEND, Errno()); goto _NewSession; }
            }
            else // Make 4 byte pixels out of raster
            {
                ReadPixelArray(uTile,     // Buffer
                           0, 0,        // Dest X/Y in buffer
                           XDC_TILE * XDC_C_MAXDEPTH,
                           &(pActiveScreen -> RastPort),
                           iCnt, jCnt,         // Source X/Y
                           XDC_TILE, XDC_TILE,  // Source w/h
                           RECTFMT_ARGB
                           );
                        
                // Send framebuffer update pixel data
                if (-1 == (send(iClientSocket, (UBYTE *) uTile, (LONG) XDC_TILE * XDC_TILE * XDC_C_MAXDEPTH, 0)))
                { vCleanSession(XDC_SEND, Errno()); goto _NewSession; }
            }
        }
        }
    }
    }
    
    vCleanSession("main.c / main : Session stop (child stopped)", 0);
    goto _NewSession;
}
