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

#define SA struct sockaddr

extern	size_t	Write( int slot, void *data, size_t size );
extern	void	Bridge( void );

/* thanks sno for the networking help :) */

void *Accept( void )
{
int	sock;
int	InSock;
int	port;
struct sockaddr_in myAddr;
struct sockaddr_in *remAddr;
int     remAddrSize=0;
pthread_attr_t attr, *attrPtr = &attr;

RegisterThread("Arbiter","Manages the client and server communication",TRUE);

pthread_attr_init(attrPtr);
pthread_attr_setdetachstate(attrPtr,1);

port = GetConfigInt("Arbiter.ListenPort=",0);
/* Prepare to listen on the port */
bzero( &myAddr, sizeof(myAddr) );
myAddr.sin_family = AF_INET;
myAddr.sin_port = htons( port );
myAddr.sin_addr.s_addr = htonl( INADDR_ANY );

/* Create a socket */
sock = socket(PF_INET,SOCK_STREAM,0);

/* Bind socket to local port */
if ( bind(sock, (SA *) &myAddr, sizeof(myAddr)) < 0 )
   {
   Error(3,"Couldn't bind socket to local port, exiting.");
   printf("\r                                                              \r");
   printf("-  (!) I couldn't bind() to the local port (%5i)             -\n",port);
   printf("-  (x) Exiting ...                                             -\n");
   sleep(1);
   exit(-1);
   }

/* Setup listen */
listen(sock, 100);

while ( 1 )
   {
   /* Accept Connection */
   remAddrSize = 0;
   InSock = accept(sock, (SA *)&remAddr, &remAddrSize);
   cBusAdd(InSock,0);
   free(remAddr);
   }

}
