Example #1
0
CIpSocket::t_SOCKET CIpSocket::Detach()
{   
	// Save away the socket handle
	t_SOCKET hSocket = m_hSocket;

	// Ditch the event handle
	CloseEventHandle();

	// We won't be freeing the socket
	m_hSocket = c_InvalidSocket;
	
	// Free whatever else is left
	Destroy();

	// It's the callers problem now
	return hSocket;
}
Example #2
0
/**
 * main
 * 
 * executable entry point
 */
INT __cdecl main(INT argc, CHAR **argv)
{
    int     i;
    int     err;
    struct  sockaddr_in mySockaddr;
    WSADATA wsaData;        

    /* Sockets descriptor */
    const int numSockets = 1;    /* number of sockets used in this test */

    SOCKET testSockets[1];    
    
    
    /* Variables for WSASend */

    WSABUF wsaSendBuf;
    DWORD  dwNbrOfByteSent;
    DWORD  dwNbrOfBuf  = 1;
    DWORD  dwSendFlags = 0;
    
    unsigned char   *sendBuffer;    

    WSAOVERLAPPED wsaOverlapped;    
    
    /* Socket DLL version */
    const WORD wVersionRequested = MAKEWORD(2,2);

    HANDLE  hWriteEvent;
    DWORD   waitResult;        

    /* PAL initialization */
    if( PAL_Initialize(argc, argv) != 0 )
    {        
        return FAIL;
    }
    
    /* Sockets initialization to INVALID_SOCKET */
    for( i = 0; i < numSockets; i++ )
    {
        testSockets[i] = INVALID_SOCKET;
    }

    /* Initialize to use winsock2.dll */
    err = WSAStartup( wVersionRequested,
                      &wsaData);

    if(err != 0)
    {
        Trace( "Client error: Unexpected failure: "
              "WSAStartup(%i) "
              "returned %d\n",
              wVersionRequested, 
              GetLastError() );
        
        Fail("");
    }

    /* Confirm that the WinSock DLL supports 2.2.
       Note that if the DLL supports versions greater    
       than 2.2 in addition to 2.2, it will still return
       2.2 in wVersion since that is the version we      
       requested.                                        
    */
    if ( wsaData.wVersion != wVersionRequested ) 
    {
        Trace("Client error: Unexpected failure "
              "to find a usable version of WinSock DLL\n");

        /* Do some cleanup */
        DoWSATestCleanup( 0, 0);

        
        Fail("");
    }

    /* create an overlapped stream socket in AF_INET domain */
    testSockets[0] = WSASocketA( AF_INET, 
                                 SOCK_DGRAM, 
                                 IPPROTO_UDP,
                                 NULL, 
                                 0, 
                                 WSA_FLAG_OVERLAPPED ); 


    if( testSockets[0] == INVALID_SOCKET )
    {
        Trace("Client error: Unexpected failure: "
              "WSASocketA"
              "(AF_INET,SOCK_DGRAM,IPPROTO_UDP,NULL,0,WSA_FLAG_OVERLAPPED) "
              " returned %d\n",
              GetLastError());

        /* Do some cleanup */
        DoWSATestCleanup( 0, 0);

        Fail("");
    }
    
    /* prepare the sockaddr_in structure */
    mySockaddr.sin_family           = AF_INET;
    mySockaddr.sin_port             = getRotorTestPort();
    mySockaddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");

    memset( &(mySockaddr.sin_zero), 0, 8);      

    /* create events */
    hWriteEvent = CreateEvent( NULL, /* no security   */
                             FALSE,    /* reset type    */
                             FALSE,    /* initial state */
                             NULL );   /* object name   */
            
    if( hWriteEvent == NULL )
    {   
        CloseEventHandle(hWriteEvent);

        Trace("Client error: Unexpected failure: "
              "CreateEvent() "
              "returned %d\n",
              GetLastError());

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );
        
        Fail("");
    }  
    

     /* Initialize the WSAOVERLAPPED to 0 */
    memset(&wsaOverlapped, 0, sizeof(WSAOVERLAPPED));

    wsaOverlapped.hEvent = hWriteEvent;    
    
    /* Set the WSABUF structure */
    sendBuffer = malloc(buffer_too_large * sizeof(char));

    if(sendBuffer==NULL)
    {
        Trace("Client error, Unexpected failure: "
                "not enough memory available for malloc()");

        CloseEventHandle(hWriteEvent);

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                            numSockets );
        
        Fail("");
    }

    wsaSendBuf.len = buffer_too_large;
    wsaSendBuf.buf = sendBuffer;
      
    /* Send some data */
    err = WSASendTo( testSockets[0],
                   &wsaSendBuf,
                   dwNbrOfBuf,
                   &dwNbrOfByteSent,
                   dwSendFlags,
                   (struct sockaddr FAR *)&mySockaddr,
                    sizeof(mySockaddr),
                   &wsaOverlapped,
                   0 );

    if(err != SOCKET_ERROR )
    {   
        if(dwNbrOfByteSent!=0)
        {
            Trace("Client WSASend has "
                "return %d, expected SOCKET_ERROR.",err);

            free(sendBuffer);

            CloseEventHandle(hWriteEvent);

            /* Do some cleanup */
            DoWSATestCleanup( testSockets,
                            numSockets );
            
            Fail("");        
        }
    }

    /* handle overlapped operation */
    if(GetLastError()==WSA_IO_PENDING)
    {
        /* Wait 10 seconds for hWriteEvent to be signaled 
            for pending operation
        */
        waitResult = WaitForSingleObject( hWriteEvent,
                                            10000 );        
        
        if (waitResult!=WAIT_OBJECT_0)
        {   
            Trace("Client Error: Unexpected failure: "
                    "WaitForSingleObject has timed out \n");

            free(sendBuffer);
            
            CloseEventHandle(hWriteEvent);
            
            /* Do some cleanup */
            DoWSATestCleanup( testSockets,
                                numSockets );
            
            Fail("");
        }
    }

    free(sendBuffer);

    /*     
    According to MSDN, 
    For message-oriented sockets, care must be taken not to exceed the 
    maximum message size of the underlying transport, which can be 
    obtained by getting the value of socket option SO_MAX_MSG_SIZE. 
    If the data is too long to pass atomically through the underlying 
    protocol the error WSAEMSGSIZE is returned, and no data is transmitted.

    
    wsaOverlapped.Internal does not return WSAEMSGSIZE.
    
    Test removed: Verify that wsaOverlapped.Internal is WSAEMSGSIZE.             
    */   

    /* Verify that the number of bytes sent is 0    
    */
    if(wsaOverlapped.InternalHigh!=0)
    {   
        Trace("Client WSASend was called with a buffer larger than"
              " SO_MAX_MSG_SIZE "
              "wsaSendBuf.len = %d, "
              "wsaOverlapped.InternalHigh = % d, "
              "buffer_too_large = %d, ",
              wsaSendBuf.len, wsaOverlapped.InternalHigh,
              buffer_too_large);

        CloseEventHandle(hWriteEvent);

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );
        
        Fail("");
    }
    
    if(!CloseEventHandle(hWriteEvent))
    {
        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );
        
        Fail("");
    }

    /* Do some cleanup */
    DoWSATestCleanup( testSockets,
                      numSockets );
   
    PAL_Terminate();
    return PASS;
} 
Example #3
0
/* DWORD  PALAPI Thread_Client(LPVOID lpParam)  
   This is a client thread started by the main process.
   It simulate a client connecting to a remote server.   
*/
void  PALAPI Thread_Client(LPVOID lpParam)
{     
    int     i;
    int     err;
    struct  sockaddr_in mySockaddr;
    WSADATA wsaData;

    /* Sockets descriptor */
    const int numSockets = 1;    /* number of sockets used in this test */

    SOCKET testSockets[1];    
    
    
    /* Variables for WSASend */

    WSABUF wsaSendBuf;
    DWORD  dwNbrOfByteSent;
    DWORD  dwNbrOfBuf  = 1;
    DWORD  dwSendFlags = 0;
    
    unsigned char   sendBuffer[255];
    

    WSAOVERLAPPED wsaOverlapped;

    /* variable for iocltsocket */
    u_long argp;

    /* Variables needed for select */
    struct timeval waitTime;
    fd_set writeFds;    
    int    socketFds;    

    /* Socket DLL version */
    const WORD wVersionRequested = MAKEWORD(2,2);

    HANDLE  hWriteEvent;
    DWORD   waitResult;
    
    /* Event handle */
    HANDLE hThreadEvent;

    threadExitCode=THREAD_UNDEFINED;

    /* Create a Event with no initial owner. EventClientServer is
       the Event owned by the server.
    */
    hThreadEvent = CreateEvent( NULL, /* no security   */
                             FALSE,   /* reset type    */
                             FALSE,   /* initial state */
                             "EventClientServer" );  /* object name   */

    /* Check for error. */
    if (hThreadEvent == NULL) 
    {        
        Trace( "Client Error: Unexpected failure: "
              "CreateEvent() "
              "returned NULL\n");

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }    
    
    /* Wait 10 seconds for EventClientServer to be signaled 
       from the server. It will mean that the server is ready
       to receive data or connection.
    */
    waitResult = WaitForSingleObject( hThreadEvent,
                                      10000 );
            
    if (waitResult!=WAIT_OBJECT_0)
    {
        Trace("Client error: Unexpected failure: "
              "WaitForSingleObject has timed out while "
              "waiting for EventClientServer.\n");

        CloseEventHandle(hThreadEvent);        
    
        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }

    /* close the thread handle, don't need anymore */
    if(!CloseEventHandle(hThreadEvent))
    {
        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }
    
    /* Sockets initialization to INVALID_SOCKET */
    for( i = 0; i < numSockets; i++ )
    {
        testSockets[i] = INVALID_SOCKET;
    }

    /* Initialize to use winsock2.dll */
    err = WSAStartup( wVersionRequested,
                      &wsaData);

    if(err != 0)
    {
        Trace( "Client error: Unexpected failure: "
              "WSAStartup(%i) "
              "returned %d\n",
              wVersionRequested, 
              GetLastError() );

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }

    /* Confirm that the WinSock DLL supports 2.2.
       Note that if the DLL supports versions greater    
       than 2.2 in addition to 2.2, it will still return
       2.2 in wVersion since that is the version we      
       requested.                                        
    */
    if ( wsaData.wVersion != wVersionRequested ) 
    {
        Trace("Client error: Unexpected failure "
              "to find a usable version of WinSock DLL\n");

        /* Do some cleanup */
        DoWSATestCleanup( 0, 0);

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }

    /* create an overlapped stream socket in AF_INET domain */

    testSockets[0] = WSASocketA( AF_INET, 
                                 SOCK_STREAM, 
                                 IPPROTO_TCP,
                                 NULL, 
                                 0, 
                                 WSA_FLAG_OVERLAPPED ); 


    if( testSockets[0] == INVALID_SOCKET )

    {
        Trace("Client error: Unexpected failure: "
              "WSASocketA"
              "(AF_INET,SOCK_DGRAM,IPPROTO_UDP,NULL,0,WSA_FLAG_OVERLAPPED) "
              " returned %d\n",
              GetLastError());

        /* Do some cleanup */
        DoWSATestCleanup( 0, 0);

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }

    /* enable non blocking socket */
    argp=1;
    err = ioctlsocket(testSockets[0], FIONBIO, (u_long FAR *)&argp);

    if (err==SOCKET_ERROR )
    {
        Trace("ERROR: Unexpected failure: "
              "ioctlsocket(.., FIONBIO, ..) "
              "returned %d\n",
              GetLastError() );

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

       
        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }
    
    /* prepare the sockaddr_in structure */
    mySockaddr.sin_family           = AF_INET;
    mySockaddr.sin_port             = getRotorTestPort();
    mySockaddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");

    memset( &(mySockaddr.sin_zero), 0, 8);

    /* connect to a server */
    err = connect( testSockets[0], 
                   (struct sockaddr *)&mySockaddr,
                   sizeof(struct sockaddr));

    if( err == SOCKET_ERROR )
    {
        err = GetLastError();
        if ( err != WSAEWOULDBLOCK )
        {
            Trace("ERROR: Unexpected failure: "
              "connect() socket with local server "
              "returned %d, expected WSAEWOULDBLOCK\n",
              GetLastError());

            /* Do some cleanup */
            DoWSATestCleanup( testSockets,
                              numSockets );

            
            threadExitCode=THREAD_FAIL;

            ExitThread(0);
        }     
        
    }

    /* set the server waiting time as 10 seconds */
    waitTime.tv_sec = 10L;
    waitTime.tv_usec = 0L;

    /* initialize the except socket set  */
    FD_ZERO( &writeFds );

    /* add socket to readable socket set */
    FD_SET( testSockets[0], 
            &writeFds );

    /* monitor the readable socket set to determine the
       completion of the connection request.
    */
    socketFds = select( 0,                        
                        NULL,
                        &writeFds,
                        NULL,
                        &waitTime);

    if( socketFds == SOCKET_ERROR )
    {
        Trace("ERROR: Unexpected failure "
              "with select\n");

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        
        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }

    if( socketFds == 0 )
    {
        Trace("ERROR: Unexpected select "
              "timed out\n");

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        
        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }

    /* fill the sent buffer with value */
    for (i=0;i<255;i++)
    {
        sendBuffer[i]= i;
    }

   
    /* create events */
    hWriteEvent = CreateEvent( NULL, /* no security   */
                             FALSE,    /* reset type    */
                             FALSE,    /* initial state */
                             NULL );   /* object name   */
            
    if( hWriteEvent == NULL )
    {
        Trace("Client error: Unexpected failure: "
              "CreateEvent() "
              "returned %d\n",
              GetLastError());

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }

     /* Initialize the WSAOVERLAPPED to 0 */
    memset(&wsaOverlapped, 0, sizeof(WSAOVERLAPPED));  
    wsaOverlapped.hEvent = hWriteEvent;
    
    /* Set the WSABUF structure */
    wsaSendBuf.len = 255;        
    wsaSendBuf.buf = sendBuffer;

   
    /* Send some data */
    err = WSASend( testSockets[0],
                   &wsaSendBuf,
                   dwNbrOfBuf,
                   &dwNbrOfByteSent,
                   dwSendFlags,
                   &wsaOverlapped,
                   0 );


    if(err == SOCKET_ERROR )
    {
        if(GetLastError()!=WSA_IO_PENDING)
        {
            Trace("Client error: Unexpected failure: "
                  "WSASend() "
                  "returned %d\n",
                  GetLastError());
                 
            CloseEventHandle(hWriteEvent);

            /* Do some cleanup */
            DoWSATestCleanup( testSockets,
                              numSockets );

            threadExitCode=THREAD_FAIL;

            ExitThread(0);
        }

        /* Wait 10 seconds for hWriteEvent to be signaled 
           for pending operation
        */
        waitResult = WaitForSingleObject( hWriteEvent, 
                                          10000 );            

        if (waitResult!=WAIT_OBJECT_0)
        {  
            Trace("Client Error: Unexpected failure: "
                  "WaitForSingleObject has timed out \n");

             CloseEventHandle(hWriteEvent);
    
            /* Do some cleanup */
            DoWSATestCleanup( testSockets,
                              numSockets );        

            threadExitCode=THREAD_FAIL;
            ExitThread(0);
        }        
    }

    /* close the handle to hWriteEvent */
    if(!CloseEventHandle(hWriteEvent))
    {
        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                        numSockets );

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }

    /* Verify that the number of bytes sent are the number of byte
       specified in the wsaBuf structure 
    */
    if(wsaSendBuf.len!=wsaOverlapped.InternalHigh)
    {   
        Trace("Client WSASend has not send the number of byte requested "
              "wsaSendBuf.len = %d while "
              "wsaOverlapped.InternalHigh = % d",
              wsaSendBuf.len, wsaOverlapped.InternalHigh);        

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }

    /* Do some cleanup */
    DoWSATestCleanup( testSockets,
                      numSockets );

    threadExitCode=THREAD_SUCCESS;

    ExitThread(0);    
} 
Example #4
0
/**
 * main
 * 
 * executable entry point
 */
