void saveexit(int status)
{
   int i;
   SendMessage(client_message[SPIKE_MAIN].fd, EXITING, NULL, 0);
   /* sleep so that all of the other programs have a chance to get the message*/
   sleep(1);
   CloseSockets(server_message);
   CloseSockets(client_message);
   CloseSockets(server_data);
   fclose(STATUSFILE);
   exit(status);
}
Exemple #2
0
status_t Thread :: WaitForInternalThreadToExit()
{
   if (_threadRunning)
   {
#if defined(MUSCLE_USE_CPLUSPLUS11_THREADS)
# if !defined(MUSCLE_NO_EXCEPTIONS)
      try {
# endif
         _thread.join();
# if !defined(MUSCLE_NO_EXCEPTIONS)
      }
      catch(...) {return B_ERROR;}
# endif
#elif defined(MUSCLE_USE_PTHREADS)
      (void) pthread_join(_thread, NULL);
#elif defined(MUSCLE_PREFER_WIN32_OVER_QT)
      (void) WaitForSingleObject(_thread, INFINITE);
      ::CloseHandle(_thread);  // Raymond Dahlberg's fix for handle-leak problem
#elif defined(MUSCLE_QT_HAS_THREADS)
      (void) _thread.wait();
#elif defined(__BEOS__) || defined(__HAIKU__)
      status_t junk;
      (void) wait_for_thread(_thread, &junk);
#elif defined(__ATHEOS__)
      (void) wait_for_thread(_thread);
#endif
      _threadRunning = false;
      CloseSockets();
      return B_NO_ERROR;
   }
   else return B_ERROR;
}
/*
 *	Cleanup
 */
int CGuiThread::ExitInstance()
{
	UpdateRegistry();
	CloseSockets();	// buggy old clients do not close sockets on exit. So we imitate closing manually
	UnloadPlugins();
	DeleteWorld();

	return CWinThread::ExitInstance();
}
SocketsToSDL::~SocketsToSDL()
{
    m_bTerminate = true;
	Notify();
	pthread_join(m_SendThread, 0);
	pthread_mutex_destroy(&m_SendMutex);

    CloseSockets();
}
PoolSession::~PoolSession()
{
    /// - If have unclosed socket, close it
    CloseSockets();

    ///- empty incoming packet queue
    WorldPacket* packet = NULL;
    while (_recvPoolQueue.next(packet))
        delete packet;
}
Exemple #6
0
/**
 * @brief Destructor.
 */
