/* -TAG:LICENSE-
   
   This file is under the DigitalSpark Freeware Class License, see the
   file LICENSE for complete licensing information.
                                                         
                                                         -TAG:LICENSE- */
#include <Threading.h>
#include "tricky.h"   

extern	int ClientFilter( char *data );
extern	int ServerFilter( char *data );
extern	size_t Write( int slot, void *data, size_t size );

/* Bridges between the client and server sockets */

void *ClientBridge( void )
{
char	cData[1024];
char	Buffer[10];
int	sDis=0;
int	cPos=0;
int	i=0;

/* find a socket that needs to be bridged */
while ( i <= MAX_CLIENTS )
   {
   if ( Client[i].State == CS_NEEDBRIDGE )
      {
      if ( pthread_mutex_trylock(&Client[i].Mutex) == 0 )
         break;
      }
   i++;
   }

if ( i > MAX_CLIENTS )
   {
   Error(0,"Unnessisary bridge spawned .. exiting.");
   pthread_exit(NULL);
   }

Client[i].State = CS_USED;

pthread_mutex_unlock(&Client[i].Mutex);

while ( 1 )
   {
   sDis = ServerConnected;

   if ( Client[i].State == CS_USED )
      {
      /* Check for incoming from client */

      if ( read(Client[i].Sock,&Buffer,1) != 1 )
         {
         cBusRemove(Client[i].Sock);
         pthread_exit(NULL);
         }
      cData[cPos] = Buffer[0];
      cPos++;
      if (( Buffer[0] == 0x0a ) || ( cPos > 1022 ))
         {
         cData[cPos] = 0;
         if ( ClientFilter(cData) == 0 )
            {
            if ( Client[i].Authorized == 1 )
               {
               if ( Write(ServerSock,cData,0) < 0 )
                  ServerConnected = 0;
               }
            }
         cPos = 0;
         }
      }
   else
      pthread_exit(NULL);

   if ( sDis > ServerConnected )
      {
      ServerAuth = 0;
      Error(0,"Server Disconnected");
      }

   }

return 0;
}