INT __cdecl main(INT argc, CHAR **argv)
{
    int     i;
    int     err;    
    int     addrlen = sizeof(struct sockaddr);
    struct  sockaddr_in mySockaddr;
    WSADATA wsaData;
    HANDLE  hReadEvent;
    DWORD   waitResult;

    /* Thread variable */
    HANDLE hThreadClient;
    DWORD dwThreadClient;     
    DWORD dwClientParam[2]; 

    HANDLE hThreadEvent; 

    /* Sockets descriptor */
    const int numSockets = 2;    /* number of sockets used in this test */

    SOCKET testSockets[2];

    /* variable for iocltsocket */
    u_long argp;

     /* Variables needed for setsockopt */
    BOOL bReuseAddr = TRUE;
    

    /* Variables needed for select */
    struct timeval waitTime;
    fd_set readFds;
    int    socketFds;

    /* Variables needed for WSARecv */
    WSABUF        wsaBuf;
    DWORD         dwNbrOfBuf  = 1;
    DWORD         dwNbrOfByteSent;
    DWORD         dwRecvFlags = 0;
    WSAOVERLAPPED wsaRecvOverlapped;
    
    /* Variable used to store transmitted data */
    unsigned char myBuffer[300];    
    
    /* Socket DLL version */
    const WORD wVersionRequested = MAKEWORD(2,2);

    /* Sockets initialization to INVALID_SOCKET */
    for( i = 0; i < numSockets; i++ )
    {
        testSockets[i] = INVALID_SOCKET;
    }

    /* PAL initialization */
    if( PAL_Initialize(argc, argv) != 0 )
    {
        return FAIL;
    }

    /* Initialize to use winsock2.dll */
    err = WSAStartup( wVersionRequested,
                      &wsaData);

    if(err != 0)
    {
        Fail( "Server error: Unexpected failure: "
              "WSAStartup(%i) "
              "returned %d\n",
              wVersionRequested, 
              GetLastError() );
    }

    /* Confirm that the WinSock DLL supports 2.2.
       Note that if the DLL supports versions greater    
       than 2.2 in addition to 2.2, it will still return
       2.2 in wVersion since that is the version we      
       requested.                                        
    */
    if ( wsaData.wVersion != wVersionRequested ) 
    {  
        Trace("Server error: Unexpected failure "
              "to find a usable version of WinSock DLL\n");

        /* Do some cleanup */
        DoWSATestCleanup( 0, 0);

        Fail("");
    }

    /* create an overlapped stream socket in AF_INET domain */

    testSockets[0] = WSASocketA( AF_INET, 
                                 SOCK_STREAM, 
                                 IPPROTO_TCP,
                                 NULL, 
                                 0, 
                                 WSA_FLAG_OVERLAPPED ); 


    if( testSockets[0] == INVALID_SOCKET )
    {   
        Trace("Server error: Unexpected failure: "
              "WSASocketA"
              "(AF_INET,SOCK_STREAM,IPPROTO_TCP,NULL,0,WSA_FLAG_OVERLAPPED)) "
              " returned %d\n",
              GetLastError());

        /* Do some cleanup */
        DoWSATestCleanup( 0, 0);

        Fail("");
    }

    /* Allows the socket to be bound to an address that is already in use. */
    err = setsockopt( testSockets[0],
                      SOL_SOCKET,
                      SO_REUSEADDR,
                      (const char *)&bReuseAddr,
                      sizeof( BOOL ) );

    if( err == SOCKET_ERROR )
    {
        Trace("Server error: Unexpected failure: "
              "setsockopt(.., SOL_SOCKET,SO_REUSEADDR, ..) "
              "returned %d\n",
              GetLastError() );

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }

    /* enable non blocking socket */
    argp=1;
    err = ioctlsocket(testSockets[0], FIONBIO, (u_long FAR *)&argp);

    if (err==SOCKET_ERROR )
    {
        Trace("ERROR: Unexpected failure: "
              "ioctlsocket(.., FIONBIO, ..) "
              "returned %d\n",
              GetLastError() );

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );
        
        Fail("");
    }


    /* prepare the sockaddr structure */
    mySockaddr.sin_family           = AF_INET;
    mySockaddr.sin_port             = getRotorTestPort();
    mySockaddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");

    memset( &(mySockaddr.sin_zero), 0, 8);

    /* bind local address to a socket */
    err = bind( testSockets[0],
                (struct sockaddr *)&mySockaddr,
                sizeof(struct sockaddr) );


    if( err == SOCKET_ERROR )
    {
        Trace("ERROR: Unexpected failure: "
              "bind() socket with local address "
              "returned %d\n",
              GetLastError() );

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }

    /* listen to the socket */
    err = listen( testSockets[0], 
                  listenBacklog );

    if( err == SOCKET_ERROR )
    {
        Trace("ERROR: Unexpected failure: "
              "listen() to sockets "
              "returned %d\n",
              GetLastError() );

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }

    /* set the server waiting time as 10 seconds */
    waitTime.tv_sec = 10L;
    waitTime.tv_usec = 0L;

    /* initialize the except socket set  */
    FD_ZERO( &readFds );

    /* add socket to readable socket set */
    FD_SET( testSockets[0], 
            &readFds );

    
    /* Create a Event with initial owner. */
    hThreadEvent = CreateEvent( NULL, /* no security   */
                             FALSE,   /* reset type    */
                             FALSE,   /* initial state */
                             "EventClientServer" );  /* object name   */

    if (hThreadEvent == NULL) 
    {        
        /* Check for error. */
        Trace( "Server Error: Unexpected failure: "
              "CreateEvent() "
              "returned NULL\n");

          /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }    
    
    /* create a client thread */

    hThreadClient = 
        CreateThread( 
                NULL,                        /* no security attributes */
                0,                           /* use default stack size */
                (LPTHREAD_START_ROUTINE)Thread_Client,/* thread function    */
                (LPVOID)&dwClientParam,      /* argument to thread function */
                0,                           /* use default creation flags  */
                &dwThreadClient);            /* returns the thread identifier*/

    if(hThreadClient==NULL)
    {        
        Trace( "Server Error: Unexpected failure: "
              "CreateThread() "
              "returned NULL\n");

        CloseEventHandle(hThreadEvent);        

          /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }
   
    Sleep(500);

    if(SetEvent(hThreadEvent)==0)
    {
        Trace("Server error: Unexpected failure: "
            "SetEvent has not set hThreadEvent as expected"
            "GetLastError returned = %d.\n",GetLastError());

        WaitForClientThreadToFinish(hThreadClient);

        CloseThreadHandle(hThreadClient);

        CloseEventHandle(hThreadEvent);        

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                        numSockets );

        Fail("");
    }
    
    /* set the server waiting time as 10 seconds */
    waitTime.tv_sec = 10L;
    waitTime.tv_usec = 0L;

    /* initialize the except socket set  */
    FD_ZERO( &readFds );

    /* add socket to readable socket set */
    FD_SET( testSockets[0], 
            &readFds );

    /* monitor the readable socket set 
       to determine when a connection is ready to be accepted
    */
    socketFds = select( 0,
                        &readFds,
                        NULL,
                        NULL,
                        &waitTime);
    

    if( socketFds == SOCKET_ERROR )
    {
        Trace("ERROR: Unexpected failure "
              "with select\n");

        WaitForClientThreadToFinish(hThreadClient);

        CloseThreadHandle(hThreadClient);

        CloseEventHandle(hThreadEvent);

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }

    if( socketFds == 0 )
    {
        Trace("ERROR: Unexpected select "
              "timed out\n");

        WaitForClientThreadToFinish(hThreadClient);

        CloseThreadHandle(hThreadClient);

        CloseEventHandle(hThreadEvent);   

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }

    if(CloseEventHandle(hThreadEvent)==0)
    {
        WaitForClientThreadToFinish(hThreadClient);

        CloseThreadHandle(hThreadClient);        

        Fail("");
    }

    /* accept connection */
    testSockets[1] = accept( testSockets[0],
                             (struct sockaddr *)&mySockaddr,
                             &addrlen );

    if( testSockets[1] == INVALID_SOCKET )
    {
        Trace("ERROR: Unexpected failure: "
              "accept() connection on socket "
              "returned %d\n",
              GetLastError());

        WaitForClientThreadToFinish(hThreadClient);

        CloseThreadHandle(hThreadClient);        

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }

    /* enable non blocking socket */
    argp=1;
    err = ioctlsocket(testSockets[1], FIONBIO, (u_long FAR *)&argp);

    if (err==SOCKET_ERROR )
    {
        Trace("ERROR: Unexpected failure: "
              "ioctlsocket(.., FIONBIO, ..) "
              "returned %d\n",
              GetLastError() );

        WaitForClientThreadToFinish(hThreadClient);

        CloseThreadHandle(hThreadClient);        

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }

    
    /* create an event */
    hReadEvent = CreateEvent( NULL, /* no security   */
                             FALSE,   /* reset type    */
                             FALSE,   /* initial state */
                             NULL );  /* object name   */
            
    if( hReadEvent == NULL )
    {            
        Trace("Server error: Unexpected failure: "
              "CreateEvent() "
              "returned %d\n",
              GetLastError());

        WaitForClientThreadToFinish(hThreadClient);        

        CloseThreadHandle(hThreadClient);        

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
        
    }



    /* Initialize the WSABUF structure */
    memset(myBuffer, 0, 300);
    wsaBuf.buf = myBuffer;
    wsaBuf.len = 150;
    
    
    for(i=0;i<2;i++)
    {
        /* Initialize the WSAOVERLAPPED to 0 */
        memset(&wsaRecvOverlapped, 0, sizeof(WSAOVERLAPPED));

        /* Specify which event to signal when data is arrived*/
        wsaRecvOverlapped.hEvent = hReadEvent;        

         /* Prepare to receive data */
        err = WSARecvFrom( testSockets[1],
                    &wsaBuf,
                    dwNbrOfBuf,
                    &dwNbrOfByteSent,
                    &dwRecvFlags,                    
                    (struct sockaddr FAR *)NULL,
                    (int)NULL,
                    &wsaRecvOverlapped,
                    0 );

        if( err != SOCKET_ERROR )
        {            
            /* on the second iteration it is expected to return no error
               see explanation below.
            */
            if(dwNbrOfByteSent!=150&&dwNbrOfByteSent!=105)
            {   
                Trace("Server error: WSARecv() "
                    "returned immediately and dwNbrOfByteSent is %d,"
                    "expected 150 of 105.\n",
                    dwNbrOfByteSent);
                
                WaitForClientThreadToFinish(hThreadClient);                

                CloseThreadHandle(hThreadClient);

                CloseEventHandle(hReadEvent);                

                /* Do some cleanup */
                DoWSATestCleanup( testSockets,
                                numSockets );

                Fail("");
            }
        }
        else if(GetLastError()!=WSA_IO_PENDING)
        {
            Trace("Server error: WSARecv() "
                    "returned %d, expected WSA_IO_PENDING\n",
                    err );
                
            WaitForClientThreadToFinish(hThreadClient);            
            
            CloseThreadHandle(hThreadClient);

            CloseEventHandle(hReadEvent);
            
            /* Do some cleanup */
            DoWSATestCleanup( testSockets,
                            numSockets );
    
            Fail("");
        }
        else
        {
            waitResult = WaitForSingleObject( hReadEvent,
                                            10000 );           
            
            if (waitResult!=WAIT_OBJECT_0)
            {                   
                Trace("Server error: Unexpected failure: "
                    "WaitForSingleObject has timed out \n");

                WaitForClientThreadToFinish(hThreadClient);                

                CloseThreadHandle(hThreadClient);

                CloseEventHandle(hReadEvent);                
        
                /* Do some cleanup */
                DoWSATestCleanup( testSockets,
                                numSockets );

                Fail("");
            }        
        }    

        /* if it is the first receive, we expect MSG_PARTIAL
           because the buffer sent is 255 long while the receive
           buffer is 150.

           Update : MSG_PARTIAL is not tested because it never happens.
        */
        if(i==0)
        {
             /* 
               MSDN: The lpFlags parameter is both an input and an output 
               parameter, allowing applications to sense the output state 
               of the MSG_PARTIAL flag bit. However, the MSG_PARTIAL flag bit 
               is not supported by all protocols. 

               According to win32 result, MSG_PARTIAL is not set with TCP.                              

               this test is no longer valid:
               if(wsaRecvOverlapped.Internal==MSG_PARTIAL))

               Here we test if the first WSARecv has been filled completely

            */

            if(wsaRecvOverlapped.InternalHigh!=150)
            {
                Trace("Server error: "
                    "First WSARecv(...) "
                    "returned wsaRecvOverlapped.InternalHigh = %d" 
                    ", expected maximum buffer size of 150."
                    "\n", wsaRecvOverlapped.InternalHigh);

                WaitForClientThreadToFinish(hThreadClient);                

                CloseThreadHandle(hThreadClient);

                CloseEventHandle(hReadEvent);

                 /* Do some cleanup */
                DoWSATestCleanup( testSockets,
                                numSockets );

                Fail("");
           }
            /*set the recv buffer to the second half of myBuffer */
            wsaBuf.buf = myBuffer+150;
            wsaBuf.len = 150;
        }
        else /* i == 1 */
        {
           /* on the second wsarecv, it should have read the remaining data to 
              be read on the overlapped result.
           */            
            if(wsaRecvOverlapped.InternalHigh!=105)
            {
                Trace("Server error: "
                    "Second WSARecv(...) "
                    "returned wsaRecvOverlapped.InternalHigh = %d" 
                    ", expected maximum buffer size of 105."
                    "\n", wsaRecvOverlapped.InternalHigh);

                WaitForClientThreadToFinish(hThreadClient);                

                CloseThreadHandle(hThreadClient);

                CloseEventHandle(hReadEvent);

                 /* Do some cleanup */
                DoWSATestCleanup( testSockets,
                                numSockets );

                Fail("");
           }           
        }       
    } /* end of the for loop */

    if(!WaitForClientThreadToFinish(hThreadClient))
    {
        CloseThreadHandle(hThreadClient);

        CloseEventHandle(hReadEvent);

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }

    if(!CloseThreadHandle(hThreadClient)||
       !CloseEventHandle(hReadEvent))
    {
        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );
        Fail("");
    }

    /* test the data received if it valid */
    for(i=0;i<255;i++)
    {
        if(myBuffer[i]!=i)
        {
           Trace("Server error: "
                "WSARecv(...) "
                "returned wsaRecvOverlapped.InternalHigh = %d" 
                ", expected maximum buffer size of 105."
                "\n", wsaRecvOverlapped.InternalHigh);

                /* Do some cleanup */
            DoWSATestCleanup( testSockets,
                            numSockets );

            Fail("");           
         }
    }
 
    /* Do some cleanup */
    DoWSATestCleanup( testSockets,
                      numSockets );


    PAL_Terminate();
    return PASS;
}
Example #5
0
/* DWORD  PALAPI Thread_Client(LPVOID lpParam)  
   This is a client thread started by the main process.
   It simulate a client connecting to a remote server.   
*/
void  PALAPI Thread_Client(LPVOID lpParam)
{     
    int     i;
    int     err;
    struct  sockaddr_in mySockaddr;    

    /* Sockets descriptor */
    const int numSockets = 1;    /* number of sockets used in this test */

    SOCKET testSockets[1];    
    
    /* Variables for WSASend */
    WSABUF wsaSendBuf;
    DWORD  dwNbrOfByteSent;
    DWORD  dwNbrOfBuf  = 1;
    DWORD  dwSendFlags = 0;
    
    unsigned char   sendBuffer[255];    

    WSAOVERLAPPED wsaOverlapped;

    /* variable for iocltsocket */
    u_long argp;
    DWORD   waitResult;

    /* Variables needed for select */
    struct timeval waitTime;
    fd_set writeFds;    
    int    socketFds;    

    HANDLE  hWriteEvent;    

    threadExitCode=THREAD_UNDEFINED;        
    
    /* Sockets initialization to INVALID_SOCKET */
    for( i = 0; i < numSockets; i++ )
    {
        testSockets[i] = INVALID_SOCKET;
    }
    /* create an overlapped stream socket in AF_INET domain */
    testSockets[0] = WSASocketA( AF_INET, 
                                 SOCK_STREAM, 
                                 IPPROTO_TCP,
                                 NULL, 
                                 0, 
                                 WSA_FLAG_OVERLAPPED ); 


    if( testSockets[0] == INVALID_SOCKET )

    {
        Trace("Client error: Unexpected failure: "
              "WSASocketA"
              "(AF_INET SOCK_STREAM IPPROTO_TCP NULL 0 WSA_FLAG_OVERLAPPED) "
              " returned %d\n",
              GetLastError());

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }

    /* enable non blocking socket */
    argp=1;
    err = ioctlsocket(testSockets[0], FIONBIO, (u_long FAR *)&argp);

    if (err==SOCKET_ERROR )
    {
        Trace("ERROR: Unexpected failure: "
              "ioctlsocket(.. FIONBIO ..) "
              "returned %d\n",
              GetLastError() );

        /* Do some cleanup */
        CloseSocket( testSockets, numSockets );
       
        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }
    
    /* prepare the sockaddr_in structure */
    mySockaddr.sin_family           = AF_INET;
    mySockaddr.sin_port             = getRotorTestPort();
    mySockaddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");

    memset( &(mySockaddr.sin_zero), 0, 8);

    /* connect to a server */
    err = connect( testSockets[0], 
                   (struct sockaddr *)&mySockaddr,
                   sizeof(struct sockaddr));

    if( err == SOCKET_ERROR )
    {        
        err = GetLastError();
        if ( err != WSAEWOULDBLOCK )
        {
            Trace("ERROR: Unexpected failure: "
              "connect() socket with local server "
              "returned %d, expected WSAEWOULDBLOCK\n",
              GetLastError());

            /* Do some cleanup */
            CloseSocket( testSockets, numSockets );

            threadExitCode=THREAD_FAIL;

            ExitThread(0);
        }     
        
    }

    /* set the server waiting time as 10 seconds */
    waitTime.tv_sec = 10L;
    waitTime.tv_usec = 0L;

    /* initialize the except socket set  */
    FD_ZERO( &writeFds );

    /* add socket to readable socket set */
    FD_SET( testSockets[0], 
            &writeFds );

    /* monitor the readable socket set to determine the
       completion of the connection request.
    */
    socketFds = select( 0,                        
                        NULL,
                        &writeFds,
                        NULL,
                        &waitTime);

    if( socketFds == SOCKET_ERROR )
    {
        Trace("ERROR: Unexpected failure "
              "with select\n");

        /* Do some cleanup */
        CloseSocket( testSockets, numSockets );
        
        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }

    if( socketFds == 0 )
    {
        Trace("ERROR: Unexpected select "
              "timed out\n");

        /* Do some cleanup */
        CloseSocket( testSockets, numSockets );
        
        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }   
   
    /* create events */
    hWriteEvent = CreateEvent( NULL, /* no security   */
                             FALSE,    /* reset type    */
                             FALSE,    /* initial state */
                             NULL );   /* object name   */
            
    if( hWriteEvent == NULL )
    {
        Trace("Client error: Unexpected failure: "
              "CreateEvent() "
              "returned %d\n",
              GetLastError());

        /* Do some cleanup */
        CloseSocket( testSockets, numSockets );

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }   
    
    memcpy(sendBuffer, srcString, strlen(srcString));
    /* Set the WSABUF structure */
    wsaSendBuf.len = 255;        
    wsaSendBuf.buf = sendBuffer;
    
    /* Initialize the WSAOVERLAPPED to 0 */
    memset(&wsaOverlapped, 0, sizeof(WSAOVERLAPPED));  
    wsaOverlapped.hEvent = hWriteEvent;

    /* Send some data */
    err = WSASendTo( testSockets[0],
                &wsaSendBuf,
                dwNbrOfBuf,
                &dwNbrOfByteSent,
                dwSendFlags,
                (struct sockaddr*)NULL, /* ignored in TCP */
                (int)NULL, /* ignored in TCP */
                &wsaOverlapped,
                0 );


    if(err == SOCKET_ERROR )
    {   
        /* Handle the overlapped operation */
        if(GetLastError()!=WSA_IO_PENDING)
        {
            Trace("Client error: Unexpected failure: "
                "WSASend() "
                "returned %d\n",
                GetLastError());
                    
            CloseEventHandle(hWriteEvent);

            /* Do some cleanup */
            CloseSocket( testSockets, numSockets );

            threadExitCode=THREAD_FAIL;

            ExitThread(0);
        }

        /* Wait 10 seconds for hWriteEvent to be signaled 
        for pending operation
        */
        waitResult = WaitForSingleObject( hWriteEvent, 
                                            10000 );            

        if (waitResult!=WAIT_OBJECT_0)
        {  
            Trace("Client Error: Unexpected failure: "
                "WaitForSingleObject has timed out \n");

            CloseEventHandle(hWriteEvent);
    
            /* Do some cleanup */
            CloseSocket( testSockets, numSockets );

            threadExitCode=THREAD_FAIL;
            ExitThread(0);
        }        
    }
    
    /* Verify that the number of bytes sent are the number of byte
        specified in the wsaBuf structure 
    */
    if(wsaSendBuf.len!=wsaOverlapped.InternalHigh)
    {            
        Trace("Server error: Array out of bound "
            "while writing buffer received in myData.\n");

        CloseEventHandle(hWriteEvent);

        /* Do some cleanup */
        CloseSocket( testSockets, numSockets );

        threadExitCode=THREAD_FAIL;
        ExitThread(0);
    }

    /* close the handle to hWriteEvent */
    if(!CloseEventHandle(hWriteEvent)||
       !CloseSocket( testSockets, numSockets ))
    {
        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }
        
    threadExitCode=THREAD_SUCCESS;

    ExitThread(0);    
} 
Example #6
0
/**
 * main
 * 
 * executable entry point
 * 
 * The main act as a the server. It will create a thread of the client
 * and signal to the thread when it is ready to recv data.
 * Once the client receive the signal, it start sending data.
 * 
 * The server will not stop until the thread it created has exited.
 * For evey return path, error or not, the server will wait for
 * the client to finish its execution. This is to make sure that all
 * resource are being freed and proper error are logged.
 *
 */