NetInstanceUDP::~NetInstanceUDP()
{
	const char * cCommand = "an internal function (~NetInstanceUDP)";
	try
	{
		CloseSockets();
		delete socketUDP;
	}
	MSG_CATCH
}
Exemple #7
0
TSS2_RC InitSocketTcti (
    TSS2_TCTI_CONTEXT *tctiContext, // OUT
    size_t *contextSize,            // IN/OUT
    const TCTI_SOCKET_CONF *conf,              // IN
    const uint64_t magic,
    const uint32_t version,
	const char *interfaceName,
    const uint8_t serverSockets
    )
{
    TSS2_RC rval = TSS2_RC_SUCCESS;
    SOCKET otherSock;
    SOCKET tpmSock;

    if( tctiContext == NULL )
    {
        *contextSize = sizeof( TSS2_TCTI_CONTEXT_INTEL );
        return TSS2_RC_SUCCESS;
    }
    else
    {
        (*printfFunction)(NO_PREFIX, "Initializing %s Interface\n", interfaceName );

        // Init TCTI context.
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->magic = magic;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->version = version;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->transmit = SocketSendTpmCommand;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->receive = SocketReceiveTpmResponse;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->finalize = SocketFinalize;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->cancel = SocketCancel;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->getPollHandles = 0;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->setLocality = SocketSetLocality;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.locality = 3;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.commandSent = 0;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.rmDebugPrefix = 0;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->currentTctiContext = 0;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->previousStage = TCTI_STAGE_INITIALIZE;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.tagReceived = 0;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.responseSizeReceived = 0;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.protocolResponseSizeReceived = 0;

        rval = (TSS2_RC) InitSockets( conf->hostname, conf->port, serverSockets, &otherSock, &tpmSock );
        if( rval == TSS2_RC_SUCCESS )
        {
            ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->otherSock = otherSock;
            ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->tpmSock = tpmSock;
        }
        else
        {
            CloseSockets( otherSock, tpmSock);
        }            
    }

    return rval;
}
Exemple #8
0
void SocketFinalize(
    TSS2_TCTI_CONTEXT *tctiContext       /* in */
    )
{
    // Send session end messages to servers.
    SocketSendSessionEnd( tctiContext, 1 );
    SocketSendSessionEnd( tctiContext, 0 );

    CloseSockets( TCTI_CONTEXT_INTEL->otherSock, TCTI_CONTEXT_INTEL->tpmSock );

    free( tctiContext );
}
Exemple #9
0
TSS2_RC InitSocketTcti (
    TSS2_TCTI_CONTEXT *tctiContext, // OUT
    size_t *contextSize,            // IN/OUT
    const TCTI_SOCKET_CONF *conf,              // IN
    const uint8_t serverSockets
    )
{
    TSS2_RC rval = TSS2_RC_SUCCESS;
    SOCKET otherSock;
    SOCKET tpmSock;

    if( tctiContext == NULL )
    {
        *contextSize = sizeof( TSS2_TCTI_CONTEXT_INTEL );
        return TSS2_RC_SUCCESS;
    }
    else
    {
        // Init TCTI context.
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->magic = TCTI_MAGIC;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->version = TCTI_VERSION;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->transmit = SocketSendTpmCommand;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->receive = SocketReceiveTpmResponse;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->finalize = SocketFinalize;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->cancel = SocketCancel;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->getPollHandles = 0;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->setLocality = SocketSetLocality;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.locality = 3;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.commandSent = 0;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.rmDebugPrefix = 0;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->currentTctiContext = 0;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->previousStage = TCTI_STAGE_INITIALIZE;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.tagReceived = 0;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.responseSizeReceived = 0;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.protocolResponseSizeReceived = 0;
        TCTI_LOG_CALLBACK( tctiContext ) = conf->logCallback;
        TCTI_LOG_BUFFER_CALLBACK( tctiContext ) = conf->logBufferCallback;
        TCTI_LOG_DATA( tctiContext ) = conf->logData;

        rval = (TSS2_RC) InitSockets( conf->hostname, conf->port, serverSockets, &otherSock, &tpmSock, TCTI_LOG_CALLBACK( tctiContext ), TCTI_LOG_DATA( tctiContext) );
        if( rval == TSS2_RC_SUCCESS )
        {
            ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->otherSock = otherSock;
            ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->tpmSock = tpmSock;
        }
        else
        {
            CloseSockets( otherSock, tpmSock);
        }            
    }

    return rval;
}
Exemple #10
0
TCPServer::~TCPServer(){
    CloseSockets();
    if(HID_DEBUG){ printf("TCPServer::~TCPServer(line %d): Thread will be closed\n",__LINE__); }
    TCPServer::AttachDetach(DETACH);
    exitThread = 1;
    if(TCPServer::pThread != NULL){
        if(HID_DEBUG){ printf("TCPServer::~TCPServer(line %d): Deleting it!\n",__LINE__); }
        delete TCPServer::pThread;
    }
    if(HID_DEBUG){ printf("TCPServer::~TCPServer(line %d): Thread done\n",__LINE__); }
    TCPServer::pThread = NULL;
}
Exemple #11
0
TSS2_RC SocketFinalize(
    TSS2_TCTI_CONTEXT *tctiContext       /* in */
    )
{
    TSS2_RC rval = TSS2_RC_SUCCESS;
    
    if( tctiContext == NULL )
    {
        rval = TSS2_TCTI_RC_BAD_REFERENCE;
    }
    else
    {
        // Send session end messages to servers.
        SendSessionEndSocketTcti( tctiContext, 1 );
        SendSessionEndSocketTcti( tctiContext, 0 );

        CloseSockets( TCTI_CONTEXT_INTEL->otherSock, TCTI_CONTEXT_INTEL->tpmSock );

        free( tctiContext );
    }

    return rval;
}
Exemple #12
0
TSS2_RC InitSocketsTcti (
    TSS2_TCTI_CONTEXT *tctiContext, // OUT
    size_t *contextSize,            // IN/OUT
    const char *config,              // IN
    const uint64_t magic,
    const uint32_t version,
	const char *interfaceName,
    const uint8_t serverSockets
    )
{
    TSS2_RC rval = TSS2_RC_SUCCESS;
    char hostName[200];
    int port;
    SOCKET otherSock;
    SOCKET tpmSock;

    if( tctiContext == NULL )
    {
        *contextSize = sizeof( TSS2_TCTI_CONTEXT_INTEL );
        return TSS2_RC_SUCCESS;
    }
    else
    {
        OpenOutFile( &outFp );
        (*printfFunction)(NO_PREFIX, "Initializing %s Interface\n", interfaceName );

        // Init TCTI context.
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->magic = magic;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->version = version;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->transmit = SocketSendTpmCommand;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->receive = SocketReceiveTpmResponse;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->finalize = SocketFinalize;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->cancel = SocketCancel;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->getPollHandles = 0;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->setLocality = SocketSetLocality;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.locality = 3;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.commandSent = 0;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.rmDebugPrefix = 0;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->currentTctiContext = 0;

        // Get hostname and port.
        if( ( strlen( config ) + 2 ) <= ( HOSTNAME_LENGTH  ) )
        {
            if( 1 == sscanf( config, "%199s", hostName ) ) 
            {
                if( strlen( config) - ( strlen( hostName ) + 2 ) <= PORT_LENGTH )
                {
                    if( 1 != sscanf( &config[strlen( hostName )], "%d", &port ) )
                    {
                        return( TSS2_TCTI_RC_BAD_VALUE );
                    }
                }
                else
                {
                    return( TSS2_TCTI_RC_BAD_VALUE );
                }
            }
            else
            {
                return( TSS2_TCTI_RC_BAD_VALUE );
            }
        }
        else
        {
            return( TSS2_TCTI_RC_INSUFFICIENT_BUFFER );
        }

        rval = (TSS2_RC) InitSockets( &hostName[0], port, serverSockets, &otherSock, &tpmSock );
        if( rval == TSS2_RC_SUCCESS )
        {
            ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->otherSock = otherSock;
            ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->tpmSock = tpmSock;
        }
        else
        {
            CloseSockets( otherSock, tpmSock);
        }            
        CloseOutFile( &outFp );
    }

    return rval;
}
Exemple #13
0
void TCPServer::DoTCPThreadInternal(){
    s32 ret;
    s32 len;
    while (1) {
        if(exitThread) break;
        memset(&(this->sock_addr),0,sizeof(sock_addr));
		sock_addr.sin_family = AF_INET;
		sock_addr.sin_port = DEFAULT_TCP_PORT;
		sock_addr.sin_addr.s_addr = 0;

		this->sockfd = ret = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
		if(ret == -1){ ErrorHandling(); continue;}
        s32 enable = 1;

        setsockopt(this->sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable));

		ret = bind(this->sockfd, (sockaddr *)&sock_addr, 16);
		if(ret < 0) { ErrorHandling(); continue;}
		ret = listen(this->sockfd, 1);
		if(ret < 0){ ErrorHandling(); continue;}

        do{
            if(HID_DEBUG){ printf("TCPServer::DoTCPThreadInternal(line %d): Waiting for a connection\n",__LINE__); }
            if(exitThread) break;
            len = 16;

            /**
                Handshake
                1. At first this server sends his protocol version
                2. The network clients answers with his preferred version (which needs to be equals or lower the version this server sent him) or an abort command.
                    3a. If the client sent a abort, close the connection and wait for another connection
                    3b. If the client sent his highest supported version, the server confirm that he is able to use this version (by sending the version back) or sending a abort command to disconnect.
            **/

            clientfd = ret = (s32)accept(sockfd, (sockaddr *)&(sock_addr),(socklen_t *) &len);

            if(ret == -1){ ErrorHandling(); break;}
            printf("TCPServer::DoTCPThreadInternal(line %d): TCP Connection accepted! Sending my protocol version: %d (0x%02X)\n",__LINE__, (WIIU_CP_TCP_HANDSHAKE - WIIU_CP_TCP_HANDSHAKE_VERSION_1)+1,WIIU_CP_TCP_HANDSHAKE);

            gUDPClientip = sock_addr.sin_addr.s_addr;
            UDPClient::createInstance();

            s32 ret;
            ret = ControllerPatcherNet::sendbyte(clientfd, WIIU_CP_TCP_HANDSHAKE); //Hey I'm a WiiU console!
            if(ret < 0){ printf("TCPServer::DoTCPThreadInternal(line %d): Error sendbyte: %02X\n",__LINE__,WIIU_CP_TCP_HANDSHAKE); ErrorHandling(); break;}

            u8 clientProtocolVersion = ControllerPatcherNet::recvbyte(clientfd);
            if(ret < 0){ printf("TCPServer::DoTCPThreadInternal(line %d): Error recvbyte: %02X\n",__LINE__,WIIU_CP_TCP_HANDSHAKE); ErrorHandling(); break;}

            if(clientProtocolVersion == WIIU_CP_TCP_HANDSHAKE_ABORT){
                 printf("TCPServer::DoTCPThreadInternal(line %d): The network client wants to abort.\n",__LINE__);
                 ErrorHandling(); break;
            }

            printf("TCPServer::DoTCPThreadInternal(line %d): received protocol version: %d (0x%02X)\n",__LINE__,(clientProtocolVersion - WIIU_CP_TCP_HANDSHAKE_VERSION_1)+1,clientProtocolVersion);

            if(clientProtocolVersion >= WIIU_CP_TCP_HANDSHAKE_VERSION_MIN && clientProtocolVersion <= WIIU_CP_TCP_HANDSHAKE_VERSION_MAX){
                printf("TCPServer::DoTCPThreadInternal(line %d): We support this protocol version. Let's confirm it to the network client.\n",__LINE__);
                gUsedProtocolVersion = clientProtocolVersion;
                ret = ControllerPatcherNet::sendbyte(clientfd, clientProtocolVersion);
                if(ret < 0){ printf("TCPServer::DoTCPThreadInternal(line %d): Error sendbyte: %02X\n",__LINE__,clientProtocolVersion); ErrorHandling(); break;}
            }else{
                printf("TCPServer::DoTCPThreadInternal(line %d): We don't support this protocol version. We need to abort =(.\n",__LINE__);
                ret = ControllerPatcherNet::sendbyte(clientfd, WIIU_CP_TCP_HANDSHAKE_ABORT);
                ErrorHandling(); break;
            }

            printf("TCPServer::DoTCPThreadInternal(line %d): Handshake done! Success!\n",__LINE__);

            TCPServer::DetachAndDelete(); //Clear connected controller
            RunTCP();

            if(clientfd != -1){
                socketclose(clientfd);
            }
            clientfd = -1;
        }while(0);
        printf("TCPServer::DoTCPThreadInternal(line %d): Connection closed\n",__LINE__);
        gUDPClientip = 0;
        UDPClient::destroyInstance();
        TCPServer::DetachAndDelete(); //Clear connected controller
        CloseSockets();
		continue;
	}

}
void SocketsToSDL::RunThread()
{
#ifdef WIN32
    FD_SET fdRead;
    int fd_max = -1;
#else
    fd_set fdRead;
    fd_set fdWrite;
    int fd_max = m_Read_Sign;
#endif
	while (!m_bTerminate)
	{
		FD_ZERO(&fdRead);
#ifndef WIN32
		FD_ZERO(&fdWrite);
#endif

		int iNum = m_SocketHandles.size();
        for (int i = 0; i < iNum; i++)
		{
			SOCK_HANDLE * pHandle = m_SocketHandles[i];
			int socket = pHandle->socket;
			FD_SET(socket, &fdRead);
#ifndef WIN32
			FD_SET(socket, &fdWrite);
#endif
            fd_max = fd_max > socket? fd_max : socket;
		}
		FD_SET(m_Read_Sign, &fdRead);

#ifdef WIN32
        if (select(0, &fdRead, NULL, NULL, NULL) == SOCKET_ERROR)
#else
        if (select(fd_max+1, &fdRead, &fdWrite, NULL, NULL) == SOCKET_ERROR)
#endif
		{
            goto SOCKET_WRONG;
		}

        bool bSend = FD_ISSET(m_Read_Sign, &fdRead);
		if (bSend)
		{
			unsigned char buffer[8];
			int bytes_read = 0;
			do
			{
				bytes_read = recv(m_Read_Sign, (char *)buffer, sizeof(buffer), 0);
			} while (bytes_read > 0);
            for (int i = 0; i < iNum; i++)
            {
                SOCK_HANDLE * pHandle = m_SocketHandles[i];
                if(!Send(pHandle))
                    goto SOCKET_WRONG;
            }
		}

        for (int i = 0; i < iNum; i++)
		{
			SOCK_HANDLE * pHandle = m_SocketHandles[i];
			if (FD_ISSET(pHandle->socket, &fdRead))
			{
                if(!Receive(pHandle))
                    goto SOCKET_WRONG;
            }
		}
	}
    return;

SOCKET_WRONG:
    m_bTerminate = true;
    CloseSockets();

    if(m_pNetwork)
        m_pNetwork->onNetworkBroken();
    return;
}
enum TVerdict CEsockTest11_3::easyTestStepL()
	{
	TInetAddr addrLocal, addrRemote;
	TRequestStatus wstat, wstat2, wstat3, rstat;
	TInt sockIndex1, sockIndex2, sockIndex3;
	
	const TInt KBufSize = 4024;
	// Constructs an empty 8 bit modifiable buffer descriptor. It contains no data.
	typedef TBuf8<KBufSize> TBuffer;
	
	// get local ip address
	TESTL(GetIpAddressFromConfig(_L("Test_11.3"), _L("ipAddressLocal"), addrLocal));
	
	// get ip address to connect to (usually loopback)
	TESTL(GetIpAddressFromConfig(_L("Test_11.3"), _L("ipAddressRemote"), addrRemote));
	
	// open socket and listen for connect requests
	TESTL(KErrNone == OpenListeningSocketL(addrLocal, sockIndex1));
	
	// open active socket and make connect request
	TESTL(KErrNone == OpenActiveSocketL(addrRemote, sockIndex2));
	
	// accept connect request
	TESTL(KErrNone == AcceptConnectionL(sockIndex3, sockIndex1));
	
	TBuffer* wtemp=new (ELeave) TBuffer;
	CleanupStack::PushL(wtemp);
	TBuffer& wbuf=*wtemp;
	
	TBuffer* rtemp=new (ELeave) TBuffer;
	CleanupStack::PushL(rtemp);
	TBuffer& rbuf=*rtemp;
	
	wbuf.SetMax();
	StripeDes(wbuf, 0, wbuf.Length(), '@', 'Z');
	
	iEsockSuite->GetSocketHandle(sockIndex2).Send(wbuf, 0, wstat);
	iEsockSuite->GetSocketHandle(sockIndex2).Send(wbuf, 0, wstat2);
	iEsockSuite->GetSocketHandle(sockIndex2).Send(wbuf, 0, wstat3);
	iEsockSuite->GetSocketHandle(sockIndex2).CancelAll();
	User::WaitForRequest(wstat);
	User::WaitForRequest(wstat2);
	User::WaitForRequest(wstat3);
	TESTEL(wstat==KErrNone || wstat==KErrCancel, wstat.Int());
	TESTEL(wstat2==KErrNone || wstat2==KErrCancel, wstat2.Int());
	TESTEL(wstat3==KErrNone || wstat3==KErrCancel, wstat3.Int());
	
	Logger().WriteFormat(_L("stat1 %d stat2 %d stat3 %d"),wstat.Int(), wstat2.Int(), wstat3.Int());
	
	iEsockSuite->GetSocketHandle(sockIndex3).Recv(rbuf, 0, rstat);
	iEsockSuite->GetSocketHandle(sockIndex3).CancelAll();
	User::WaitForRequest(rstat);
	TESTEL(rstat==KErrNone || rstat==KErrCancel, rstat.Int());
	
	iEsockSuite->GetSocketHandle(sockIndex2).Shutdown(RSocket::ENormal, wstat);
	iEsockSuite->GetSocketHandle(sockIndex3).Shutdown(RSocket::ENormal, rstat);
	iEsockSuite->GetSocketHandle(sockIndex2).CancelAll();
	iEsockSuite->GetSocketHandle(sockIndex3).CancelAll();
	User::WaitForRequest(wstat);
	User::WaitForRequest(rstat);
	TESTEL(wstat == KErrNone, wstat.Int());
	TESTEL(rstat == KErrNone, rstat.Int());

	CleanupStack::PopAndDestroy(2, wtemp);
	
	// shutdown the client socket - do not wait for completion
	CloseSockets(2);
	return EPass;
	}
int
main(int argc, char *argv[])
{
    int         i, oldumask;

    argcGlobal = argc;
    argvGlobal = argv;

    configfilename = NULL;

    /* init stuff */
    ProcessCmdLine(argc, argv);

    /*
     * Do this first thing, to get any options that only take effect at
     * startup time.  It is read again each time the server resets.
     */
    if (ReadConfigFile(configfilename) != FSSuccess) {
	FatalError("couldn't read config file\n");
    }
    InitErrors();

    /* make sure at least world write access is disabled */
    if (((oldumask = umask(022)) & 002) == 002)
	(void)umask(oldumask);

    SetDaemonState();
    SetUserId();

    while (1) {
	serverGeneration++;
	OsInit();
	if (serverGeneration == 1) {
	    /* do first time init */
	    CreateSockets(OldListenCount, OldListen);
	    InitProcVectors();
	    clients = (ClientPtr *) fsalloc(MAXCLIENTS * sizeof(ClientPtr));
	    if (!clients)
		FatalError("couldn't create client array\n");
	    for (i = MINCLIENT; i < MAXCLIENTS; i++)
		clients[i] = NullClient;
	    /* make serverClient */
	    serverClient = (ClientPtr) fsalloc(sizeof(ClientRec));
	    if (!serverClient)
		FatalError("couldn't create server client\n");
	}
	ResetSockets();

	/* init per-cycle stuff */
	InitClient(serverClient, SERVER_CLIENT, (pointer) 0);

	clients[SERVER_CLIENT] = serverClient;
	currentMaxClients = MINCLIENT;
	currentClient = serverClient;

	if (!InitClientResources(serverClient))
	    FatalError("couldn't init server resources\n");

	InitAtoms();
	InitFonts();
	SetConfigValues();
	if (!create_connection_block())
	    FatalError("couldn't create connection block\n");

#ifdef DEBUG
	fprintf(stderr, "Entering Dispatch loop\n");
#endif

	Dispatch();

#ifdef DEBUG
	fprintf(stderr, "Leaving Dispatch loop\n");
#endif

	/* clean up per-cycle stuff */
	if ((dispatchException & DE_TERMINATE) || drone_server)
	    break;
	fsfree(ConnectionInfo);
	/* note that we're parsing it again, for each time the server resets */
	if (ReadConfigFile(configfilename) != FSSuccess)
	    FatalError("couldn't read config file\n");
    }

    CloseSockets();
    CloseErrors();
    exit(0);
}
Exemple #17
0
void TCPServer::ErrorHandling(){
    CloseSockets();
    wiiu_os_usleep(1000*1000*2);
}
bool SocketsToSDL::CreateSignal()
{
    int tcp1, tcp2;
    sockaddr_in name;
	memset(&name, 0, sizeof(name));
	name.sin_family = AF_INET;
	name.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
#ifdef WIN32
    int namelen = sizeof(name);
#else
    size_t namelen = sizeof(name);;
#endif

    tcp1 = tcp2 = -1;
	int tcp = socket(AF_INET, SOCK_STREAM, 0);
	if (tcp == -1){
		goto clean;
	}
	if (bind(tcp, (sockaddr*)&name, namelen) == -1){
		goto clean;
	}
	if (::listen(tcp, 5) == -1){
		goto clean;
	}
#ifdef ANDROID
    if (getsockname(tcp, (sockaddr*)&name, (socklen_t *)&namelen) == -1){
#else
    if (getsockname(tcp, (sockaddr*)&name, &namelen) == -1){
#endif
        goto clean;
	}
    tcp1 = socket(AF_INET, SOCK_STREAM, 0);
	if (tcp1 == -1){
		goto clean;
	}
    if (-1 == connect(tcp1, (sockaddr*)&name, namelen)){
		goto clean;
	}
#ifdef ANDROID
    tcp2 = accept(tcp, (sockaddr*)&name, (socklen_t *)&namelen);
#else
    tcp2 = accept(tcp, (sockaddr*)&name, &namelen);
#endif
	if (tcp2 == -1){
		goto clean;
	}
#ifdef WIN32
    if (closesocket(tcp) == -1){
#else
    if (close(tcp) == -1){
#endif
        goto clean;
	}
	m_Write_Sign = tcp1;
	m_Read_Sign = tcp2;
#ifdef WIN32
    {
        u_long iMode = 1;
        ioctlsocket(m_Read_Sign, FIONBIO, (u_long FAR*) &iMode);
    }
#else
    #include<fcntl.h>
    fcntl(m_Read_Sign,F_SETFL, O_NONBLOCK);
#endif
    return true;

clean:
	if (tcp != -1){
#ifdef WIN32
        closesocket(tcp);
#else
        close(tcp);
#endif
    }
	if (tcp2 != -1){
#ifdef WIN32
        closesocket(tcp2);
#else
        close(tcp2);
#endif
    }
	if (tcp1 != -1){
#ifdef WIN32
        closesocket(tcp1);
#else
        close(tcp1);
#endif
    }
	return false;
}

void* StartSocketThread(void* p) {
	SocketsToSDL * pThis = (SocketsToSDL *)p;
	pThis->RunThread();
	return 0;
}

bool SocketsToSDL::ConnectTo(std::vector<IChannel *> Channels, INetworkStatus * pNetwork)
{
    m_pNetwork = pNetwork;
	if (!CreateSignal())
		return false;

    int iNum = Channels.size();
    for (int i = 0; i < iNum; i++)
	{
        LOGE("-------");
        SOCK_HANDLE * pHandle = getNewSocketHandle(Channels[i], m_sHost, m_iPort);

        if(pHandle != NULL)
        {
            m_SocketHandles.push_back(pHandle);
            Channels[i]->setSocketManager(this, pHandle);
        }
        else
        {
            goto FAILED;
        }
	}

    m_bTerminate = false;
	if (0 != pthread_create(&m_SendThread, 0, &StartSocketThread, this))
		goto FAILED;

    return true;

FAILED:
    CloseSockets();
    return false;
}