INT __cdecl main(INT argc, CHAR **argv)
{
    int     i;
    int     err;    
    struct  sockaddr_in mySockaddr;
    WSADATA wsaData;
    HANDLE  hReadEvent;
    DWORD   waitResult;

    /* Thread variable */
    HANDLE hThreadClient;
    DWORD dwThreadClient;     
    DWORD dwClientParam[2];

    HANDLE hThreadEvent; 
    int bClientStarted=0;

    /* Sockets descriptor */
    const int numSockets = 1;    /* number of sockets used in this test */

    /* variable for iocltsocket */
    u_long argp;

    SOCKET testSockets[1];

     /* Variables needed for setsockopt */
    BOOL bReuseAddr = TRUE;  

    /* Variables needed for WSARecv */
    WSABUF        wsaBuf;
    DWORD         dwNbrOfBuf  = 1;
    DWORD         dwNbrOfByteSent;
    DWORD         dwRecvFlags = 0;
    WSAOVERLAPPED wsaRecvOverlapped;
    
    /* Variable used to store transmitted data */
    unsigned char myBuffer[255];
    unsigned char myData[500][255];
    unsigned char* pMyData;
    
    int bufferCounter;
    /* Socket DLL version */
    const WORD wVersionRequested = MAKEWORD(2,2);

    /* Sockets initialization to INVALID_SOCKET */
    for( i = 0; i < numSockets; i++ )
    {
        testSockets[i] = INVALID_SOCKET;
    }

    /* PAL initialization */
    if( PAL_Initialize(argc, argv) != 0 )
    {
        return FAIL;
    }


    /* Initialize to use winsock2.dll */
    err = WSAStartup( wVersionRequested,
                      &wsaData);

    if(err != 0)
    {
        Fail( "Server error: Unexpected failure: "
              "WSAStartup(%d) "
              "returned %d\n",
              wVersionRequested, 
              GetLastError() );
    }

    /* Confirm that the WinSock DLL supports 2.2.
       Note that if the DLL supports versions greater    
       than 2.2 in addition to 2.2, it will still return
       2.2 in wVersion since that is the version we      
       requested.                                        
    */
    if ( wsaData.wVersion != wVersionRequested ) 
    {
        Trace("Server error: Unexpected failure "
              "to find a usable version of WinSock DLL\n");

        /* Do some cleanup */
        DoWSATestCleanup( 0, 0);

        Fail("");
    }

    /* create an overlapped stream socket in AF_INET domain */

    testSockets[0] = WSASocketA( AF_INET, 
                                 SOCK_DGRAM,
                                 IPPROTO_UDP,
                                 NULL, 
                                 0, 
                                 WSA_FLAG_OVERLAPPED );


    if( testSockets[0] == INVALID_SOCKET )

    {
        Trace("Server error: Unexpected failure: "
              "WSASocketA"
              "(AF_INET,SOCK_DGRAM,IPPROTO_UDP,NULL,0,WSA_FLAG_OVERLAPPED)) "
              " returned %d\n",
              GetLastError());

        /* Do some cleanup */
        DoWSATestCleanup( 0, 0);

        Fail("");
    }

    /* Allows the socket to be bound to an address that is already in use. */
    err = setsockopt( testSockets[0],
                      SOL_SOCKET,
                      SO_REUSEADDR,
                      (const char *)&bReuseAddr,
                      sizeof( BOOL ) );

    if( err == SOCKET_ERROR )
    {
        Trace("Server error: Unexpected failure: "
              "setsockopt(.., SOL_SOCKET,SO_REUSEADDR, ..) "
              "returned %d\n",
              GetLastError() );

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }

    /* enable non blocking socket */
    argp=1;
    err = ioctlsocket(testSockets[0], FIONBIO, (u_long FAR *)&argp);

    if (err==SOCKET_ERROR )
    {
        Trace("ERROR: Unexpected failure: "
              "ioctlsocket(.., FIONBIO, ..) "
              "returned %d\n",
              GetLastError() );

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );
        
        Fail("");
    }

    /* prepare the sockaddr structure */

    mySockaddr.sin_family           = AF_INET;
    mySockaddr.sin_port             = getRotorTestPort();
    mySockaddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");

    memset( &(mySockaddr.sin_zero), 0, 8);

    /* bind local address to a socket */
    err = bind( testSockets[0],
                (struct sockaddr *)&mySockaddr,
                sizeof(struct sockaddr) );


    if( err == SOCKET_ERROR )
    {
        Trace("Server error: Unexpected failure: "
              "bind() socket with local address "
              "returned %d\n",
              GetLastError() );

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }
    
    /* Create an Event with initial owner. */
    hThreadEvent = (HANDLE)CreateEvent( NULL,
        TRUE,                /* reset type */
        FALSE,                /* initially not signaled */
        (LPCSTR)"EventClientServer");  /* name of Event */

    if (hThreadEvent == NULL) 
    {   
        /* Check for error. */
        Trace( "Server Error: Unexpected failure: "
              "CreateEvent() "
              "returned NULL\n");   

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }

    /* create an event */
    hReadEvent = CreateEvent( NULL, /* no security   */
                             FALSE,   /* reset type    */
                             FALSE,   /* initial state */
                             NULL );  /* object name   */
            
    if( hReadEvent == NULL )
    {   
        Trace("Server error: Unexpected failure: "
              "CreateEvent() "
              "returned %d\n",
              GetLastError());

        CloseEventHandle(hThreadEvent);

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
        
    }    
    

    /* create a client thread */

    hThreadClient = 
        CreateThread( 
                NULL,                        /* no security attributes */
                0,                           /* use default stack size */
                (LPTHREAD_START_ROUTINE)Thread_Client,/* thread function    */
                (LPVOID)&dwClientParam,      /* argument to thread function */
                0,                           /* use default creation flags  */
                &dwThreadClient);            /* returns the thread identifier*/

    if(hThreadClient==NULL)
    {
        Trace( "Server Error: Unexpected failure: "
              "CreateThread() "
              "returned NULL\n");

        CloseEventHandle(hThreadEvent);

        CloseEventHandle(hReadEvent);        

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail( "");
    }
    
    bufferCounter = 0;
    pMyData = (unsigned char*)myData;

    /* This loop call WSARecv 500 times to stress tests UDP data exchange
       over connectionless socket.
       Data received are copied in an array and verified after the all receive
       operation are done.
    */
    for(i=0;i<500;i++)
    {   
        /* reset the buffer used by WSARecv */
        memset(myBuffer, 0, 255); 

        /* Initialize the WSAOVERLAPPED to 0 */
        memset(&wsaRecvOverlapped, 0, sizeof(WSAOVERLAPPED));

        /* Specify which event to signal when data is arrived*/
        wsaRecvOverlapped.hEvent = hReadEvent; 

        /* Initialize the WSABUF structure */
        wsaBuf.buf = myBuffer;
        wsaBuf.len = 255;

        /* Prepare to receive data */
        err = WSARecv( testSockets[0],
                       &wsaBuf,
                       dwNbrOfBuf,
                       &dwNbrOfByteSent,
                       &dwRecvFlags,
                       &wsaRecvOverlapped,
                       0 );

        if( err == SOCKET_ERROR )
        {                    
            err = GetLastError();
            /* Only WSA_IO_PENDING is expected */
            if(err!=WSA_IO_PENDING)
            {
                Trace("Server error: WSARecv()"
                      "returned %d, expected WSA_IO_PENDING\n",
                      err );

                WaitForClientThreadToFinish(hThreadClient);

                CloseThreadHandle(hThreadClient);
                
                CloseEventHandle(hThreadEvent);
                
                CloseEventHandle(hReadEvent);
                
                /* Do some cleanup */
                DoWSATestCleanup( testSockets,
                                  numSockets );
        
                Fail("");
            }
        }
        else    /* WSARecv returned immediately */
        {
            /* It can happen in non-blocking mode 
               operation can continue normaly
            */

            if (dwNbrOfByteSent==0)
            {
                Trace("Server error: WSARecv()"
                      "returned dwNbrOfByteSent=0, expected 255.\n");

                WaitForClientThreadToFinish(hThreadClient);

                CloseThreadHandle(hThreadClient);
                
                CloseEventHandle(hThreadEvent);
                
                CloseEventHandle(hReadEvent);
                
                /* Do some cleanup */
                DoWSATestCleanup( testSockets,
                                  numSockets );
        
                Fail("");
            }

            /* Reset event */
            ResetEvent(hReadEvent);
        }            

        /* verify if it needs to start the client thread */
        if(!bClientStarted)
        {
            if(SetEvent(hThreadEvent)==0)
            {
                Trace("Server error: Unexpected failure: "
                        "SetEvent has not set hThreadEvent as expected"
                        "GetLastError returned = %d.\n",GetLastError());

                WaitForClientThreadToFinish(hThreadClient);

                CloseThreadHandle(hThreadClient);

                CloseEventHandle(hThreadEvent);
                
                CloseEventHandle(hReadEvent);                

                /* Do some cleanup */
                DoWSATestCleanup( testSockets,
                                    numSockets );

                Fail("");
            }
            bClientStarted=1;
        }

        if(err==WSA_IO_PENDING)
        {
            /* wait for data to be read on the receive buffer */
            waitResult = WaitForSingleObject( hReadEvent,
                                            10000 );
            
            if (waitResult!=WAIT_OBJECT_0)
            {   
                Trace("Server error: Unexpected failure: "
                    "WaitForSingleObject has timed out \n");
                
                WaitForClientThreadToFinish(hThreadClient);

                CloseThreadHandle(hThreadClient);

                CloseEventHandle(hThreadEvent);
                
                CloseEventHandle(hReadEvent);
                
        
                /* Do some cleanup */
                DoWSATestCleanup( testSockets,
                                numSockets );

                Fail("");
            }
        }        
        
        /* Verify that the buffer received is not bigger than the 
           the maximum specified in wsaBuf structure
        */
        if(wsaBuf.len<wsaRecvOverlapped.InternalHigh)
        {            
            Trace("Server error: "
                  "WSARecv(...) "
                  "returned wsaRecvOverlapped with InternalHigh of %d" 
                  ", expected value equal ot lower to %d\n",
                  wsaRecvOverlapped.InternalHigh, wsaBuf.len);

            WaitForClientThreadToFinish(hThreadClient);

            CloseThreadHandle(hThreadClient);

            CloseEventHandle(hThreadEvent);
            
            CloseEventHandle(hReadEvent);            
            
            /* Do some cleanup */
            DoWSATestCleanup( testSockets,
                              numSockets );
    
            Fail("");
        }        

        
        
        /* test if data can be copied to the current position in the 
           receiving data array. */
        if( pMyData+wsaRecvOverlapped.InternalHigh <
            &(myData[500][255]) )
        {
            /* copy buffer to data array */
            memcpy(pMyData,wsaBuf.buf,wsaRecvOverlapped.InternalHigh);

            /* increment the position where we can write data on the array*/
            pMyData+=wsaRecvOverlapped.InternalHigh;
        }
        else
        {
            /* Else the data received exceed buffer capacity */
            Trace("Server error: Unexpected, data received exceed "
                  "buffer capacity.\n");
            
            WaitForClientThreadToFinish(hThreadClient);

            CloseThreadHandle(hThreadClient);

            CloseEventHandle(hThreadEvent);
            
            CloseEventHandle(hReadEvent);

             /* Do some cleanup */
            DoWSATestCleanup( testSockets,
                              numSockets );

            Fail("");
        }
        
        /* Increment bufferCounter to keep track of the number 
           of byte received */
        bufferCounter += wsaRecvOverlapped.InternalHigh;        
    }

    if(!WaitForClientThreadToFinish(hThreadClient))
    {
        /* Error waiting for the client thread */

        /* Error message generated in function */

        CloseThreadHandle(hThreadClient);
        
        CloseEventHandle(hThreadEvent);
        
        CloseEventHandle(hReadEvent);

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }

    if(!CloseEventHandle(hThreadEvent)||
       !CloseThreadHandle(hThreadClient)||
       !CloseEventHandle(hReadEvent))
    {
        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );
        Fail("");
    }

    /* Expected number of bytes received is 127500 */
    if(bufferCounter!=127500)
    {        
        Trace("Server error: Invalid number of byte received from the client");

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");

        
    }

    /* verify that all data in the data array are as expected */
    pMyData=(unsigned char*)myData;
    for(i=0;i<bufferCounter;i++)
    {
        if(pMyData>&(myData[500][255]))
        {
            Trace("Server error: invalid access to array myData\n");                   

            /* Do some cleanup */
            DoWSATestCleanup( testSockets,
                              numSockets );
            Fail("");

        }

        if(*pMyData!=(i%255))
        {
            Trace("Server error: comparing received data at position %d"
                   " in data array",i);

            /* Do some cleanup */
            DoWSATestCleanup( testSockets,
                              numSockets );
            Fail("");
        }
        pMyData++;
    }
 
    /* Do some cleanup */
    DoWSATestCleanup( testSockets,
                      numSockets );

    PAL_Terminate();
    return PASS;
}
Example #7
0
/* DWORD  PALAPI Thread_Client(LPVOID lpParam)  
*  This is a client thread started by the main process.
*  It simulate a client connecting to a remote server.   
*
*  As soon as the client thread is started it calls WaitForSingleObject
*  and wait for the server to be ready to receive data. 
*
*  If the client fail somewhere it will set a global variable accordingly
*  and will call ExitThread. The main thread (server) will then continue 
*  its execution normally and handle the client error.
*
*    
*
*/
void  PALAPI Thread_Client(LPVOID lpParam)
{     
    int     i;
    int     err;
    struct  sockaddr_in mySockaddr;    

    int byteCounter;

    /* Sockets descriptor */
    const int numSockets = 1;    /* number of sockets used in this test */

    SOCKET testSockets[1];

    /* variable for iocltsocket */
    u_long argp;    
    
    /* Variables for WSASend */

    WSABUF wsaSendBuf;
    DWORD  dwNbrOfByteSent;
    DWORD  dwNbrOfBuf  = 1;
    DWORD  dwSendFlags = 0;
    
    unsigned char   sendBuffer[255];
    

    WSAOVERLAPPED wsaOverlapped;

    HANDLE  hWriteEvent;
    DWORD   waitResult;
    
    /* Thread Event handle */
    HANDLE hThreadEvent;

    threadExitCode=THREAD_UNDEFINED;

    /* Create the EventClientServer controled by the server  */     
    hThreadEvent = (HANDLE)CreateEvent( NULL,
        TRUE,                /* ignored */
        FALSE,                /* ignored */
        (LPCSTR)"EventClientServer");  /* name of Event */

    if (hThreadEvent == NULL) 
    {        
        /* Check for error. */
        Trace( "Server Error: Unexpected failure: "
              "CreateEvent() "
              "returned NULL\n");

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }
    
    /* Wait 10 seconds for EventClientServer to be signaled 
       from the server. It will mean that the server is ready
       to receive data or connection.
    */
    waitResult = WaitForSingleObject( hThreadEvent,
                                      10000 );
            
    if (waitResult!=WAIT_OBJECT_0)
    {
        Trace("Client error: Unexpected failure: "
              "WaitForSingleObject has timed out while "
              "waiting for EventClientServer.\n");

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }    
    
    /* Destroy the Event Handle, we don't need it anymore */
    if(!CloseEventHandle(hThreadEvent))
    {       
        /* Trace is done in CloseEventHandle */

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }


    /* Sockets initialization to INVALID_SOCKET */
    for( i = 0; i < numSockets; i++ )
    {
        testSockets[i] = INVALID_SOCKET;
    }


    /* create an overlapped stream socket in AF_INET domain */

    testSockets[0] = WSASocketA( AF_INET, 
                                 SOCK_DGRAM, 
                                 IPPROTO_UDP,
                                 NULL, 
                                 0, 
                                 WSA_FLAG_OVERLAPPED ); 


    if( testSockets[0] == INVALID_SOCKET )

    {
        Trace("Client error: Unexpected failure: "
              "WSASocketA"
              "(AF_INET,SOCK_DGRAM,IPPROTO_UDP,NULL,0,WSA_FLAG_OVERLAPPED)) "
              " returned %d\n",
              GetLastError());        

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }

     /* enable non blocking socket */
    argp=1;
    err = ioctlsocket(testSockets[0], FIONBIO, (u_long FAR *)&argp);

    if (err==SOCKET_ERROR )
    {
        Trace("ERROR: Unexpected failure: "
              "ioctlsocket(.., FIONBIO, ..) "
              "returned %d\n",
              GetLastError() );

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );
        
        Fail("");
    }
    
    /* prepare the sockaddr_in structure */
    mySockaddr.sin_family           = AF_INET;
    mySockaddr.sin_port             = getRotorTestPort();
    mySockaddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");

    memset( &(mySockaddr.sin_zero), 0, 8);

    /* connect to a server */
    err = connect( testSockets[0], 
                   (struct sockaddr *)&mySockaddr,
                   sizeof(struct sockaddr));

    if( err == SOCKET_ERROR )
    {
        Trace("Client error: Unexpected failure: "
              "connect() socket with local server "
              "returned %d\n",
              GetLastError());

        /* Do some cleanup */
        CloseSocket( testSockets, numSockets );

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }


    /* fill the sent buffer with value */
    for (i=0;i<255;i++)
    {
        sendBuffer[i]= i;
    }

    /* prepare data for the send operation */    

    /* create events */
    hWriteEvent = CreateEvent( NULL, /* no security   */
                             FALSE,    /* reset type    */
                             FALSE,    /* initial state */
                             NULL );   /* object name   */
            
    if( hWriteEvent == NULL )
    {            
        Trace("Client error: Unexpected failure: "
              "CreateEvent() "
              "returned %d\n",
              GetLastError());

        /* Do some cleanup */
        CloseSocket( testSockets, numSockets );

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }    
    
    /* Set the WSABUF structure */
    wsaSendBuf.len = 255;        
    wsaSendBuf.buf = sendBuffer;
    
    byteCounter = 0;

    /*
        That loop will wsasend a 500 buffer of data with UDP datagram to
        the server thread.
    */
    for(i=0;i<500;i++)
    {        
        /* Initialize the WSAOVERLAPPED for every send operation */
        memset(&wsaOverlapped, 0, sizeof(WSAOVERLAPPED));
        wsaOverlapped.hEvent = hWriteEvent;

        /* Send some data */
        err = WSASend( testSockets[0],
                       &(wsaSendBuf),
                       dwNbrOfBuf,
                       &dwNbrOfByteSent,
                       dwSendFlags,
                       &wsaOverlapped,
                       0 );


        if(err == SOCKET_ERROR )
        {
            if(GetLastError()!=WSA_IO_PENDING)
            {
                Trace("Client error: Unexpected failure: "
                      "WSASend() "
                      "returned %d\n",
                      GetLastError());                

                /* Do some cleanup */
                CloseEventHandle(hWriteEvent);

                CloseSocket( testSockets, numSockets );

                threadExitCode=THREAD_FAIL;

                ExitThread(0);
            }

            /* Wait 10 seconds for WriteEvent to be signaled 
               for pending operation
            */
            waitResult = WaitForSingleObject( hWriteEvent, 
                                              10000 );            
 
            if (waitResult!=WAIT_OBJECT_0)
            {   
                Trace("Client Error: Unexpected failure: "
                      "WaitForSingleObject has timed out \n");

                /* Do some cleanup */

                CloseEventHandle(hWriteEvent);                        
                
                CloseSocket( testSockets, numSockets );

                threadExitCode=THREAD_FAIL;

                ExitThread(0);
            }            
        }
        else
        {
            /* WSASend returned immediately */
            if(dwNbrOfByteSent==0)
            {
                Trace("Client error: WSARecv()"
                      "returned dwNbrOfByteSent=0, expected 255.\n");

                /* Do some cleanup */

                CloseEventHandle(hWriteEvent);                        
                
                CloseSocket( testSockets, numSockets );

                threadExitCode=THREAD_FAIL;

                ExitThread(0);
                
            }
            /* Reset event */
            ResetEvent(hWriteEvent);
        }
        
        /* test if number of byte sent is different from 0
           in that case it means that the connection was closed
        */
        if(wsaOverlapped.InternalHigh==0)
        {
            Trace("Client Error: Unexpected failure: "
                  "WSASend overlapped operation sent 0 byte. "
                  "wsaOverlapped.Internal "
                  "= %d\n",wsaOverlapped.InternalHigh);
            
            /* Do some cleanup */
            CloseEventHandle(hWriteEvent);
            
            CloseSocket( testSockets, numSockets );                

            threadExitCode=THREAD_FAIL;

            ExitThread(0);            
        }

        /* keep track of the number of bytes sent */
        byteCounter += wsaOverlapped.InternalHigh;
 
        /* Verify that the number of bytes sent are the number of byte
           specified in the wsaBuf structure 
        */
        if(wsaSendBuf.len!=wsaOverlapped.InternalHigh)
        {   
            Trace("Client WSASend has not send the number of byte requested "
                  "wsaSendBuf.len = %d while "
                  "wsaOverlapped.InternalHigh = % d",
                  wsaSendBuf.len, wsaOverlapped.InternalHigh);

            /* Do some cleanup */
            CloseSocket( testSockets, numSockets );

            CloseEventHandle(hWriteEvent);

            threadExitCode=THREAD_FAIL;

            ExitThread(0);
        }

        /* since it is UDP, it is more safe to wait a bit between 
           each send operation. Otherwise we lose some frame.
        */
        Sleep(10);
    }   
    
    
    if(!CloseEventHandle(hWriteEvent))
    {
        /* Do some cleanup */
        CloseSocket( testSockets, numSockets );

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }
    

    /* Do some cleanup */
    if(!CloseSocket( testSockets, numSockets ))
    {
        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }

    /* Expected number of bytes sent is 127500 */
    if(byteCounter!=127500)
    {
        Trace("Client error: Invalid number of byte sent to the server: %d"
               "\n",byteCounter);

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }    

    threadExitCode=THREAD_SUCCESS;

    ExitThread(0);    
} 
Example #8
0
void CIpSocket::Destroy()
{
	// Let everyone know we're closing
	if ( c_InvalidSocket != m_hSocket )
		OnClose();

	// Ditch the event handle
	CloseEventHandle();

	// Save socket pointer to socket
	t_SOCKET hSocket = m_bFree ? m_hSocket : c_InvalidSocket;

	// Ditch member variable
	m_hSocket = c_InvalidSocket;

	// Invalidate member variables
    m_sConnect.clear();
    m_addrPeer.Destroy();
    m_addrLocal.Destroy();

    m_uConnectState = 0;
    m_uEventState = 0;
    memset( &m_uEventStatus, 0, sizeof( m_uEventStatus ) );

    m_uSocketFamily = 0;
    m_uSocketType = 0;
    m_uSocketProtocol = 0;

    m_uConnectState = 0;

	m_uReads = 0;
	m_uWrites = 0;
	m_uAccepts = 0;
	m_uFlags = 0;
	m_lActivity = 0;

	m_bFree = 1;

	// Ensure valid socket handle
	if ( c_InvalidSocket == hSocket )
		return;

	if ( IsInitialized() )
	{
		// Turn off non-blocking
//		int flags = fcntl( tcPtrToULong( hSocket ), F_GETFL, 0 );
//		fcntl( tcPtrToULong( m_hSocket ), F_SETFL, flags & ~O_NONBLOCK );

		struct linger lopt;
		lopt.l_onoff = 1;
		lopt.l_linger = 60;

		if ( -1 == setsockopt( tcPtrToULong( hSocket ), SOL_SOCKET, SO_LINGER, &lopt, sizeof( lopt ) ) )
			m_uLastError = errno;

		// Shutdown the socket
//		if ( -1 == shutdown( tcPtrToULong( hSocket ), SHUT_RDWR ) )
//		{	m_uLastError = errno;
//			if ( ENOTCONN != errno )
//				;
//		} // end if

		// Close the socket
		if ( -1 == close( tcPtrToULong( hSocket ) ) )
			m_uLastError = errno;

	} // end if

}
Example #9
0
/**
 * main
 *
 * executable entry point
 */
INT __cdecl main(INT argc, CHAR **argv)
{
    int     i;
    int     err;
    int     addrlen = sizeof(struct sockaddr);
    struct  sockaddr_in mySockaddr;
    WSADATA wsaData;
    HANDLE  hReadEvent;
    DWORD   waitResult;

    /* Thread variable */
    HANDLE hThreadClient;
    DWORD dwThreadClient;
    DWORD dwClientParam[2];

    /* Sockets descriptor */
    const int numSockets = 2;    /* number of sockets used in this test */

    SOCKET testSockets[2];

    /* Variables needed for setsockopt */
    BOOL bReuseAddr = TRUE;


    /* Variables needed for select */
    struct timeval waitTime;
    fd_set readFds;
    int    socketFds;

    /* Variables needed for WSARecv */
    WSABUF        wsaBuf;
    DWORD         dwNbrOfBuf  = 1;
    DWORD         dwNbrOfByteSent;
    DWORD         dwRecvFlags = 0;
    WSAOVERLAPPED wsaRecvOverlapped;

    /* Variable used to store transmitted data */
    unsigned char myBuffer[255];
    unsigned char myData[500][255];
    unsigned char* pMyData;

    int bufferCounter;

    /* Socket DLL version */
    const WORD wVersionRequested = MAKEWORD(2,2);

    /* Sockets initialization to INVALID_SOCKET */
    for( i = 0; i < numSockets; i++ )
    {
        testSockets[i] = INVALID_SOCKET;
    }

    /* PAL initialization */
    if( PAL_Initialize(argc, argv) != 0 )
    {
        return FAIL;
    }

    /* Initialize to use winsock2.dll */
    err = WSAStartup( wVersionRequested,
                      &wsaData);

    if(err != 0)
    {
        Fail( "Server error: Unexpected failure: "
              "WSAStartup(%i) "
              "returned %d\n",
              wVersionRequested,
              GetLastError() );
    }

    /* Confirm that the WinSock DLL supports 2.2.
       Note that if the DLL supports versions greater
       than 2.2 in addition to 2.2, it will still return
       2.2 in wVersion since that is the version we
       requested.
    */
    if ( wsaData.wVersion != wVersionRequested )
    {
        Trace("Server error: Unexpected failure "
              "to find a usable version of WinSock DLL\n");

        /* Do some cleanup */
        DoWSATestCleanup( 0, 0);

        Fail("");
    }

    /* create an overlapped stream socket in AF_INET domain */

    testSockets[0] = WSASocketA( AF_INET,
                                 SOCK_STREAM,
                                 IPPROTO_TCP,
                                 NULL,
                                 0,
                                 WSA_FLAG_OVERLAPPED );


    if( testSockets[0] == INVALID_SOCKET )
    {
        Trace("Server error: Unexpected failure: "
              "WSASocketA"
              "(AF_INET,SOCK_STREAM,IPPROTO_TCP,NULL,0,WSA_FLAG_OVERLAPPED)) "
              " returned %d\n",
              GetLastError());

        /* Do some cleanup */
        DoWSATestCleanup( 0, 0);

        Fail("");
    }

    /* Allows the socket to be bound to an address that is already in use. */
    err = setsockopt( testSockets[0],
                      SOL_SOCKET,
                      SO_REUSEADDR,
                      (const char *)&bReuseAddr,
                      sizeof( BOOL ) );

    if( err == SOCKET_ERROR )
    {
        Trace("Server error: Unexpected failure: "
              "setsockopt(.., SOL_SOCKET,SO_REUSEADDR, ..) "
              "returned %d\n",
              GetLastError() );

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }

    /* prepare the sockaddr structure */

    mySockaddr.sin_family           = AF_INET;
    mySockaddr.sin_port             = getRotorTestPort();
    mySockaddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");

    memset( &(mySockaddr.sin_zero), 0, 8);

    /* bind local address to a socket */
    err = bind( testSockets[0],
                (struct sockaddr *)&mySockaddr,
                sizeof(struct sockaddr) );


    if( err == SOCKET_ERROR )
    {
        Trace("ERROR: Unexpected failure: "
              "bind() socket with local address "
              "returned %d\n",
              GetLastError() );

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }

    /* listen to the socket */
    err = listen( testSockets[0],
                  listenBacklog );

    if( err == SOCKET_ERROR )
    {
        Trace("ERROR: Unexpected failure: "
              "listen() to sockets "
              "returned %d\n",
              GetLastError() );

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }

    /* create a client thread */

    hThreadClient =
        CreateThread(
            NULL,                        /* no security attributes */
            0,                           /* use default stack size */
            (LPTHREAD_START_ROUTINE)Thread_Client,/* thread function    */
            (LPVOID)&dwClientParam,      /* argument to thread function */
            0,                           /* use default creation flags  */
            &dwThreadClient);            /* returns the thread identifier*/

    if(hThreadClient==NULL)
    {
        Trace( "Server Error: Unexpected failure: "
               "CreateThread() "
               "returned NULL\n");

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }

    /* set the server waiting time as 10 seconds */
    waitTime.tv_sec = 10L;
    waitTime.tv_usec = 0L;

    /* initialize the except socket set  */
    FD_ZERO( &readFds );

    /* add socket to readable socket set */
    FD_SET( testSockets[0],
            &readFds );

    /* monitor the readable socket set   */
    socketFds = select( 0,
                        &readFds,
                        NULL,
                        NULL,
                        &waitTime);

    if( socketFds == SOCKET_ERROR )
    {
        Trace("ERROR: Unexpected failure "
              "with select\n");

        WaitForClientThreadToFinish(hThreadClient);

        CloseThreadHandle(hThreadClient);

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }

    if( socketFds == 0 )
    {
        Trace("ERROR: Unexpected select "
              "timed out\n");

        WaitForClientThreadToFinish(hThreadClient);

        CloseThreadHandle(hThreadClient);

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }

    /* accept connection */
    testSockets[1] = accept( testSockets[0],
                             (struct sockaddr *)&mySockaddr,
                             &addrlen );

    if( testSockets[1] == INVALID_SOCKET )
    {
        Trace("ERROR: Unexpected failure: "
              "accept() connection on socket "
              "returned %d\n",
              GetLastError());

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }

    /* create an event */
    hReadEvent = CreateEvent( NULL, /* no security   */
                              FALSE,   /* reset type    */
                              FALSE,   /* initial state */
                              NULL );  /* object name   */

    if( hReadEvent == NULL )
    {
        Trace("Server error: Unexpected failure: "
              "CreateEvent() "
              "returned %d\n",
              GetLastError());

        WaitForClientThreadToFinish(hThreadClient);


        CloseThreadHandle(hThreadClient);

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");

    }

    /* Initialize the WSABUF structure */
    wsaBuf.buf = myBuffer;
    wsaBuf.len = 255;

    bufferCounter = 0;
    pMyData = (unsigned char*)myData;

    /* loop that receive data from client
       It received 400 buffer then proceed to a shutdown
       on the receiving socket.
    */
    for(i=0; i<400; i++)
    {
        /* Initialize the WSAOVERLAPPED to 0 */
        memset(&wsaRecvOverlapped, 0, sizeof(WSAOVERLAPPED));
        /* Specify which event to signal when data is arrived*/
        wsaRecvOverlapped.hEvent = hReadEvent;

        memset(myBuffer, 0, 255);

        /* Prepare to receive data */
        err = WSARecv( testSockets[1],
                       &wsaBuf,
                       dwNbrOfBuf,
                       &dwNbrOfByteSent,
                       &dwRecvFlags,
                       &wsaRecvOverlapped,
                       0 );

        if( err != SOCKET_ERROR )
        {
            if(dwNbrOfByteSent==0)
            {
                Trace("Server error: WSARecv() "
                      "received %d, expected 0.\n",
                      dwNbrOfByteSent);

                WaitForClientThreadToFinish(hThreadClient);

                CloseThreadHandle(hThreadClient);

                CloseEventHandle(hReadEvent);

                /* Do some cleanup */
                DoWSATestCleanup( testSockets,
                                  numSockets );

                Fail("");
            }
            /* reset the event */
            ResetEvent(hReadEvent);
        }
        else if(GetLastError()!=WSA_IO_PENDING)
        {
            Trace("Server error: WSARecv() "
                  "returned %d, expected WSA_IO_PENDING\n",
                  GetLastError() );

            WaitForClientThreadToFinish(hThreadClient);

            CloseThreadHandle(hThreadClient);

            CloseEventHandle(hReadEvent);

            /* Do some cleanup */
            DoWSATestCleanup( testSockets,
                              numSockets );

            Fail("");
        }
        else
        {
            waitResult = WaitForSingleObject( hReadEvent,
                                              10000 );

            if (waitResult!=WAIT_OBJECT_0)
            {
                Trace("Server error: Unexpected failure: "
                      "WaitForSingleObject has timed out \n");

                WaitForClientThreadToFinish(hThreadClient);

                CloseThreadHandle(hThreadClient);

                CloseEventHandle(hReadEvent);

                /* Do some cleanup */
                DoWSATestCleanup( testSockets,
                                  numSockets );

                Fail("");
            }
        }

        /* test if data can be copied to the current position in the
          receiving data array. */
        if( pMyData+wsaRecvOverlapped.InternalHigh <&(myData[500][255]) )
        {
            /* copy buffer to data array */
            memcpy(pMyData,wsaBuf.buf,wsaRecvOverlapped.InternalHigh);

            /* increment the position where we can write data on the array*/
            pMyData+=wsaRecvOverlapped.InternalHigh;
        }
        else
        {
            /* Else the data received exceed buffer capacity */
            Trace("Unexpected, data received exceed buffer capacity.\n");
            WaitForClientThreadToFinish(hThreadClient);

            CloseThreadHandle(hThreadClient);

            CloseEventHandle(hReadEvent);

            /* Do some cleanup */
            DoWSATestCleanup( testSockets,
                              numSockets );

            Fail("");
        }
    }


    if(!WaitForClientThreadToFinish(hThreadClient))
    {

        CloseThreadHandle(hThreadClient);

        CloseEventHandle(hReadEvent);

        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );

        Fail("");
    }

    if(!CloseThreadHandle(hThreadClient)||
            !CloseEventHandle(hReadEvent))
    {
        /* Do some cleanup */
        DoWSATestCleanup( testSockets,
                          numSockets );
        Fail("");
    }

    /* Do some cleanup */
    DoWSATestCleanup( testSockets,
                      numSockets );

    PAL_Terminate();
    return PASS;
}
Example #10
0
/* DWORD  PALAPI Thread_Client(LPVOID lpParam)
   This is a client thread started by the main process.
   It simulate a client connecting to a remote server.
*/
void  PALAPI Thread_Client(LPVOID lpParam)
{
    unsigned int     i;
    int     err;
    struct  sockaddr_in mySockaddr;

    /* Sockets descriptor */
    const int numSockets = 1;    /* number of sockets used in this test */

    SOCKET testSockets[1];


    /* Variables for WSASend */

    WSABUF wsaSendBuf;
    DWORD  dwNbrOfByteSent;
    DWORD  dwNbrOfBuf  = 1;
    DWORD  dwSendFlags = 0;

    unsigned char sendBuffer[255];

    WSAOVERLAPPED wsaOverlapped;

    int byteCounter;

    HANDLE  hWriteEvent;
    DWORD   waitResult;

    threadExitCode=THREAD_UNDEFINED;

    /* Sockets initialization to INVALID_SOCKET */
    for( i = 0; i < (unsigned int)numSockets; i++ )
    {
        testSockets[i] = INVALID_SOCKET;
    }

    /* create an overlapped stream socket in AF_INET domain */

    testSockets[0] = WSASocketA( AF_INET,
                                 SOCK_STREAM,
                                 IPPROTO_TCP,
                                 NULL,
                                 0,
                                 WSA_FLAG_OVERLAPPED );


    if( testSockets[0] == INVALID_SOCKET )

    {
        Trace("Client error: Unexpected failure: "
              "WSASocketA"
              "(AF_INET,SOCK_STREAM,IPPROTO_TCP,NULL,0,WSA_FLAG_OVERLAPPED) "
              " returned %d\n",
              GetLastError());

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }

    /* prepare the sockaddr_in structure */
    mySockaddr.sin_family           = AF_INET;
    mySockaddr.sin_port             = getRotorTestPort();
    mySockaddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");

    memset( &(mySockaddr.sin_zero), 0, 8);

    /* Wait for server to call accept */
    Sleep(500);

    /* connect to a server */
    err = connect( testSockets[0],
                   (struct sockaddr *)&mySockaddr,
                   sizeof(struct sockaddr));

    if( err == SOCKET_ERROR )
    {
        Trace("Client error: Unexpected failure: "
              "connect() socket with local server "
              "returned %d\n",
              GetLastError());

        /* Do some cleanup */
        CloseSocket( testSockets, numSockets );

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }


    /* create events */
    hWriteEvent = CreateEvent( NULL, /* no security   */
                               FALSE,    /* reset type    */
                               FALSE,    /* initial state */
                               NULL );   /* object name   */

    if( hWriteEvent == NULL )
    {
        Trace("Client error: Unexpected failure: "
              "CreateEvent() "
              "returned %d\n",
              GetLastError());

        CloseEventHandle(hWriteEvent);

        /* Do some cleanup */
        CloseSocket( testSockets, numSockets );

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }

    /* Initialize the WSAOVERLAPPED to 0 */
    memset(&wsaOverlapped, 0, sizeof(WSAOVERLAPPED));
    wsaOverlapped.hEvent = hWriteEvent;

    /* fill the sent buffer with value */
    for (i=0; i<255; i++)
    {
        sendBuffer[i]=i;
    }

    /* Set the WSABUF structure */
    wsaSendBuf.len = 255;
    wsaSendBuf.buf = sendBuffer;
    byteCounter = 0;

    /* This loop is intended to send 500 buffer (of 255 bytes).
       The server that receive will shutdown connection
       at the 400th recv. The Client should handle that close
       connection gracefully and close its allocated resources
    */
    for(i=0; i<500; i++)
    {
        /* Initialize the WSAOVERLAPPED to 0 */
        memset(&wsaOverlapped, 0, sizeof(WSAOVERLAPPED));
        wsaOverlapped.hEvent = hWriteEvent;

        /* Send some data */
        err = WSASendTo( testSockets[0],
                         &wsaSendBuf,
                         dwNbrOfBuf,
                         &dwNbrOfByteSent,
                         dwSendFlags,
                         (struct sockaddr*)NULL, /* ignored in TCP */
                         (int)NULL, /* ignored in TCP */
                         &wsaOverlapped,
                         0 );

        if(err != SOCKET_ERROR )
        {
            /* Program continue normally, reset the write event */
            ResetEvent(hWriteEvent);
        }
        else
        {
            /* The server shutdown its socket after 400 wsarecv, it is
               impossible to have 401 or more successfull send operation */
            if(GetLastError()==WSAECONNABORTED||GetLastError()==WSAESHUTDOWN)
            {
                if (i<400)
                {
                    if(GetLastError()==WSAESHUTDOWN)
                    {
                        Trace("Unexpected WSAESHUTDOWN");
                    }
                    else
                    {
                        Trace("Unexpected WSAECONNABORTED");
                    }

                    CloseEventHandle(hWriteEvent);

                    CloseSocket( testSockets, numSockets );

                    Fail("");
                }
                else
                {
                    /* the program will terminate normally because
                       connection has been closed by the server.
                    */
                    break;
                }
            }

            /* Handle the overlapped operation */
            if(GetLastError()!=WSA_IO_PENDING)
            {

                Trace("Client error: Unexpected failure: "
                      "WSASend() "
                      "returned %d\n",
                      GetLastError());


                CloseEventHandle(hWriteEvent);

                /* Do some cleanup */
                CloseSocket( testSockets, numSockets );

                threadExitCode=THREAD_FAIL;

                ExitThread(0);
            }

            /* Wait 10 seconds for WriteEvent to be signaled
               by the pending operation
            */
            waitResult = WaitForSingleObject( hWriteEvent,
                                              10000 );

            if (waitResult!=WAIT_OBJECT_0)
            {
                Trace("ERROR: Unexpected failure: "
                      "WaitForSingleObject has timed out \n");

                CloseEventHandle(hWriteEvent);

                /* Do some cleanup */
                CloseSocket( testSockets, numSockets );

                threadExitCode=THREAD_FAIL;

                ExitThread(0);
            }
        }

        /* keep track of the number of bytes sent */
        byteCounter += wsaOverlapped.InternalHigh;

        /* if wsaOverlapped.InternalHigh is 0, it means
           that connection has been closed
        */
        if(wsaOverlapped.InternalHigh==0)
        {
            /* The server shutdown the receiving socket
               after 400 successfull receive.
            */
            if (i<400)
            {
                Trace("Unexpected wsaOverlapped.InternalHigh = 0 "
                      "at WSASend attempt #%d", i);


                CloseEventHandle(hWriteEvent);

                /* Do some cleanup */
                CloseSocket( testSockets, numSockets );

                threadExitCode=THREAD_FAIL;

                ExitThread(0);
            }
        }
    } /* end of loop */



    if(!CloseEventHandle(hWriteEvent)||
            !CloseSocket( testSockets, numSockets ))
    {
        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }

    threadExitCode=THREAD_SUCCESS;

    ExitThread(0);
}
Example #11
0
/* DWORD  PALAPI Thread_Client(LPVOID lpParam)  
   This is a client thread started by the main process.
   It simulate a client connecting to a remote server.   
*/
void  PALAPI Thread_Client(LPVOID lpParam)
{     
    int     i;
    int     err;
    struct  sockaddr_in mySockaddr;    

    /* Sockets descriptor */
    const int numSockets = 1;    /* number of sockets used in this test */

    SOCKET testSockets[1];
    
    /* Variables for WSASend */

    WSABUF wsaSendBuf;
    DWORD  dwNbrOfByteSent;
    DWORD  dwNbrOfBuf  = 1;
    DWORD  dwSendFlags = 0;
    
    unsigned char   sendBuffer[255];

    int byteCounter;

    WSAOVERLAPPED wsaOverlapped;

    /* variable for iocltsocket */
    u_long argp;

    /* Variables needed for select */
    struct timeval waitTime;
    fd_set writeFds;    
    int    socketFds;        

    HANDLE  hWriteEvent;
    DWORD   waitResult;

    threadExitCode=THREAD_UNDEFINED;

    /* Sockets initialization to INVALID_SOCKET */
    for( i = 0; i < numSockets; i++ )
    {
        testSockets[i] = INVALID_SOCKET;
    }

    /* create an overlapped stream socket in AF_INET domain */

    testSockets[0] = WSASocketA( AF_INET, 
                                 SOCK_STREAM, 
                                 IPPROTO_TCP,
                                 NULL, 
                                 0, 
                                 WSA_FLAG_OVERLAPPED ); 


    if( testSockets[0] == INVALID_SOCKET )

    {
        Trace("Client error: Unexpected failure: "
              "WSASocketA"
              "(AF_INET,SOCK_STREAM,IPPROTO_TCP,NULL,0,WSA_FLAG_OVERLAPPED) "
              " returned %u\n",
              GetLastError());

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }

    /* enable non blocking socket */
    argp=1;
    err = ioctlsocket(testSockets[0], FIONBIO, (u_long FAR *)&argp);

    if (err==SOCKET_ERROR )
    {
        Trace("ERROR: Unexpected failure: "
              "ioctlsocket(.., FIONBIO, ..) "
              "returned %u\n",
              GetLastError() );

        /* Do some cleanup */
        CloseSocket( testSockets, numSockets );
       
        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }
    
    /* prepare the sockaddr_in structure */
    mySockaddr.sin_family           = AF_INET;
    mySockaddr.sin_port             = getRotorTestPort();
    mySockaddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");

    memset( &(mySockaddr.sin_zero), 0, 8);

    /* wait for the server to be prepared */
    Sleep(1000);

    /* connect to a server */
    err = connect( testSockets[0], 
                   (struct sockaddr *)&mySockaddr,
                   sizeof(struct sockaddr));

    if( err == SOCKET_ERROR )    
    {
        err = GetLastError();
        if ( err != WSAEWOULDBLOCK )
        {
            Trace("ERROR: Unexpected failure: "
              "connect() socket with local server "
              "returned %u, expected WSAEWOULDBLOCK\n",
              GetLastError());

            /* Do some cleanup */
            CloseSocket( testSockets, numSockets );
            
            threadExitCode=THREAD_FAIL;

            ExitThread(0);
        }     

          /* set the server waiting time as 10 seconds */
        waitTime.tv_sec = 10L;
        waitTime.tv_usec = 0L;

        /* initialize the except socket set  */
        FD_ZERO( &writeFds );

        /* add socket to readable socket set */
        FD_SET( testSockets[0], 
                &writeFds );

        /* monitor the readable socket set to determine the
        completion of the connection request.
        */
        socketFds = select( 0,                        
                            NULL,
                            &writeFds,
                            NULL,
                            &waitTime);

        if( socketFds == SOCKET_ERROR )
        {
            Trace("ERROR: Unexpected failure "
                "with select\n");

            /* Do some cleanup */
            CloseSocket( testSockets, numSockets );
            
            threadExitCode=THREAD_FAIL;

            ExitThread(0);
        }

        if( socketFds == 0 )
        {
            Trace("ERROR: Unexpected select "
                "timed out\n");

            /* Do some cleanup */
            CloseSocket( testSockets, numSockets );
            
            threadExitCode=THREAD_FAIL;

            ExitThread(0);
        }        
    }  
   
    /* create events */
    hWriteEvent = CreateEvent( NULL, /* no security   */
                             FALSE,    /* reset type    */
                             FALSE,    /* initial state */
                             NULL );   /* object name   */
            
    if( hWriteEvent == NULL )
    {
        Trace("Client error: Unexpected failure: "
              "CreateEvent() "
              "returned %u\n",
              GetLastError());

        /* Do some cleanup */
        CloseSocket( testSockets, numSockets );

        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }   

    /* fill the sent buffer with value */
    for (i=0;i<255;i++)
    {
        sendBuffer[i]= i;
    }

    /* Set the WSABUF structure */
    wsaSendBuf.len = 255;        
    wsaSendBuf.buf = sendBuffer;

    byteCounter = 0;   

    /*  This loop send a 400 buffer to the server.
        It then shutdown the connection.
    */
    for(i=0;i<500;i++)
    {
        /* Initialize the WSAOVERLAPPED to 0 */
        memset(&wsaOverlapped, 0, sizeof(WSAOVERLAPPED));  
        wsaOverlapped.hEvent = hWriteEvent;

        /* Send some data */
        err = WSASendTo( testSockets[0],
                    &wsaSendBuf,
                    dwNbrOfBuf,
                    &dwNbrOfByteSent,
                    dwSendFlags,
                    (struct sockaddr*)NULL, /* ignored in TCP */
                    (int)NULL, /* ignored in TCP */
                    &wsaOverlapped,
                    0 );


        if(err == SOCKET_ERROR )
        {
             /* The server shutdown its socket after 400 wsarecv, it is 
               impossible to have 401 or more successfull send operation */
            err=GetLastError();
            if(err==WSAECONNABORTED
               ||err==WSAESHUTDOWN
               ||err==WSAECONNRESET)
            {
                if (i<400)
                {
                    if(err==WSAESHUTDOWN)
                    {
                        Trace("Unexpected WSAESHUTDOWN at send %d",i);
                    }
                    else if(err==WSAECONNABORTED)
                    {
                        Trace("Unexpected WSAECONNABORTED at send %d",i);
                    }
                    else if(err==WSAECONNRESET)
                    {
                        Trace("Unexpected WSAECONNRESET at send %d",i);
                    }

                    CloseEventHandle(hWriteEvent);

                    /* Do some cleanup */
                    CloseSocket( testSockets, numSockets );

                    threadExitCode=THREAD_FAIL;

                    ExitThread(0);
                }
                else
                {
                    break;
                }
            }

            /* Handle the overlapped operation */
            if(err!=WSA_IO_PENDING)
            {
                Trace("Client error: Unexpected failure: "
                    "WSASend() "
                    "returned %u\n",
                    err);
                     
                CloseEventHandle(hWriteEvent);

                /* Do some cleanup */
                CloseSocket( testSockets, numSockets );

                threadExitCode=THREAD_FAIL;

                ExitThread(0);
            }

            /* Wait 10 seconds for hWriteEvent to be signaled 
            for pending operation
            */
            waitResult = WaitForSingleObject( hWriteEvent, 
                                              10000 );            

            if (waitResult!=WAIT_OBJECT_0)
            {  
                Trace("Client Error: Unexpected failure: "
                    "WaitForSingleObject has timed out \n");

                CloseEventHandle(hWriteEvent);
        
                /* Do some cleanup */
                CloseSocket( testSockets, numSockets );       

                threadExitCode=THREAD_FAIL;
                ExitThread(0);
            }
            
            /* The server shutdown its socket after 400 wsarecv, it is 
               impossible to have 401 or more successfull send operation */
            if(wsaOverlapped.Internal==WSAECONNABORTED||
               wsaOverlapped.Internal==WSAESHUTDOWN||
               wsaOverlapped.Internal==WSAECONNRESET)
            {
                if (i<400)
                {
                    if(err==WSAESHUTDOWN)
                    {
                        Trace("Unexpected WSAESHUTDOWN at send %d",i);
                    }
                    else if(err==WSAECONNABORTED)
                    {
                        Trace("Unexpected WSAECONNABORTED at send %d",i);
                    }
                    else if(err==WSAECONNRESET)
                    {
                        Trace("Unexpected WSAECONNRESET at send %d",i);
                    }

                    CloseEventHandle(hWriteEvent);

                    /* Do some cleanup */
                    CloseSocket( testSockets, numSockets );

                    threadExitCode=THREAD_FAIL;

                    ExitThread(0);
                }
                else
                {
                    break;
                }
            }

        }
        else
        {
            /* Reset Event */
            ResetEvent(hWriteEvent);
        }

        /* if wsaOverlapped.InternalHigh is 0, it means 
           that connection has been closed
        */
        if(wsaOverlapped.InternalHigh==0&&wsaOverlapped.Internal==0)
        {
            /* The server shutdown the receiving socket 
               after 400 successfull receive.
            */
            if (i<400)
            {
                Trace("Unexpected wsaOverlapped.InternalHigh = 0 " 
                     "at WSASend attempt #%d", i);

                CloseEventHandle(hWriteEvent);
    
                /* Do some cleanup */
                CloseSocket( testSockets, numSockets ); 

                threadExitCode=THREAD_FAIL;
                ExitThread(0);
            }
            /* the server shutdown the socket as expected */
            break;
        }

        /* keep track of the number of bytes sent */
        byteCounter += wsaOverlapped.InternalHigh;

        /* Verify that the number of bytes sent are the number of byte
           specified in the wsaBuf structure 
        */
        if(wsaSendBuf.len!=wsaOverlapped.InternalHigh)
        {            
            Trace("Server error: Array out of bound "
                "while writing buffer received in myData.\n");

            CloseEventHandle(hWriteEvent);
    
            /* Do some cleanup */
            CloseSocket( testSockets, numSockets );   

            threadExitCode=THREAD_FAIL;
            ExitThread(0);
        }
    }/* end of for loop */

    /* close the handle to hWriteEvent 
       Do some cleanup 
    */
    
    if(!CloseEventHandle(hWriteEvent)||
       !CloseSocket( testSockets, numSockets ))
    {
        threadExitCode=THREAD_FAIL;

        ExitThread(0);
    }

    threadExitCode=THREAD_SUCCESS;

    ExitThread(0);    
}