void CBounsDBManager::RestManagerEvent()
{
	ResetEvent(m_hManagerEvent);
}
Beispiel #2
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];

    /* 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[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 %u\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 %u\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 %u\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 %u\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 %u\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 %u\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 
       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);        

        /* 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 );

        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 %u\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 %u\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 %u\n",
              GetLastError());

        WaitForClientThreadToFinish(hThreadClient);        

        CloseThreadHandle(hThreadClient);        

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

        Fail("");
        
    }



   /* Initialize the WSABUF structure */
    memset(myBuffer, 0, 255);

    wsaBuf.buf = myBuffer;
    wsaBuf.len = 255;    
    
    bufferCounter = 0;
    pMyData = (unsigned char*)myData;

    /* this loop receives data sent from client 
       after 400 recv, it shutdowns the connection to test how
       the client react.
    */
    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;

         /* reset the buffer used by WSARecv */
        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() "
                            "returned  0 bytes\n");
                    
                WaitForClientThreadToFinish(hThreadClient);            
                
                CloseThreadHandle(hThreadClient);

                CloseEventHandle(hReadEvent);
                
                /* Do some cleanup */
                DoWSATestCleanup( testSockets,
                                numSockets );
        
                Fail("");
            }
            /* Reset Event */
            ResetEvent(hReadEvent);
        }
        else
        {
            err = GetLastError();
            /* Only WSA_IO_PENDING is expected */
            if(err!=WSA_IO_PENDING)
            {
                Trace("Server error: WSARecv() "
                        "returned %u, expected WSA_IO_PENDING\n",
                        GetLastError() );
                    
                WaitForClientThreadToFinish(hThreadClient);            
                
                CloseThreadHandle(hThreadClient);

                CloseEventHandle(hReadEvent);
                
                /* Do some cleanup */
                DoWSATestCleanup( testSockets,
                                numSockets );
        
                Fail("");
            }
            /* Wait 10 seconds for ReadEvent to be signaled 
                from the pending operation
            */
            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
        {
            Trace("Server error: Array out of bound "
                "while writing buffer received in myData.\n");

            WaitForClientThreadToFinish(hThreadClient);                

            CloseThreadHandle(hThreadClient);

            CloseEventHandle(hReadEvent);                

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

            Fail("");            
        }

        /* Increment bufferCounter to keep track of the number 
           of byte received */
        bufferCounter += wsaRecvOverlapped.InternalHigh; 
        
    } /* end of the for loop */

    // Ensure that all the data is received before the sockets are closed
    Sleep(2000);

    /* Disconnect the socket */
    err = shutdown( testSockets[1], 
                    SD_BOTH);
    if (err == SOCKET_ERROR)
    {                
        Trace("ERROR: Unexpected failure: "
                "shutdown() socket with local server "
                "returned %u\n",
                GetLastError());  

       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("");
    }

     
    /* verify that all data in the data array are as expected */
    pMyData=(unsigned char*)myData;
    for(i=0;i<bufferCounter;i++)
    {
        if(*pMyData!=(i%255))
        {
            Trace("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;
}
void qemu_event_reset(QemuEvent *ev)
{
    ResetEvent(ev->event);
}
Beispiel #4
0
int MyAssertProc(const wchar_t* pszFile, int nLine, const wchar_t* pszTest, bool abNoPipe)
{
	HooksUnlocker;

	#ifdef _DEBUG
	if (MyAssertSkip(pszFile, nLine, pszTest, abNoPipe))
		return 1;
	#endif

	MyAssertDumpToFile(pszFile, nLine, pszTest);

	HANDLE hHeap = GetProcessHeap();
	MyAssertInfo* pa = (MyAssertInfo*)HeapAlloc(hHeap, HEAP_ZERO_MEMORY, sizeof(MyAssertInfo));
	if (!pa)
		return -1;
	wchar_t *szExeName = (wchar_t*)HeapAlloc(hHeap, HEAP_ZERO_MEMORY, (MAX_PATH+1)*sizeof(wchar_t));
	if (szExeName && !GetModuleFileNameW(NULL, szExeName, MAX_PATH+1)) szExeName[0] = 0;
	pa->bNoPipe = abNoPipe;
	msprintf(pa->szTitle, countof(pa->szTitle), L"CEAssert PID=%u TID=%u", GetCurrentProcessId(), GetCurrentThreadId());
	wchar_t szVer4[2] = WSTRING(MVV_4a);
	msprintf(pa->szDebugInfo, countof(pa->szDebugInfo), L"Assertion in %s [%02u%02u%02u%s]\n%s\n\n%s: %i\n\nPress 'Retry' to trap.",
	                szExeName ? szExeName : L"<HeapAllocFailed>",
					MVV_1, MVV_2, MVV_3, szVer4,
					pszTest ? pszTest : L"", pszFile, nLine);
	DWORD dwCode = 0;

	if (gAllowAssertThread == am_Thread)
	{
		DWORD dwTID;
		HANDLE hThread = apiCreateThread(MyAssertThread, pa, &dwTID, "MyAssertThread");

		if (hThread == NULL)
		{
			dwCode = IDRETRY;
			goto wrap;
		}

		WaitForSingleObject(hThread, INFINITE);
		GetExitCodeThread(hThread, &dwCode);
		CloseHandle(hThread);
		goto wrap;
	}
	
#ifdef ASSERT_PIPE_ALLOWED
#ifdef _DEBUG
	if (!abNoPipe && (gAllowAssertThread == am_Pipe))
	{
		HWND hConWnd = GetConEmuHWND(2);
		HWND hGuiWnd = ghConEmuWnd;

		// -- искать - нельзя. Если мы НЕ в ConEmu - нельзя стучаться в другие копии!!!
		//#ifndef CONEMU_MINIMAL
		//if (hGuiWnd == NULL)
		//{
		//	hGuiWnd = FindWindowEx(NULL, NULL, VirtualConsoleClassMain, NULL);
		//}
		//#endif

		if (hGuiWnd && gnInMyAssertTrap <= 0)
		{
			InterlockedIncrement(&gnInMyAssertTrap);
			InterlockedIncrement(&gnInMyAssertPipe);
			gnInMyAssertThread = GetCurrentThreadId();
			ResetEvent(ghInMyAssertTrap);
			
			dwCode = GuiMessageBox(abNoPipe ? NULL : hGuiWnd, pa->szDebugInfo, pa->szTitle, MB_SETFOREGROUND|MB_SYSTEMMODAL|MB_RETRYCANCEL);
			InterlockedDecrement(&gnInMyAssertTrap);
			InterlockedDecrement(&gnInMyAssertPipe);
			SetEvent(ghInMyAssertTrap);
			gnInMyAssertThread = 0;
			goto wrap;
		}
	}

	while (gnInMyAssertPipe>0 && (gnInMyAssertThread != GetCurrentThreadId()))
	{
		Sleep(250);
	}
#endif
#endif

	// В консольных приложениях попытка запустить CreateThread(MyAssertThread) может зависать
	dwCode = MyAssertThread(pa);

wrap:
	if (pa)
		HeapFree(hHeap, 0, pa);
	if (szExeName)
		HeapFree(hHeap, 0, szExeName);
	return (dwCode == IDRETRY) ? -1 : 1;
}
Beispiel #5
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 */

    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];    
    
    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("");
    }

    /* 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;    

    /* 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 = WSARecvFrom( testSockets[0],
                       &wsaBuf,
                       dwNbrOfBuf,
                       &dwNbrOfByteSent,
                       &dwRecvFlags,
                       (struct sockaddr FAR *) NULL,
                       (int) NULL,
                       &wsaRecvOverlapped,
                       0 ); 

        if( err != SOCKET_ERROR )
        {            
            if(dwNbrOfByteSent==0)
            {
                /* Packet dropped, UDP is not reliable 
                   we just stop receiving
                */
                break;
            }
            /* Reset the event */
            ResetEvent(hReadEvent);
        }
        else
        {
            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("");
            }
        }

        /* 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,
                                            1000 );
            
            if (waitResult!=WAIT_OBJECT_0)
            {            
                /* Packet dropped, UDP is not reliable 
                   we just stop receiving
                */
                break;
            }
        }
        
        
        /* 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("");
        }
        
        /* 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("");
    }    
 
    /* Do some cleanup */
    DoWSATestCleanup( testSockets,
                      numSockets );

    
    if(bufferCounter==0)
    {
        Trace("Server error: 0 byte has been received on UDP socket");
        Fail("");
    }

    PAL_Terminate();
    return PASS;
}
void AT91_USBHS_Driver::Global_ISR( void* Param )
{
    struct AT91_UDPHS *pUdp = (struct AT91_UDPHS *) (AT91C_BASE_UDP);

    UINT32 USB_INTR = (pUdp->UDPHS_INTSTA & pUdp->UDPHS_IEN);
    UINT32 endpoint  = 0;

//    debug_printf("%x", USB_INTR);
    // Handle all UDP interrupts
    while(USB_INTR != 0)
    {
        // Start Of Frame (SOF)
        if(USB_INTR & AT91C_UDPHS_IEN_SOF)
        {

            // Acknowledge interrupt
            pUdp->UDPHS_CLRINT = AT91C_UDPHS_IEN_SOF;
            USB_INTR &= ~AT91C_UDPHS_IEN_SOF;
            // This interrupt should not happen, as it is not enabled.
            
            ASSERT(0);
        }

        // Suspend
        if (USB_INTR & AT91C_UDPHS_DET_SUSPD)
        {
            AT91_PMC_DisableUTMIBIAS();
            // Acknowledge interrupt
            pUdp->UDPHS_CLRINT  = AT91C_UDPHS_DET_SUSPD | AT91C_UDPHS_WAKE_UP;
            USB_INTR &= ~AT91C_UDPHS_DET_SUSPD;
            
            SuspendEvent();        
        }

        // Resume or Wakeup
        if((USB_INTR & AT91C_UDPHS_WAKE_UP) ||(USB_INTR & AT91C_UDPHS_ENDOFRSM))
        {
            ResumeEvent();

            // Acknowledge interrupt
            pUdp->UDPHS_CLRINT = AT91C_UDPHS_WAKE_UP | AT91C_UDPHS_ENDOFRSM;
            USB_INTR &= ~(AT91C_UDPHS_WAKE_UP | AT91C_UDPHS_ENDOFRSM);
        }

        // End of bus reset
        if(USB_INTR & AT91C_UDPHS_ENDRESET)
        {
            // Acknowledge end of bus reset interrupt
            

            ResetEvent();
            pUdp->UDPHS_CLRINT = AT91C_UDPHS_WAKE_UP | AT91C_UDPHS_DET_SUSPD | AT91C_UDPHS_ENDRESET;
            pUdp->UDPHS_IEN |= AT91C_UDPHS_DET_SUSPD;

            USB_INTR &= ~AT91C_UDPHS_ENDRESET;
        }
        
        if(USB_INTR & AT91C_UDPHS_UPSTR_RES)
        {
            pUdp->UDPHS_CLRINT = AT91C_UDPHS_UPSTR_RES;
            USB_INTR &= ~AT91C_UDPHS_UPSTR_RES;
        }
        else //Endpoint Interrupt
        {
            UINT32 i = 0;
            USB_INTR >>= 8;
            while(USB_INTR != 0)
            {
                if (USB_INTR & 1)
                {
                        
                    endpoint  = i;
                    Endpoint_ISR(endpoint);
                    if (endpoint == 1)
                    {
//                        debug_printf("1\r\n");
//                        num_ep_int1 += 1;
                    }
                    if (endpoint == 2)
                    {
//                        debug_printf("2\r\n");
//                        num_ep_int2 += 1;
                    }
                    
                }
                USB_INTR >>= 1;
                i++;
            }
        }
        USB_INTR = pUdp->UDPHS_INTSTA & pUdp->UDPHS_IEN;
    }
}
Beispiel #7
0
void Character::Control(GLdouble FrameInterval)
{
	GLdouble step = WALK_SPEED;
	if(bSpecial[GLUT_KEY_SHIFT_L])
		step *= SPRINT_KOEF;

	if(bKeyboard['W']) {
		dVelocityX -= FrameInterval*AIR_ACCEL*step*sin(TORAD(dSpinY));
		dVelocityZ -= FrameInterval*AIR_ACCEL*step*cos(TORAD(dSpinY));
	}
	if(bKeyboard['S']) {
		dVelocityX += FrameInterval*AIR_ACCEL*step*sin(TORAD(dSpinY));
		dVelocityZ += FrameInterval*AIR_ACCEL*step*cos(TORAD(dSpinY));
	}
	if(bKeyboard['D']) {
		dVelocityX += FrameInterval*AIR_ACCEL*step*cos(TORAD(dSpinY));
		dVelocityZ -= FrameInterval*AIR_ACCEL*step*sin(TORAD(dSpinY));
	}
	if(bKeyboard['A']) {
		dVelocityX -= FrameInterval*AIR_ACCEL*step*cos(TORAD(dSpinY));
		dVelocityZ += FrameInterval*AIR_ACCEL*step*sin(TORAD(dSpinY));
	}
	if(bKeyboard['R']) {
		dVelocityY += FrameInterval*AIR_ACCEL*step;
	}
	if(bKeyboard['F']) {
		dVelocityY -= FrameInterval*AIR_ACCEL*step;
	}

	GLdouble ko = dVelocityX*dVelocityX + dVelocityZ*dVelocityZ;
	if(ko > WALK_SPEED*WALK_SPEED*SPRINT_KOEF*SPRINT_KOEF) {
		ko = pow(ko, 0.5);
		dVelocityX = dVelocityX*WALK_SPEED*SPRINT_KOEF/ko;
		dVelocityZ = dVelocityZ*WALK_SPEED*SPRINT_KOEF/ko;
	}

	if(bKeyboard[VK_SPACE]) {
	}
	
	if(bKeyboard['X']) {
		dVelocityX = 0;
		dVelocityY = 0;
		dVelocityZ = 0;
	}
	
	GLdouble yerr, xerr, zerr;
	GetPlane(&xerr, &yerr, &zerr);
	
	PosInWorld pos;
	if(zerr < xerr && zerr < yerr) {
		if((position.bz < centerPos.bz && position.cz == centerPos.cz) || position.cz < centerPos.cz) {
			pos = PosInWorld(0, 0, 0.5);
		} else {
			pos = PosInWorld(0, 0, -0.5);
		}
	} else if(xerr < zerr && xerr < yerr) {
		if((position.bx < centerPos.bx && position.cx == centerPos.cx) || position.cx < centerPos.cx) {
			pos = PosInWorld(0.5, 0, 0);
		} else {
			pos = PosInWorld(-0.5, 0, 0);
		}
	} else if(yerr < xerr && yerr < zerr) {
		if(position.by < centerPos.by) {
			pos = PosInWorld(0, 0.5, 0);
		} else {
			pos = PosInWorld(0, -0.5, 0);
		}
	}
	aimedBlock = BlockInWorld(centerPos + pos);
	freeBlock = BlockInWorld(centerPos + pos.inv());

	int num = 100;
	int sq = 100;
	int sqb2 = sq/2;

	if(bKeyboard['1']) {
		int i = 0;
		while(i < num) {
			if(wWorld.AddBlock(BlockInWorld(rand()%sq-sqb2, abs(rand()%sq-sqb2), rand()%sq-sqb2), rand()%14+1, true))
				i++;
		}
	}
	if(bKeyboard['2']) {
		int i = 0;
		while(i < num) {
			if(wWorld.RemoveBlock(BlockInWorld(rand()%sq-sqb2, rand()%sq-sqb2, rand()%sq-sqb2), true))
				i++;
		}
	}

	if(bKeyboard['3']) {
		for(BlockCoord i = -sqb2; i <= sqb2; i++) {
			for(BlockCoord j = -sqb2; j <= sqb2; j++) {
				for(BlockCoord k = -sqb2; k <= sqb2; k++) {
					wWorld.RemoveBlock(BlockInWorld(i, j, k), true);
				}
			}
		}
	}

	if(bKeyboard['4']) {
		wWorld.LoadChunk(0, 0);
		bKeyboard['4'] = false;
	}
	if(bKeyboard['5']) {
		wWorld.UnLoadChunk(0, 0);
		bKeyboard['5'] = false;
	}
	if(bKeyboard['6']) {
		for(int i = 0; i < 8; i++)
			for(int j = 0; j < 8; j++)
				wWorld.LoadChunk(i, j);
		bKeyboard['6'] = false;
	}
	if(bKeyboard['7']) {
		for(int i = 0; i < 8; i++)
			for(int j = 0; j < 8; j++)
				wWorld.UnLoadChunk(i, j);
		bKeyboard['7'] = false;
	}

	if(bKeyboard['0']) {
		static Param par = {0, 1, &wWorld};

		_beginthread(LoadNGenerate, 0, &par);

		WaitForSingleObject(wWorld.parget2, INFINITE);
		ResetEvent(wWorld.parget2);

		par.z++;
		bKeyboard['0'] = false;
	}
	
	if(bKeyboard['C']) {
		Chunk *chunk;
		int index;
		wWorld.FindBlock(aimedBlock, &chunk, &index);
		if ((chunk)&&(chunk->bBlocks[index].cMaterial == MAT_DIRT)) {
			chunk->bBlocks[index].bVisible ^= (1 << SNOWCOVERED);
		}
	}
	if(bKeyboard['V']) {
		Chunk *chunk;
		int index;
		wWorld.FindBlock(aimedBlock, &chunk, &index);
		if ((chunk)&&(chunk->bBlocks[index].cMaterial == MAT_DIRT)) {
			chunk->bBlocks[index].bVisible ^= (1 << GRASSCOVERED);
		}
	}
	if(bKeyboard['E']) {
		wWorld.RemoveBlock(aimedBlock, true);
	}
	if(bKeyboard['Q']) {
		wWorld.AddBlock(freeBlock, MAT_PUMPKIN_SHINE, true);
	}
	if(bKeyboard['O']) {
		wWorld.SaveChunks();
	}

	position = position + PosInWorld(FrameInterval*dVelocityX, FrameInterval*dVelocityY, FrameInterval*dVelocityZ);

	/*{
		signed short xx, yy, zz;
		GLdouble wx = gfPosX + gfVelX;
		GLdouble wy = gfPosY - PLAYER_HEIGHT + 0.1;
		GLdouble wz = gfPosZ;

		xx = floor(wx/TILE_SIZE + 0.5);
		zz = floor(wz/TILE_SIZE + 0.5);
		yy = floor(wy/TILE_SIZE);

		if((FindTile(xx, yy, zz) == NULL)&&(FindTile(xx, yy + 1, zz) == NULL))
			gfPosX += g_FrameInterval*gfVelX;
		else gfVelX = 0;
	}
	{
		signed short xx, yy, zz;
		GLdouble wx = gfPosX;
		GLdouble wy = gfPosY - PLAYER_HEIGHT + 0.1;
		GLdouble wz = gfPosZ + gfVelZ;

		xx = floor(wx/TILE_SIZE + 0.5);
		zz = floor(wz/TILE_SIZE + 0.5);
		yy = floor(wy/TILE_SIZE);

		if((FindTile(xx, yy, zz) == NULL)&&(FindTile(xx, yy + 1, zz) == NULL))
			gfPosZ += g_FrameInterval*gfVelZ;
		else gfVelZ = 0;
	}
	*/
	/*if(falling)
	{
		gfPosY -= g_FrameInterval*gfVelY;
		if(gfVelY < MAX_DOWNSTEP)
			gfVelY += g_FrameInterval*STEP_DOWNSTEP;
	}*/
	/*
	{
		signed short xx, yy, zz;
		GLdouble wx = gfPosX;
		GLdouble wy = gfPosY - PLAYER_HEIGHT;
		GLdouble wz = gfPosZ;

		xx = floor(wx/TILE_SIZE + 0.5);
		zz = floor(wz/TILE_SIZE + 0.5);
		yy = floor(wy/TILE_SIZE);

		if(FindTile(xx, yy, zz) == NULL) falling = true;
		else
		{
			gfVelY = 0;
			if(falling)
			{
				falling = false;
				gfPosY = (yy + 1)*TILE_SIZE + PLAYER_HEIGHT - 0.001;
			}
		}
	}

	if(!falling)
	{
		gfVelX = 0;
		gfVelZ = 0;
	}*/
	//falling = 1;

// 	if(dPositionX >= LOCATION_SIZE_XZ*TILE_SIZE) { dPositionX -= LOCATION_SIZE_XZ*TILE_SIZE; lnwPositionX++;}
// 	if(dPositionX < 0) { dPositionX += LOCATION_SIZE_XZ*TILE_SIZE; lnwPositionX--;}
// 	if(dPositionZ >= LOCATION_SIZE_XZ*TILE_SIZE) { dPositionZ -= LOCATION_SIZE_XZ*TILE_SIZE; lnwPositionZ++;}
// 	if(dPositionZ < 0) { dPositionZ += LOCATION_SIZE_XZ*TILE_SIZE; lnwPositionZ--;}

}
Beispiel #8
0
bool	CAGuard::WaitFor(UInt64 inNanos)
{
	bool theAnswer = false;

#if TARGET_OS_MAC
	ThrowIf(!pthread_equal(pthread_self(), mOwner), CAException(1), "CAGuard::WaitFor: A thread has to have locked a guard be for it can wait");

	#if	Log_TimedWaits
		DebugMessageN1("CAGuard::WaitFor: waiting %.0f", (Float64)inNanos);
	#endif

	struct timespec	theTimeSpec;
	static const UInt64	kNanosPerSecond = 1000000000ULL;
	if(inNanos >= kNanosPerSecond)
	{
		theTimeSpec.tv_sec = static_cast<UInt32>(inNanos / kNanosPerSecond);
		theTimeSpec.tv_nsec = static_cast<UInt32>(inNanos % kNanosPerSecond);
	}
	else
	{
		theTimeSpec.tv_sec = 0;
		theTimeSpec.tv_nsec = static_cast<UInt32>(inNanos);
	}
	
	#if	Log_TimedWaits || Log_Latency || Log_Average_Latency
		UInt64	theStartNanos = CAHostTimeBase::GetCurrentTimeInNanos();
	#endif

	mOwner = 0;

	#if	Log_WaitOwnership
		DebugPrintfRtn(DebugPrintfFileComma "%p %.4f: CAGuard::WaitFor: thread %p is waiting on %s, owner: %p\n", pthread_self(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), pthread_self(), mName, mOwner);
	#endif

	OSStatus theError = pthread_cond_timedwait_relative_np(&mCondVar, &mMutex, &theTimeSpec);
	ThrowIf((theError != 0) && (theError != ETIMEDOUT), CAException(theError), "CAGuard::WaitFor: Wait got an error");
	mOwner = pthread_self();
	
	#if	Log_TimedWaits || Log_Latency || Log_Average_Latency
		UInt64	theEndNanos = CAHostTimeBase::GetCurrentTimeInNanos();
	#endif
	
	#if	Log_TimedWaits
		DebugMessageN1("CAGuard::WaitFor: waited  %.0f", (Float64)(theEndNanos - theStartNanos));
	#endif
	
	#if	Log_Latency
		DebugMessageN1("CAGuard::WaitFor: latency  %.0f", (Float64)((theEndNanos - theStartNanos) - inNanos));
	#endif
	
	#if	Log_Average_Latency
		++mAverageLatencyCount;
		mAverageLatencyAccumulator += (theEndNanos - theStartNanos) - inNanos;
		if(mAverageLatencyCount >= 50)
		{
			DebugMessageN2("CAGuard::WaitFor: average latency  %.3f ns over %ld waits", mAverageLatencyAccumulator / mAverageLatencyCount, mAverageLatencyCount);
			mAverageLatencyCount = 0;
			mAverageLatencyAccumulator = 0.0;
		}
	#endif

	#if	Log_WaitOwnership
		DebugPrintfRtn(DebugPrintfFileComma "%p %.4f: CAGuard::WaitFor: thread %p waited on %s, owner: %p\n", pthread_self(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), pthread_self(), mName, mOwner);
	#endif

	theAnswer = theError == ETIMEDOUT;
#elif TARGET_OS_WIN32
	ThrowIf(GetCurrentThreadId() != mOwner, CAException(1), "CAGuard::WaitFor: A thread has to have locked a guard be for it can wait");

	#if	Log_TimedWaits
		DebugMessageN1("CAGuard::WaitFor: waiting %.0f", (Float64)inNanos);
	#endif

	//	the time out is specified in milliseconds(!)
	UInt32 theWaitTime = static_cast<UInt32>(inNanos / 1000000ULL);

	#if	Log_TimedWaits || Log_Latency || Log_Average_Latency
		UInt64	theStartNanos = CAHostTimeBase::GetCurrentTimeInNanos();
	#endif

	mOwner = 0;

	#if	Log_WaitOwnership
		DebugPrintfRtn(DebugPrintfFileComma "%lu %.4f: CAGuard::WaitFor: thread %lu is waiting on %s, owner: %lu\n", GetCurrentThreadId(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), GetCurrentThreadId(), mName, mOwner);
	#endif
	
	ReleaseMutex(mMutex);
	HANDLE theHandles[] = { mMutex, mEvent };
	OSStatus theError = WaitForMultipleObjects(2, theHandles, true, theWaitTime);
	ThrowIf((theError != WAIT_OBJECT_0) && (theError != WAIT_TIMEOUT), CAException(GetLastError()), "CAGuard::WaitFor: Wait got an error");
	mOwner = GetCurrentThreadId();
	ResetEvent(mEvent);
	
	#if	Log_TimedWaits || Log_Latency || Log_Average_Latency
		UInt64	theEndNanos = CAHostTimeBase::GetCurrentTimeInNanos();
	#endif
	
	#if	Log_TimedWaits
		DebugMessageN1("CAGuard::WaitFor: waited  %.0f", (Float64)(theEndNanos - theStartNanos));
	#endif
	
	#if	Log_Latency
		DebugMessageN1("CAGuard::WaitFor: latency  %.0f", (Float64)((theEndNanos - theStartNanos) - inNanos));
	#endif
	
	#if	Log_Average_Latency
		++mAverageLatencyCount;
		mAverageLatencyAccumulator += (theEndNanos - theStartNanos) - inNanos;
		if(mAverageLatencyCount >= 50)
		{
			DebugMessageN2("CAGuard::WaitFor: average latency  %.3f ns over %ld waits", mAverageLatencyAccumulator / mAverageLatencyCount, mAverageLatencyCount);
			mAverageLatencyCount = 0;
			mAverageLatencyAccumulator = 0.0;
		}
	#endif

	#if	Log_WaitOwnership
		DebugPrintfRtn(DebugPrintfFileComma "%lu %.4f: CAGuard::WaitFor: thread %lu waited on %s, owner: %lu\n", GetCurrentThreadId(), ((Float64)(CAHostTimeBase::GetCurrentTimeInNanos()) / 1000000.0), GetCurrentThreadId(), mName, mOwner);
	#endif

	theAnswer = theError == WAIT_TIMEOUT;
#endif

	return theAnswer;
}
Beispiel #9
0
void __cdecl CMsnProto::MsnFileAckThread(void* arg)
{
	filetransfer* ft = (filetransfer*)arg;

	TCHAR filefull[MAX_PATH];
	mir_sntprintf(filefull, _T("%s\\%s"), ft->std.tszWorkingDir, ft->std.tszCurrentFile);
	replaceStrT(ft->std.tszCurrentFile, filefull);

	ResetEvent(ft->hResumeEvt);
	if (ProtoBroadcastAck(ft->std.hContact, ACKTYPE_FILE, ACKRESULT_FILERESUME, ft, (LPARAM)&ft->std))
		WaitForSingleObject(ft->hResumeEvt, INFINITE);

	ft->create();

#ifdef OBSOLETE
	if (ft->tType != SERVER_HTTP) {
		if (ft->p2p_appID != 0) {
			if (fcrt)
				p2p_sendFeedStart(ft);
			p2p_sendStatus(ft, fcrt ? 200 : 603);
		}
		else msnftp_sendAcceptReject(ft, fcrt);
	}
#endif

	ProtoBroadcastAck(ft->std.hContact, ACKTYPE_FILE, ACKRESULT_INITIALISING, ft, 0);

	if (ft->tType == SERVER_HTTP) {
		const char *pszSkypeToken;

		if (ft->fileId != -1 && (pszSkypeToken=authSkypeToken.Token())) {
			NETLIBHTTPHEADER nlbhHeaders[3] = { 0 };
			NETLIBHTTPREQUEST nlhr = { 0 }, *nlhrReply;
			char szRange[32];

			nlbhHeaders[0].szName = "User-Agent";		nlbhHeaders[0].szValue = (LPSTR)MSN_USER_AGENT;
			nlbhHeaders[1].szName = "Authorization";	nlbhHeaders[1].szValue = (char*)pszSkypeToken;
			nlhr.headersCount = 2;
			if (ft->std.currentFileProgress) {
				mir_snprintf(szRange, sizeof(szRange), "bytes=%I64d-", ft->std.currentFileProgress);
				nlbhHeaders[2].szName = "Range";
				nlbhHeaders[2].szValue = szRange;
				nlhr.headersCount++;
			}

			nlhr.cbSize = sizeof(nlhr);
			nlhr.requestType = REQUEST_GET;
			nlhr.flags = NLHRF_GENERATEHOST | NLHRF_SMARTREMOVEHOST | NLHRF_SMARTAUTHHEADER | NLHRF_HTTP11;
			nlhr.szUrl = ft->szInvcookie;
			nlhr.headers = (NETLIBHTTPHEADER*)&nlbhHeaders;

			NETLIBOPENCONNECTION nloc = { 0 };
			MyNetlibConnFromUrl(nlhr.szUrl, nloc);
			nloc.flags |= NLOCF_HTTP;
			if (nloc.flags & NLOCF_SSL) nlhr.flags |= NLHRF_SSL;
			HANDLE nlc = (HANDLE)CallService(MS_NETLIB_OPENCONNECTION, (WPARAM)m_hNetlibUser, (LPARAM)&nloc);

			if (nlc && CallService(MS_NETLIB_SENDHTTPREQUEST, (WPARAM)nlc, (LPARAM)&nlhr) != SOCKET_ERROR &&
				(nlhrReply = (NETLIBHTTPREQUEST*)CallService(MS_NETLIB_RECVHTTPHEADERS, (WPARAM)nlc, 0))) 
			{
					if (nlhrReply->resultCode == 200 || nlhrReply->resultCode == 206) {
						INT_PTR dw;
						char buf[1024];

						ProtoBroadcastAck(ft->std.hContact, ACKTYPE_FILE, ACKRESULT_CONNECTED, ft, 0);
						while (!ft->bCanceled && ft->std.currentFileProgress < ft->std.currentFileSize &&
							(dw = Netlib_Recv(nlc, buf, sizeof(buf), MSG_NODUMP))>0 && dw!=SOCKET_ERROR) 
						{
							_write(ft->fileId, buf, dw);
							ft->std.totalProgress += dw;
							ft->std.currentFileProgress += dw;
							ProtoBroadcastAck(ft->std.hContact, ACKTYPE_FILE, ACKRESULT_DATA, ft, (LPARAM)&ft->std);
						}
						if (ft->std.currentFileProgress == ft->std.currentFileSize) ft->std.currentFileNumber++;

					}
					CallService(MS_NETLIB_FREEHTTPREQUESTSTRUCT, 0, (LPARAM)nlhrReply);
			}
			Netlib_CloseHandle(nlc);
			mir_free((char*)nloc.szHost);
			if (ft->std.currentFileNumber >= ft->std.totalFiles) ft->complete();
		}
		delete ft;
	}
}
Beispiel #10
0
DWORD WINAPI ReadDILCANMsg(LPVOID pVoid)
{
    CPARAM_THREADPROC* pThreadParam = (CPARAM_THREADPROC*) pVoid;

    if (pThreadParam != NULL)
    {
        CReadCanMsg* pCurrObj = (CReadCanMsg*) pThreadParam->m_pBuffer;

        if (pCurrObj != NULL)
        {
            pThreadParam->m_unActionCode = INVOKE_FUNCTION; // Set default action
            // Create the action event. In this case this will be used solely for
            // thread exit procedure. The first entry will be used.
            pThreadParam->m_hActionEvent = pCurrObj->m_ahActionEvent[0];
            DWORD dwWaitRet;
            BYTE byHIndex;
            bool bLoopON = true;

            while (bLoopON)
            {
                dwWaitRet = WaitForMultipleObjects(pCurrObj->m_nEvents,
                                                   pCurrObj->m_ahActionEvent, FALSE, INFINITE);
                ///// TEMP : BEGIN
                DWORD dwLLimit = WAIT_OBJECT_0;
                DWORD dwULimit = WAIT_OBJECT_0 + pCurrObj->m_nEvents - 1;
                DWORD dwLLError = WAIT_ABANDONED_0;
                DWORD dwULError = WAIT_ABANDONED_0 + pCurrObj->m_nEvents - 1;

                if ((dwWaitRet >= dwLLimit) && (dwWaitRet <= dwULimit))
                {
                    switch (pThreadParam->m_unActionCode)
                    {
                        case INVOKE_FUNCTION:
                        {
                            //Get the handle's index and pass it
                            byHIndex = (BYTE)(dwWaitRet - WAIT_OBJECT_0);
                            HANDLE hHandleSet = pCurrObj->m_ahActionEvent[byHIndex];
                            BYTE byNodeIndex;

                            if( pCurrObj->m_omHandleToNodeMgrMap.Lookup(hHandleSet, byNodeIndex))
                            {
                                //vRetrieveDataFromBuffer to read from that buffer
                                pCurrObj->vRetrieveDataFromBuffer(byNodeIndex);
                            }

                            //BOOL Result = ResetEvent(hHandleSet);
                            ResetEvent(hHandleSet);
                        }
                        break;

                        case EXIT_THREAD:
                        {
                            bLoopON = false;
                        }
                        break;

                        case INACTION:
                        {
                            // Signal the owner
                            SetEvent(pThreadParam->m_hThread2Owner);
                            Sleep(0);
                            // Wait until owner signals back.
                            WaitForSingleObject(pThreadParam->m_hOwner2Thread, INFINITE);
                            // Signal the owner
                            SetEvent(pThreadParam->m_hThread2Owner);
                            Sleep(0);
                        }
                        break;

                        case CREATE_TIME_MAP:
                        default:
                            break;
                    }
                }
                else if ((dwWaitRet >= dwLLError) && (dwWaitRet <= dwULError))
                {
                    TRACE(_T("Abandoned... %X %d\n"), dwWaitRet, g_unCount++);
                }
                else if ( dwWaitRet == WAIT_TIMEOUT)
                {
                    TRACE(_T("ReadDILCANMsg->WAIT_TIMEOUT %d\n"), g_unCount++);
                }
                else if (dwWaitRet == WAIT_FAILED)
                {
                    TRACE(_T("WAIT_FAILED... %X %d\n"), GetLastError(), g_unCount++);
                }

                ///// TEMP : END
            }

            SetEvent(pThreadParam->hGetExitNotifyEvent());
        }
    }

    return 0;
}
Beispiel #11
0
bool CLREventStatic::Reset()
{
    if (!m_fInitialized)
        return false;
    return !!ResetEvent(m_hEvent);
}
Beispiel #12
0
static NTSTATUS NTAPI
ConSrvTermReadStream(IN OUT PTERMINAL This,
                     /**/IN PUNICODE_STRING ExeName /**/OPTIONAL/**/,/**/
                     IN BOOLEAN Unicode,
                     /**PWCHAR Buffer,**/
                     OUT PVOID Buffer,
                     IN OUT PCONSOLE_READCONSOLE_CONTROL ReadControl,
                     IN ULONG NumCharsToRead,
                     OUT PULONG NumCharsRead OPTIONAL)
{
    PFRONTEND FrontEnd = This->Data;
    PCONSRV_CONSOLE Console = FrontEnd->Console;
    PCONSOLE_INPUT_BUFFER InputBuffer = &Console->InputBuffer;

    // STATUS_PENDING : Wait if more to read ; STATUS_SUCCESS : Don't wait.
    NTSTATUS Status = STATUS_PENDING;

    PLIST_ENTRY CurrentEntry;
    ConsoleInput *Input;
    ULONG i;

    /* Validity checks */
    // ASSERT(Console == InputBuffer->Header.Console);
    ASSERT((Buffer != NULL) || (Buffer == NULL && NumCharsToRead == 0));

    /* We haven't read anything (yet) */
    i = ReadControl->nInitialChars;

    if (InputBuffer->Mode & ENABLE_LINE_INPUT)
    {
        /* COOKED mode, call the line discipline */

        if (Console->LineBuffer == NULL)
        {
            /* Starting a new line */
            Console->LineMaxSize = max(256, NumCharsToRead);

            Console->LineBuffer = ConsoleAllocHeap(0, Console->LineMaxSize * sizeof(WCHAR));
            if (Console->LineBuffer == NULL) return STATUS_NO_MEMORY;

            Console->LinePos = Console->LineSize = ReadControl->nInitialChars;
            Console->LineComplete = Console->LineUpPressed = FALSE;
            Console->LineInsertToggle = Console->InsertMode;
            Console->LineWakeupMask = ReadControl->dwCtrlWakeupMask;

            /*
             * Pre-filling the buffer is only allowed in the Unicode API,
             * so we don't need to worry about ANSI <-> Unicode conversion.
             */
            memcpy(Console->LineBuffer, Buffer, Console->LineSize * sizeof(WCHAR));
            if (Console->LineSize == Console->LineMaxSize)
            {
                Console->LineComplete = TRUE;
                Console->LinePos = 0;
            }
        }

        /* If we don't have a complete line yet, process the pending input */
        while (!Console->LineComplete && !IsListEmpty(&InputBuffer->InputEvents))
        {
            /* Remove input event from queue */
            CurrentEntry = RemoveHeadList(&InputBuffer->InputEvents);
            if (IsListEmpty(&InputBuffer->InputEvents))
            {
                ResetEvent(InputBuffer->ActiveEvent);
            }
            Input = CONTAINING_RECORD(CurrentEntry, ConsoleInput, ListEntry);

            /* Only pay attention to key down */
            if (Input->InputEvent.EventType == KEY_EVENT &&
                Input->InputEvent.Event.KeyEvent.bKeyDown)
            {
                LineInputKeyDown(Console, ExeName,
                                 &Input->InputEvent.Event.KeyEvent);
                ReadControl->dwControlKeyState = Input->InputEvent.Event.KeyEvent.dwControlKeyState;
            }
            ConsoleFreeHeap(Input);
        }

        /* Check if we have a complete line to read from */
        if (Console->LineComplete)
        {
            while (i < NumCharsToRead && Console->LinePos != Console->LineSize)
            {
                WCHAR Char = Console->LineBuffer[Console->LinePos++];

                if (Unicode)
                {
                    ((PWCHAR)Buffer)[i] = Char;
                }
                else
                {
                    ConsoleInputUnicodeCharToAnsiChar(Console, &((PCHAR)Buffer)[i], &Char);
                }
                ++i;
            }

            if (Console->LinePos == Console->LineSize)
            {
                /* Entire line has been read */
                ConsoleFreeHeap(Console->LineBuffer);
                Console->LineBuffer = NULL;
            }

            Status = STATUS_SUCCESS;
        }
    }
    else
    {
        /* RAW mode */

        /* Character input */
        while (i < NumCharsToRead && !IsListEmpty(&InputBuffer->InputEvents))
        {
            /* Remove input event from queue */
            CurrentEntry = RemoveHeadList(&InputBuffer->InputEvents);
            if (IsListEmpty(&InputBuffer->InputEvents))
            {
                ResetEvent(InputBuffer->ActiveEvent);
            }
            Input = CONTAINING_RECORD(CurrentEntry, ConsoleInput, ListEntry);

            /* Only pay attention to valid characters, on key down */
            if (Input->InputEvent.EventType == KEY_EVENT  &&
                Input->InputEvent.Event.KeyEvent.bKeyDown &&
                Input->InputEvent.Event.KeyEvent.uChar.UnicodeChar != L'\0')
            {
                WCHAR Char = Input->InputEvent.Event.KeyEvent.uChar.UnicodeChar;

                if (Unicode)
                {
                    ((PWCHAR)Buffer)[i] = Char;
                }
                else
                {
                    ConsoleInputUnicodeCharToAnsiChar(Console, &((PCHAR)Buffer)[i], &Char);
                }
                ++i;

                /* Did read something */
                Status = STATUS_SUCCESS;
            }
            ConsoleFreeHeap(Input);
        }
    }

    // FIXME: Only set if Status == STATUS_SUCCESS ???
    if (NumCharsRead) *NumCharsRead = i;

    return Status;
}
Beispiel #13
0
static void named_pipe_accept_loop(const char *path) {
  HANDLE handles[2];
  OVERLAPPED olap;
  HANDLE connected_event = CreateEvent(NULL, FALSE, TRUE, NULL);

  if (!connected_event) {
    w_log(W_LOG_ERR, "named_pipe_accept_loop: CreateEvent failed: %s\n",
        win32_strerror(GetLastError()));
    return;
  }

  listener_thread_event = CreateEvent(NULL, FALSE, TRUE, NULL);

  handles[0] = connected_event;
  handles[1] = listener_thread_event;
  memset(&olap, 0, sizeof(olap));
  olap.hEvent = connected_event;

  w_log(W_LOG_ERR, "waiting for pipe clients on %s\n", path);
  while (!stopping) {
    w_stm_t stm;
    HANDLE client_fd;
    DWORD res;

    client_fd = CreateNamedPipe(
        path,
        PIPE_ACCESS_DUPLEX|FILE_FLAG_OVERLAPPED,
        PIPE_TYPE_BYTE|PIPE_READMODE_BYTE|
        PIPE_REJECT_REMOTE_CLIENTS,
        PIPE_UNLIMITED_INSTANCES,
        WATCHMAN_IO_BUF_SIZE,
        512, 0, NULL);

    if (client_fd == INVALID_HANDLE_VALUE) {
      w_log(W_LOG_ERR, "CreateNamedPipe(%s) failed: %s\n",
          path, win32_strerror(GetLastError()));
      continue;
    }

    ResetEvent(connected_event);
    if (!ConnectNamedPipe(client_fd, &olap)) {
      res = GetLastError();

      if (res == ERROR_PIPE_CONNECTED) {
        goto good_client;
      }

      if (res != ERROR_IO_PENDING) {
        w_log(W_LOG_ERR, "ConnectNamedPipe: %s\n",
            win32_strerror(GetLastError()));
        CloseHandle(client_fd);
        continue;
      }

      res = WaitForMultipleObjectsEx(2, handles, false, INFINITE, true);
      if (res == WAIT_OBJECT_0 + 1) {
        // Signalled to stop
        CancelIoEx(client_fd, &olap);
        CloseHandle(client_fd);
        continue;
      }

      if (res == WAIT_OBJECT_0) {
        goto good_client;
      }

      w_log(W_LOG_ERR, "WaitForMultipleObjectsEx: ConnectNamedPipe: "
          "unexpected status %u\n", res);
      CancelIoEx(client_fd, &olap);
      CloseHandle(client_fd);
    } else {
good_client:
      stm = w_stm_handleopen(client_fd);
      if (!stm) {
        w_log(W_LOG_ERR, "Failed to allocate stm for pipe handle: %s\n",
            strerror(errno));
        CloseHandle(client_fd);
        continue;
      }

      make_new_client(stm);
    }
  }
}
Beispiel #14
0
static DWORD WINAPI PerformancePageRefreshThread(void *lpParameter)
{
	ULONG	CommitChargeTotal;
	ULONG	CommitChargeLimit;
	ULONG	CommitChargePeak;

	ULONG	KernelMemoryTotal;
	ULONG	KernelMemoryPaged;
	ULONG	KernelMemoryNonPaged;

	ULONG	PhysicalMemoryTotal;
	ULONG	PhysicalMemoryAvailable;
	ULONG	PhysicalMemorySystemCache;

	ULONG	TotalHandles;
	ULONG	TotalThreads;
	ULONG	TotalProcesses;

	WCHAR	Text[256];

	static const WCHAR    wszFormatDigit[] = {'%','u',0};
	WCHAR    wszMemUsage[255];

	LoadStringW(hInst, IDS_STATUS_BAR_MEMORY_USAGE, wszMemUsage, sizeof(wszMemUsage)/sizeof(WCHAR));

	/*  Create the event */
	hPerformancePageEvent = CreateEventW(NULL, TRUE, TRUE, NULL);

	/*  If we couldn't create the event then exit the thread */
	if (!hPerformancePageEvent)
		return 0;

	while (1)
	{
		DWORD	dwWaitVal;

		/*  Wait on the event */
		dwWaitVal = WaitForSingleObject(hPerformancePageEvent, INFINITE);

		/*  If the wait failed then the event object must have been */
		/*  closed and the task manager is exiting so exit this thread */
		if (dwWaitVal == WAIT_FAILED)
			return 0;

		if (dwWaitVal == WAIT_OBJECT_0)
		{
			ULONG CpuUsage;
			ULONG CpuKernelUsage;
			int nBarsUsed1, nBarsUsed2;
			DWORD_PTR args[2];

			/*  Reset our event */
			ResetEvent(hPerformancePageEvent);

			/* 
			 *  Update the commit charge info
			 */ 
			CommitChargeTotal = PerfDataGetCommitChargeTotalK();
			CommitChargeLimit = PerfDataGetCommitChargeLimitK();
			CommitChargePeak = PerfDataGetCommitChargePeakK();
			wsprintfW(Text, wszFormatDigit, CommitChargeTotal);
			SetWindowTextW(hPerformancePageCommitChargeTotalEdit, Text);
			wsprintfW(Text, wszFormatDigit, CommitChargeLimit);
			SetWindowTextW(hPerformancePageCommitChargeLimitEdit, Text);
			wsprintfW(Text, wszFormatDigit, CommitChargePeak);

			SetWindowTextW(hPerformancePageCommitChargePeakEdit, Text);

			args[0] = CommitChargeTotal;
			args[1] = CommitChargeLimit;
			FormatMessageW(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ARGUMENT_ARRAY,
			               wszMemUsage, 0, 0, Text,
			               sizeof(Text)/sizeof(*Text), (__ms_va_list*)args);
			SendMessageW(hStatusWnd, SB_SETTEXTW, 2, (LPARAM)Text);

			/* 
			 *  Update the kernel memory info
			 */ 
			KernelMemoryTotal = PerfDataGetKernelMemoryTotalK();
			KernelMemoryPaged = PerfDataGetKernelMemoryPagedK();
			KernelMemoryNonPaged = PerfDataGetKernelMemoryNonPagedK();
			wsprintfW(Text, wszFormatDigit, KernelMemoryTotal);
			SetWindowTextW(hPerformancePageKernelMemoryTotalEdit, Text);
			wsprintfW(Text, wszFormatDigit, KernelMemoryPaged);
			SetWindowTextW(hPerformancePageKernelMemoryPagedEdit, Text);
			wsprintfW(Text, wszFormatDigit, KernelMemoryNonPaged);
			SetWindowTextW(hPerformancePageKernelMemoryNonPagedEdit, Text);

			/* 
			 *  Update the physical memory info
			 */ 
			PhysicalMemoryTotal = PerfDataGetPhysicalMemoryTotalK();
			PhysicalMemoryAvailable = PerfDataGetPhysicalMemoryAvailableK();
			PhysicalMemorySystemCache = PerfDataGetPhysicalMemorySystemCacheK();
			wsprintfW(Text, wszFormatDigit, PhysicalMemoryTotal);
			SetWindowTextW(hPerformancePagePhysicalMemoryTotalEdit, Text);
			wsprintfW(Text, wszFormatDigit, PhysicalMemoryAvailable);
			SetWindowTextW(hPerformancePagePhysicalMemoryAvailableEdit, Text);
			wsprintfW(Text, wszFormatDigit, PhysicalMemorySystemCache);
			SetWindowTextW(hPerformancePagePhysicalMemorySystemCacheEdit, Text);

			/* 
			 *  Update the totals info
			 */ 
			TotalHandles = PerfDataGetSystemHandleCount();
			TotalThreads = PerfDataGetTotalThreadCount();
			TotalProcesses = PerfDataGetProcessCount();
			wsprintfW(Text, wszFormatDigit, TotalHandles);
			SetWindowTextW(hPerformancePageTotalsHandleCountEdit, Text);
			wsprintfW(Text, wszFormatDigit, TotalThreads);
			SetWindowTextW(hPerformancePageTotalsThreadCountEdit, Text);
			wsprintfW(Text, wszFormatDigit, TotalProcesses);
			SetWindowTextW(hPerformancePageTotalsProcessCountEdit, Text);

			/* 
			 *  Redraw the graphs
			 */ 
			InvalidateRect(hPerformancePageCpuUsageGraph, NULL, FALSE);
			InvalidateRect(hPerformancePageMemUsageGraph, NULL, FALSE);

                        /*
                         *  Get the CPU usage
                         */
                        CpuUsage = PerfDataGetProcessorUsage();
                        CpuKernelUsage = PerfDataGetProcessorSystemUsage();

                        /*
                         *  Get the memory usage
                         */
                        CommitChargeTotal = (ULONGLONG)PerfDataGetCommitChargeTotalK();
                        CommitChargeLimit = (ULONGLONG)PerfDataGetCommitChargeLimitK();
                        nBarsUsed1 = CommitChargeLimit ? ((CommitChargeTotal * 100) / CommitChargeLimit) : 0;

                        PhysicalMemoryTotal = PerfDataGetPhysicalMemoryTotalK();
                        PhysicalMemoryAvailable = PerfDataGetPhysicalMemoryAvailableK();
                        nBarsUsed2 = PhysicalMemoryTotal ? ((PhysicalMemoryAvailable * 100) / PhysicalMemoryTotal) : 0;


                        GraphCtrl_AppendPoint(&PerformancePageCpuUsageHistoryGraph, CpuUsage, CpuKernelUsage, 0.0, 0.0);
                        GraphCtrl_AppendPoint(&PerformancePageMemUsageHistoryGraph, nBarsUsed1, nBarsUsed2, 0.0, 0.0);
                        /* PerformancePageMemUsageHistoryGraph.SetRange(0.0, 100.0, 10) ; */
                        InvalidateRect(hPerformancePageMemUsageHistoryGraph, NULL, FALSE);
                        InvalidateRect(hPerformancePageCpuUsageHistoryGraph, NULL, FALSE);
                }
	}
        return 0;
}
Beispiel #15
0
/// <summary>
/// Execute code in context of any existing thread
/// </summary>
/// <param name="pCode">Cde to execute</param>
/// <param name="size">Code size.</param>
/// <param name="callResult">Execution result</param>
/// <param name="thd">Target thread</param>
/// <returns>Status</returns>
NTSTATUS RemoteExec::ExecInAnyThread( PVOID pCode, size_t size, uint64_t& callResult, Thread& thd )
{
    NTSTATUS dwResult = STATUS_SUCCESS;
    CONTEXT_T ctx;

    // Prepare for remote exec
    CreateRPCEnvironment( true );

    // Write code
    dwResult = CopyCode( pCode, size );
    if (dwResult != STATUS_SUCCESS)
        return dwResult;

    if (_hWaitEvent)
        ResetEvent( _hWaitEvent );

    if (!thd.Suspend())
        return LastNtStatus();

    if (thd.GetContext( ctx, CONTEXT_ALL, true ))
    {
        AsmJit::Assembler a;
        AsmJitHelper ah( a );

#ifdef _M_AMD64
        const int count = 15;
        AsmJit::GPReg regs[] = { AsmJit::rax, AsmJit::rbx, AsmJit::rcx, AsmJit::rdx, AsmJit::rsi,
                                 AsmJit::rdi, AsmJit::r8,  AsmJit::r9,  AsmJit::r10, AsmJit::r11,
                                 AsmJit::r12, AsmJit::r13, AsmJit::r14, AsmJit::r15, AsmJit::rbp
                               };
        //
        // Preserve thread context
        // I don't care about FPU, XMM and anything else
        //
        a.sub(AsmJit::rsp, count * WordSize);  // Stack must be aligned on 16 bytes
        a.pushfq();                            //

        // Save registers
        for (int i = 0; i < count; i++)
            a.mov( AsmJit::Mem( AsmJit::rsp, i * WordSize ), regs[i] );

        ah.GenCall( _userCode.ptr<size_t>(), { _userData.ptr<size_t>() } );
        AddReturnWithEvent( ah, rt_int32, INTRET_OFFSET );

        // Restore registers
        for (int i = 0; i < count; i++)
            a.mov( regs[i], AsmJit::Mem( AsmJit::rsp, i * WordSize ) );

        a.popfq();
        a.add( AsmJit::rsp, count * WordSize );

        a.jmp( ctx.Rip );
#else
        a.pushad();
        a.pushfd();

        ah.GenCall( _userCode.ptr<size_t>(), { _userData.ptr<size_t>() } );
        AddReturnWithEvent( ah, rt_int32, INTRET_OFFSET );

        a.popfd();
        a.popad();

        a.push( ctx.NIP );
        a.ret();
#endif

        if (_userCode.Write( size, a.getCodeSize(), a.make() ) == STATUS_SUCCESS)
        {
            ctx.NIP = _userCode.ptr<size_t>() + size;

            if (!thd.SetContext( ctx, true ))
                dwResult = LastNtStatus();
        }
        else
            dwResult = LastNtStatus();
    }
    else
        dwResult = LastNtStatus();

    thd.Resume();

    if (dwResult == STATUS_SUCCESS)
    {
        WaitForSingleObject( _hWaitEvent, INFINITE );
        callResult = _userData.Read<size_t>( INTRET_OFFSET, 0 );
    }

    return dwResult;
}
void CEventThread::RunThread()
{
	Log(StrF(_T("Start of CEventThread::RunThread() Name: %s"), m_threadName));

	m_threadRunning = true;
	m_threadWasStarted = true;
	HANDLE *pHandleArray = new HANDLE[m_eventMap.size()];

	int indexPos = 0;
	for(EventMapType::iterator it = m_eventMap.begin(); it != m_eventMap.end(); it++)
	{
		pHandleArray[indexPos] = it->first;
		indexPos++;
	}

	SetEvent(m_hEvt);
	ResetEvent(m_hEvt);

	while(m_exitThread == false)
	{
		DWORD event = WaitForMultipleObjects((DWORD)m_eventMap.size(), pHandleArray, FALSE, m_waitTimeout);

		if(event == WAIT_FAILED)
		{
			LPVOID lpMsgBuf = NULL;
			DWORD dwErr = GetLastError();
			FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
							FORMAT_MESSAGE_FROM_SYSTEM |
							FORMAT_MESSAGE_IGNORE_INSERTS,
							NULL,
							dwErr,
							MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
							(LPTSTR) &lpMsgBuf,
							0,
							NULL);

			ASSERT(!lpMsgBuf);
			LocalFree(lpMsgBuf);
		}
		else if(event == WAIT_TIMEOUT)
		{
			OnTimeOut(m_param);
		}
		else
		{
			HANDLE firedHandle = pHandleArray[event - WAIT_OBJECT_0];
			int eventId = m_eventMap[firedHandle];
			if(eventId == EXIT_EVENT)
			{				
				break;
			}
			else
			{
				Log(StrF(_T("Start of CEventThread::RunThread() - OnEvent %d - Name %s"), eventId, m_threadName));
				OnEvent(eventId, m_param);
				Log(StrF(_T("End of CEventThread::RunThread() - OnEvent %d - Name: %d"), eventId, m_threadName));
			}
		}
	}

	UndoFireEvent(EXIT_EVENT);

	SetEvent(m_hEvt);

	Log(StrF(_T("End of CEventThread::RunThread() Name: %s"), m_threadName));

	m_threadRunning = false;
}
Beispiel #17
0
void NONS_Event::reset(){
#if NONS_SYS_WINDOWS
	ResetEvent(this->event);
#endif
}
Beispiel #18
0
int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
	HWND _hAfxWnd = ::FindWindow("TAfxWForm", NULL);
	if (_hAfxWnd == INVALID_HANDLE_VALUE) {
		_hAfxWnd = ::FindWindow("TAfxForm", NULL);
		if (_hAfxWnd == INVALID_HANDLE_VALUE) {
			return -1;
		}
	}

	BOOL bFirstExec = FALSE;
	HANDLE hEvent = OpenEvent(EVENT_ALL_ACCESS, TRUE, __AFXVIM_EVENT__);
	if (hEvent == NULL) {
		bFirstExec = TRUE;
		hEvent = CreateEvent(NULL, FALSE, FALSE, __AFXVIM_EVENT__);
	}

	// 2011.10.29 共有メモリ上に設定を持つ
	int *smode = NULL;
	HANDLE hShare = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
			0, 32, __AFXVIM_SHAREDMEM__);
	if (hShare != NULL) {
		smode = (int*)::MapViewOfFile(hShare, FILE_MAP_WRITE, 0, 0, 32);
		if (bFirstExec) {
			memset(smode, 0, 32);
		}
	}

	PROCESS_INFORMATION pi;
	STARTUPINFO si;

	ZeroMemory(&si,sizeof(si));
	si.cb=sizeof(si);

	char cmd[256];
	if (bFirstExec) {
		sprintf(cmd, 
				"%s --windowid 0x%08x --servername afxvim --cmd \":silent set go+=C\"",
				lpCmdLine,
				_hAfxWnd);
	} else {
		char *sep = strstr(lpCmdLine, "gvim.exe");
		if (sep != NULL && strlen(sep+8) > 0 ) {
			sep += 8;
			sprintf(cmd, 
					"%s --servername afxvim --remote-tab-silent %s",
					lpCmdLine, sep);
		} else {
			if ((smode != NULL) && (smode[0] != NULL)) {
				ShowWindow((HWND)smode[0], SW_RESTORE);
				::UnmapViewOfFile(smode);
				::CloseHandle(hShare);
				::CloseHandle(hEvent);
				return 0;
			}
			sprintf(cmd,
					"%s --servername afxvim --remote-tab-silent __dummy__", lpCmdLine);
		}
	}

	if (!CreateProcess(
			NULL,
			cmd,
			NULL,
			NULL,
			FALSE,
			NORMAL_PRIORITY_CLASS,
			NULL,
			NULL,
			&si,
			&pi)) {
		::UnmapViewOfFile(smode);
		::CloseHandle(hShare);
		::CloseHandle(hEvent);
		::MessageBox(NULL, "err", "execute command error.", MB_OK);
		return -1;
	}

	_hVimWnd = (HWND)INVALID_HANDLE_VALUE;
	_vimPid = pi.hProcess;

	if (!bFirstExec) {
		SetEvent(hEvent);
	} else {
		// 2011.05.24 0.2.0 入力可能になるまで待つ
		::WaitForInputIdle(pi.hProcess, INFINITE);

		// 2011.05.02 0.1.1 afxckwが起動していたら非表示にする
		::EnumChildWindows(_hAfxWnd, EnumChildProc4Ckw, NULL);
		if (_hWndAfxCkw != NULL) {
			ShowWindow(_hWndAfxCkw, SW_HIDE);
		}

		RECT rect;
		RECT vimRect;
		RECT rectAfx;
		POINT vimLeftTopPoint;
		memset(&rectAfx, 0, sizeof(rectAfx));

		BOOL bFirstIconic = TRUE;
		DWORD dwExCode;
		while (1) {
			if (_hVimWnd == INVALID_HANDLE_VALUE || _hVimWnd == 0) {
				EnumChildWindows(_hAfxWnd, EnumChildProc , 0);
				if (_hVimWnd != NULL) {
					smode[0] = (int)_hVimWnd;
				}
			}
			dwExCode = WaitForSingleObject(pi.hProcess, 300);
			if (dwExCode == WAIT_TIMEOUT) {
				if (IsIconic(_hVimWnd)) {
					if (bFirstIconic == TRUE) {
						SetFocusOtherProcess(_hAfxWnd);
						bFirstIconic = FALSE;
					}
					if (WaitForSingleObject(hEvent, 0) == WAIT_OBJECT_0) {
						rectAfx.left = -100;
						ResetEvent(hEvent);
					}
				} else {
					bFirstIconic = TRUE;
					HWND active = ::GetForegroundWindow();
					if (active == _hAfxWnd) {
						if (_hVimWnd != INVALID_HANDLE_VALUE) {
							SetFocusOtherProcess(_hVimWnd);
						}
					}

					// 2011.05.12 vimにフォーカスが移っているならafxを最前面に移動
					/*
					if (active == _hVimWnd) {
						::SetFocusOtherProcess(_hAfxWnd, _hVimWnd);
					}
					*/

					// 2011.10.23 vimの位置監視
					::GetWindowRect(_hVimWnd, &vimRect);
					vimLeftTopPoint.x = vimRect.left;
					vimLeftTopPoint.y = vimRect.top;
					::ScreenToClient(_hAfxWnd, &vimLeftTopPoint);
					if (vimLeftTopPoint.x != 0 || vimLeftTopPoint.y != 0) {
						::SetWindowPos( _hVimWnd, HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE);
					}

					::GetClientRect(_hAfxWnd, &rect);
					if (( rect.right - rect.left) != ( rectAfx.right - rectAfx.left ) || 
						( rect.bottom - rect.top) != ( rectAfx.bottom - rectAfx.top ) ) {
						::SetWindowPos( _hVimWnd, HWND_TOP, 0, 0, rect.right, rect.bottom, 0);
						rectAfx = rect;
					}
				}

				continue;
			} else  {
				break;
			}
		}

		// 2011.05.02 0.1.1 隠していたafxckwを表示にする。
		if (_hWndAfxCkw != INVALID_HANDLE_VALUE) {
			ShowWindow(_hWndAfxCkw, SW_SHOW);
		}

		// 2011.05.10 終了時はあふwにフォーカスを戻す
		SetFocusOtherProcess(_hAfxWnd);
	}

	::UnmapViewOfFile(smode);
	::CloseHandle(hShare);
	::CloseHandle(pi.hProcess);
	::CloseHandle(pi.hThread);
	::CloseHandle(hEvent);

	return 0;
}
Beispiel #19
0
static ALCboolean DSoundResetPlayback(ALCdevice *device)
{
    DSoundPlaybackData *data = (DSoundPlaybackData*)device->ExtraData;
    DSBUFFERDESC DSBDescription;
    WAVEFORMATEXTENSIBLE OutputType;
    DWORD speakers;
    HRESULT hr;

    memset(&OutputType, 0, sizeof(OutputType));

    if(data->DSnotify)
        IDirectSoundNotify_Release(data->DSnotify);
    data->DSnotify = NULL;
    if(data->DSsbuffer)
        IDirectSoundBuffer_Release(data->DSsbuffer);
    data->DSsbuffer = NULL;
    if(data->DSpbuffer != NULL)
        IDirectSoundBuffer_Release(data->DSpbuffer);
    data->DSpbuffer = NULL;

    switch(device->FmtType)
    {
        case DevFmtByte:
            device->FmtType = DevFmtUByte;
            break;
        case DevFmtFloat:
            if((device->Flags&DEVICE_SAMPLE_TYPE_REQUEST))
                break;
            /* fall-through */
        case DevFmtUShort:
            device->FmtType = DevFmtShort;
            break;
        case DevFmtUInt:
            device->FmtType = DevFmtInt;
            break;
        case DevFmtUByte:
        case DevFmtShort:
        case DevFmtInt:
            break;
    }

    hr = IDirectSound_GetSpeakerConfig(data->DS, &speakers);
    if(SUCCEEDED(hr))
    {
        if(!(device->Flags&DEVICE_CHANNELS_REQUEST))
        {
            speakers = DSSPEAKER_CONFIG(speakers);
            if(speakers == DSSPEAKER_MONO)
                device->FmtChans = DevFmtMono;
            else if(speakers == DSSPEAKER_STEREO || speakers == DSSPEAKER_HEADPHONE)
                device->FmtChans = DevFmtStereo;
            else if(speakers == DSSPEAKER_QUAD)
                device->FmtChans = DevFmtQuad;
            else if(speakers == DSSPEAKER_5POINT1)
                device->FmtChans = DevFmtX51;
            else if(speakers == DSSPEAKER_7POINT1)
                device->FmtChans = DevFmtX71;
            else
                ERR("Unknown system speaker config: 0x%lx\n", speakers);
        }

        switch(device->FmtChans)
        {
            case DevFmtMono:
                OutputType.dwChannelMask = SPEAKER_FRONT_CENTER;
                break;
            case DevFmtStereo:
                OutputType.dwChannelMask = SPEAKER_FRONT_LEFT |
                                           SPEAKER_FRONT_RIGHT;
                break;
            case DevFmtQuad:
                OutputType.dwChannelMask = SPEAKER_FRONT_LEFT |
                                           SPEAKER_FRONT_RIGHT |
                                           SPEAKER_BACK_LEFT |
                                           SPEAKER_BACK_RIGHT;
                break;
            case DevFmtX51:
                OutputType.dwChannelMask = SPEAKER_FRONT_LEFT |
                                           SPEAKER_FRONT_RIGHT |
                                           SPEAKER_FRONT_CENTER |
                                           SPEAKER_LOW_FREQUENCY |
                                           SPEAKER_BACK_LEFT |
                                           SPEAKER_BACK_RIGHT;
                break;
            case DevFmtX51Side:
                OutputType.dwChannelMask = SPEAKER_FRONT_LEFT |
                                           SPEAKER_FRONT_RIGHT |
                                           SPEAKER_FRONT_CENTER |
                                           SPEAKER_LOW_FREQUENCY |
                                           SPEAKER_SIDE_LEFT |
                                           SPEAKER_SIDE_RIGHT;
                break;
            case DevFmtX61:
                OutputType.dwChannelMask = SPEAKER_FRONT_LEFT |
                                           SPEAKER_FRONT_RIGHT |
                                           SPEAKER_FRONT_CENTER |
                                           SPEAKER_LOW_FREQUENCY |
                                           SPEAKER_BACK_CENTER |
                                           SPEAKER_SIDE_LEFT |
                                           SPEAKER_SIDE_RIGHT;
                break;
            case DevFmtX71:
                OutputType.dwChannelMask = SPEAKER_FRONT_LEFT |
                                           SPEAKER_FRONT_RIGHT |
                                           SPEAKER_FRONT_CENTER |
                                           SPEAKER_LOW_FREQUENCY |
                                           SPEAKER_BACK_LEFT |
                                           SPEAKER_BACK_RIGHT |
                                           SPEAKER_SIDE_LEFT |
                                           SPEAKER_SIDE_RIGHT;
                break;
        }

retry_open:
        hr = S_OK;
        OutputType.Format.wFormatTag = WAVE_FORMAT_PCM;
        OutputType.Format.nChannels = ChannelsFromDevFmt(device->FmtChans);
        OutputType.Format.wBitsPerSample = BytesFromDevFmt(device->FmtType) * 8;
        OutputType.Format.nBlockAlign = OutputType.Format.nChannels*OutputType.Format.wBitsPerSample/8;
        OutputType.Format.nSamplesPerSec = device->Frequency;
        OutputType.Format.nAvgBytesPerSec = OutputType.Format.nSamplesPerSec*OutputType.Format.nBlockAlign;
        OutputType.Format.cbSize = 0;
    }

    if(OutputType.Format.nChannels > 2 || device->FmtType == DevFmtFloat)
    {
        OutputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
        OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample;
        OutputType.Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
        if(device->FmtType == DevFmtFloat)
            OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
        else
            OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;

        if(data->DSpbuffer)
            IDirectSoundBuffer_Release(data->DSpbuffer);
        data->DSpbuffer = NULL;
    }
    else
    {
        if(SUCCEEDED(hr))
        {
            memset(&DSBDescription,0,sizeof(DSBUFFERDESC));
            DSBDescription.dwSize=sizeof(DSBUFFERDESC);
            DSBDescription.dwFlags=DSBCAPS_PRIMARYBUFFER;
            hr = IDirectSound_CreateSoundBuffer(data->DS, &DSBDescription, &data->DSpbuffer, NULL);
        }
        if(SUCCEEDED(hr))
            hr = IDirectSoundBuffer_SetFormat(data->DSpbuffer,&OutputType.Format);
    }

    if(SUCCEEDED(hr))
    {
        if(device->NumUpdates > MAX_UPDATES)
        {
            device->UpdateSize = (device->UpdateSize*device->NumUpdates +
                                  MAX_UPDATES-1) / MAX_UPDATES;
            device->NumUpdates = MAX_UPDATES;
        }

        memset(&DSBDescription,0,sizeof(DSBUFFERDESC));
        DSBDescription.dwSize=sizeof(DSBUFFERDESC);
        DSBDescription.dwFlags=DSBCAPS_CTRLPOSITIONNOTIFY|DSBCAPS_GETCURRENTPOSITION2|DSBCAPS_GLOBALFOCUS;
        DSBDescription.dwBufferBytes=device->UpdateSize * device->NumUpdates *
                                     OutputType.Format.nBlockAlign;
        DSBDescription.lpwfxFormat=&OutputType.Format;
        hr = IDirectSound_CreateSoundBuffer(data->DS, &DSBDescription, &data->DSsbuffer, NULL);
        if(FAILED(hr) && device->FmtType == DevFmtFloat)
        {
            device->FmtType = DevFmtShort;
            goto retry_open;
        }
    }

    if(SUCCEEDED(hr))
    {
        hr = IDirectSoundBuffer_QueryInterface(data->DSsbuffer, &IID_IDirectSoundNotify, (LPVOID *)&data->DSnotify);
        if(SUCCEEDED(hr))
        {
            DSBPOSITIONNOTIFY notifies[MAX_UPDATES];
            ALuint i;

            for(i = 0;i < device->NumUpdates;++i)
            {
                notifies[i].dwOffset = i * device->UpdateSize *
                                       OutputType.Format.nBlockAlign;
                notifies[i].hEventNotify = data->NotifyEvent;
            }
            if(IDirectSoundNotify_SetNotificationPositions(data->DSnotify, device->NumUpdates, notifies) != DS_OK)
                hr = E_FAIL;
        }
    }

    if(FAILED(hr))
    {
        if(data->DSnotify != NULL)
            IDirectSoundNotify_Release(data->DSnotify);
        data->DSnotify = NULL;
        if(data->DSsbuffer != NULL)
            IDirectSoundBuffer_Release(data->DSsbuffer);
        data->DSsbuffer = NULL;
        if(data->DSpbuffer != NULL)
            IDirectSoundBuffer_Release(data->DSpbuffer);
        data->DSpbuffer = NULL;
        return ALC_FALSE;
    }

    ResetEvent(data->NotifyEvent);
    SetDefaultWFXChannelOrder(device);

    return ALC_TRUE;
}
Beispiel #20
0
static PyObject *
semlock_acquire(SemLockObject *self, PyObject *args, PyObject *kwds)
{
    int blocking = 1;
    double timeout;
    PyObject *timeout_obj = Py_None;
    DWORD res, full_msecs, msecs, start, ticks;

    static char *kwlist[] = {"block", "timeout", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO", kwlist,
                                     &blocking, &timeout_obj))
        return NULL;

    /* calculate timeout */
    if (!blocking) {
        full_msecs = 0;
    } else if (timeout_obj == Py_None) {
        full_msecs = INFINITE;
    } else {
        timeout = PyFloat_AsDouble(timeout_obj);
        if (PyErr_Occurred())
            return NULL;
        timeout *= 1000.0;      /* convert to millisecs */
        if (timeout < 0.0) {
            timeout = 0.0;
        } else if (timeout >= 0.5 * INFINITE) { /* 25 days */
            PyErr_SetString(PyExc_OverflowError,
                            "timeout is too large");
            return NULL;
        }
        full_msecs = (DWORD)(timeout + 0.5);
    }

    /* check whether we already own the lock */
    if (self->kind == RECURSIVE_MUTEX && ISMINE(self)) {
        ++self->count;
        Py_RETURN_TRUE;
    }

    /* check whether we can acquire without blocking */
    if (WaitForSingleObject(self->handle, 0) == WAIT_OBJECT_0) {
        self->last_tid = GetCurrentThreadId();
        ++self->count;
        Py_RETURN_TRUE;
    }

    msecs = full_msecs;
    start = GetTickCount();

    for ( ; ; ) {
        HANDLE handles[2] = {self->handle, sigint_event};

        /* do the wait */
        Py_BEGIN_ALLOW_THREADS
        ResetEvent(sigint_event);
        res = WaitForMultipleObjects(2, handles, FALSE, msecs);
        Py_END_ALLOW_THREADS

        /* handle result */
        if (res != WAIT_OBJECT_0 + 1)
            break;

        /* got SIGINT so give signal handler a chance to run */
        Sleep(1);

        /* if this is main thread let KeyboardInterrupt be raised */
        if (PyErr_CheckSignals())
            return NULL;

        /* recalculate timeout */
        if (msecs != INFINITE) {
            ticks = GetTickCount();
            if ((DWORD)(ticks - start) >= full_msecs)
                Py_RETURN_FALSE;
            msecs = full_msecs - (ticks - start);
        }
    }

    /* handle result */
    switch (res) {
    case WAIT_TIMEOUT:
        Py_RETURN_FALSE;
    case WAIT_OBJECT_0:
        self->last_tid = GetCurrentThreadId();
        ++self->count;
        Py_RETURN_TRUE;
    case WAIT_FAILED:
        return PyErr_SetFromWindowsErr(0);
    default:
        PyErr_Format(PyExc_RuntimeError, "WaitForSingleObject() or "
                     "WaitForMultipleObjects() gave unrecognized "
                     "value %d", res);
        return NULL;
    }
}
//-------------------------------------------------------------------------------------
bool TPThread::onWaitCondSignal(void)
{
#if KBE_PLATFORM == PLATFORM_WIN32
	if(threadWaitSecond_ <= 0)
	{
		state_ = THREAD_STATE_SLEEP;
		WaitForSingleObject(cond_, INFINITE); 
		ResetEvent(cond_);
	}
	else
	{
		state_ = THREAD_STATE_SLEEP;
		DWORD ret = WaitForSingleObject(cond_, threadWaitSecond_ * 1000);
		ResetEvent(cond_);

		// 如果是因为超时了, 说明这个线程很久没有被用到, 我们应该注销这个线程。
		// 通知ThreadPool注销自己
		if (ret == WAIT_TIMEOUT)
		{																	
			threadPool_->removeHangThread(this);							
			return false;
		}
		else if(ret != WAIT_OBJECT_0)
		{
			ERROR_MSG(fmt::format("TPThread::onWaitCondSignal: WaitForSingleObject is error, ret={0}\n", 
				ret));
		}
	}	
#else		
	if(threadWaitSecond_ <= 0)
	{
		lock();
		state_ = THREAD_STATE_SLEEP;
		pthread_cond_wait(&cond_, &mutex_);
		unlock();
	}
	else
	{
		struct timeval now;
		struct timespec timeout;			
		gettimeofday(&now, NULL);
		timeout.tv_sec = now.tv_sec + threadWaitSecond_;
		timeout.tv_nsec = now.tv_usec * 1000;
		
		lock();
		state_ = THREAD_STATE_SLEEP;
		int ret = pthread_cond_timedwait(&cond_, &mutex_, &timeout);
		unlock();
		
		// 如果是因为超时了, 说明这个线程很久没有被用到, 我们应该注销这个线程。
		if (ret == ETIMEDOUT)
		{
			// 通知ThreadPool注销自己
			threadPool_->removeHangThread(this);
			return false;
		}
		else if(ret != 0)
		{
			ERROR_MSG(fmt::format("TPThread::onWaitCondSignal: pthread_cond_timedwait is error, {0}\n", 
				kbe_strerror()));
		}
	}
#endif
	return true;
}
void
ngx_master_process_cycle(ngx_cycle_t *cycle)
{
    u_long      nev, ev, timeout;
    ngx_err_t   err;
    ngx_int_t   n;
    ngx_msec_t  timer;
    ngx_uint_t  live;
    HANDLE      events[MAXIMUM_WAIT_OBJECTS];

    ngx_process_init(cycle);

    ngx_sprintf((u_char *) ngx_master_process_event_name,
                "ngx_master_%s%Z", ngx_unique);

    if (ngx_process == NGX_PROCESS_WORKER) {

        if (FreeConsole() == 0) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                "FreeConsole() failed");
        }

        ngx_worker_process_cycle(cycle, ngx_master_process_event_name);
        return;
    }

    ngx_log_debug0(NGX_LOG_DEBUG_CORE, cycle->log, 0, "master started");

    ngx_console_init(cycle);

    SetEnvironmentVariable("ngx_unique", ngx_unique);

    ngx_master_process_event = CreateEvent(NULL, 1, 0,
                                           ngx_master_process_event_name);
    if (ngx_master_process_event == NULL) {
        ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                      "CreateEvent(\"%s\") failed",
                      ngx_master_process_event_name);
        exit(2);
    }

    if (ngx_create_signal_events(cycle) != NGX_OK) {
        exit(2);
    }

    ngx_sprintf((u_char *) ngx_cache_manager_mutex_name,
                "ngx_cache_manager_mutex_%s%Z", ngx_unique);

    ngx_cache_manager_mutex = CreateMutex(NULL, 0,
                                          ngx_cache_manager_mutex_name);
    if (ngx_cache_manager_mutex == NULL) {
        ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                   "CreateMutex(\"%s\") failed", ngx_cache_manager_mutex_name);
        exit(2);
    }


    events[0] = ngx_stop_event;
    events[1] = ngx_quit_event;
    events[2] = ngx_reopen_event;
    events[3] = ngx_reload_event;

//    ngx_close_listening_sockets(cycle);
    ngx_set_inherited_listen_sockets(cycle);

    if (ngx_start_worker_processes(cycle, NGX_PROCESS_RESPAWN) == 0) {
        exit(2);
    }

    timer = 0;
    timeout = INFINITE;

    for ( ;; ) {

        nev = 4;
        for (n = 0; n < ngx_last_process; n++) {
            if (ngx_processes[n].handle) {
                events[nev++] = ngx_processes[n].handle;
            }
        }

        if (timer) {
            timeout = timer > ngx_current_msec ? timer - ngx_current_msec : 0;
        }

        ev = WaitForMultipleObjects(nev, events, 0, timeout);

        err = ngx_errno;
        ngx_time_update();

        ngx_log_debug1(NGX_LOG_DEBUG_CORE, cycle->log, 0,
                       "master WaitForMultipleObjects: %ul", ev);

        if (ev == WAIT_OBJECT_0) {
            ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "exiting");

            if (ResetEvent(ngx_stop_event) == 0) {
                ngx_log_error(NGX_LOG_ALERT, cycle->log, 0,
                              "ResetEvent(\"%s\") failed", ngx_stop_event_name);
            }

            if (timer == 0) {
                timer = ngx_current_msec + 5000;
            }

            ngx_terminate = 1;
            ngx_quit_worker_processes(cycle, 0);

            continue;
        }

        if (ev == WAIT_OBJECT_0 + 1) {
            ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "shutting down");

            if (ResetEvent(ngx_quit_event) == 0) {
                ngx_log_error(NGX_LOG_ALERT, cycle->log, 0,
                              "ResetEvent(\"%s\") failed", ngx_quit_event_name);
            }

            ngx_quit = 1;
            ngx_quit_worker_processes(cycle, 0);

            continue;
        }

        if (ev == WAIT_OBJECT_0 + 2) {
            ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "reopening logs");

            if (ResetEvent(ngx_reopen_event) == 0) {
                ngx_log_error(NGX_LOG_ALERT, cycle->log, 0,
                              "ResetEvent(\"%s\") failed",
                              ngx_reopen_event_name);
            }

            ngx_reopen_files(cycle, -1);
            ngx_reopen_worker_processes(cycle);

            continue;
        }

        if (ev == WAIT_OBJECT_0 + 3) {
            ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "reconfiguring");

            if (ResetEvent(ngx_reload_event) == 0) {
                ngx_log_error(NGX_LOG_ALERT, cycle->log, 0,
                              "ResetEvent(\"%s\") failed",
                              ngx_reload_event_name);
            }

			
/* 这个方案暂时已经可用了。不好的地方就是不能重启端口。如果端口配置有变化,就会有毛病。
			cycle = ngx_init_cycle(cycle);
			if (cycle == NULL) {
				cycle = (ngx_cycle_t *) ngx_cycle;
				continue;
			}

			ngx_cycle = cycle;

			//ngx_close_listening_sockets(cycle);

			if (ngx_start_worker_processes(cycle, NGX_PROCESS_JUST_RESPAWN)) {
				ngx_quit_worker_processes(cycle, 1);
			}
*/

			/*---code 这里代码是先退掉所有工作进程,然后关闭listen 端口,再reload 配置,重启端口,重启工作进程*/
			ngx_quit_worker_processes(cycle, 0);
			ngx_close_listening_sockets(cycle);

			ngx_msleep(500);

			cycle = ngx_init_cycle(cycle);
			if (cycle == NULL) {
				cycle = (ngx_cycle_t *) ngx_cycle;
				continue;
			}

			ngx_cycle = cycle;

			if (ngx_open_listening_sockets(cycle) != NGX_OK) {
				ngx_log_error(NGX_LOG_ALERT, cycle->log, err,
					"reload ngx_open_listening_sockets() failed");

				ngx_quit = 1;
				continue;
			}

			ngx_set_inherited_listen_sockets(cycle);

			if (ngx_start_worker_processes(cycle, NGX_PROCESS_RESPAWN) == 0) {
				exit(2);
			}
			/*---code --- end*/

            continue;
        }

        if (ev > WAIT_OBJECT_0 + 3 && ev < WAIT_OBJECT_0 + nev) {

            ngx_log_debug0(NGX_LOG_DEBUG_CORE, cycle->log, 0, "reap worker");

            live = ngx_reap_worker(cycle, events[ev]);

            if (!live && (ngx_terminate || ngx_quit)) {
                ngx_master_process_exit(cycle);
            }

            continue;
        }

        if (ev == WAIT_TIMEOUT) {
            ngx_terminate_worker_processes(cycle);

            ngx_master_process_exit(cycle);
        }

        if (ev == WAIT_FAILED) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, err,
                          "WaitForMultipleObjects() failed");

            continue;
        }

        ngx_log_error(NGX_LOG_ALERT, cycle->log, 0,
            "WaitForMultipleObjects() returned unexpected value %ul", ev);
    }
}
Beispiel #23
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];    
    
    
    /* 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);
    }
    
    /* 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);

    /* 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 = WSASendTo( testSockets[0],
                       &(wsaSendBuf),
                       dwNbrOfBuf,
                       &dwNbrOfByteSent,
                       dwSendFlags,
                       (struct sockaddr FAR *)&mySockaddr,
                       sizeof(mySockaddr),
                       &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 
               dwNbrOfByteSent should be 255
            */
            if(dwNbrOfByteSent!=255)
            {
                Trace("Client error, Unexpected failure: "
                      "number of byte sent by WSASend to is %d"
                      ", expected 255.\n",dwNbrOfByteSent);

                /* Do some cleanup */

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

                threadExitCode=THREAD_FAIL;

                ExitThread(0);
            }
            /* Reset the 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);
        }        
    }   
    
    
    if(!CloseEventHandle(hWriteEvent))
    {
        /* Do some cleanup */
        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);
    }    

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

        ExitThread(0);
    }

    threadExitCode=THREAD_SUCCESS;

    ExitThread(0);    
} 
static void
ngx_worker_process_cycle(ngx_cycle_t *cycle, char *mevn)
{
    char        wtevn[NGX_PROCESS_SYNC_NAME];
    char        wqevn[NGX_PROCESS_SYNC_NAME];
    char        wroevn[NGX_PROCESS_SYNC_NAME];
    HANDLE      mev, events[3];
    u_long      nev, ev;
    ngx_err_t   err;
    ngx_tid_t   wtid, cmtid, cltid;
    ngx_log_t  *log;

    log = cycle->log;

    ngx_log_debug0(NGX_LOG_DEBUG_CORE, log, 0, "worker started");

    ngx_sprintf((u_char *) wtevn, "ngx_worker_term_%ul%Z", ngx_pid);
    events[0] = CreateEvent(NULL, 1, 0, wtevn);
    if (events[0] == NULL) {
        ngx_log_error(NGX_LOG_ALERT, log, ngx_errno,
                      "CreateEvent(\"%s\") failed", wtevn);
        goto failed;
    }

    ngx_sprintf((u_char *) wqevn, "ngx_worker_quit_%ul%Z", ngx_pid);
    events[1] = CreateEvent(NULL, 1, 0, wqevn);
    if (events[1] == NULL) {
        ngx_log_error(NGX_LOG_ALERT, log, ngx_errno,
                      "CreateEvent(\"%s\") failed", wqevn);
        goto failed;
    }

    ngx_sprintf((u_char *) wroevn, "ngx_worker_reopen_%ul%Z", ngx_pid);
    events[2] = CreateEvent(NULL, 1, 0, wroevn);
    if (events[2] == NULL) {
        ngx_log_error(NGX_LOG_ALERT, log, ngx_errno,
                      "CreateEvent(\"%s\") failed", wroevn);
        goto failed;
    }

    mev = OpenEvent(EVENT_MODIFY_STATE, 0, mevn);
    if (mev == NULL) {
        ngx_log_error(NGX_LOG_ALERT, log, ngx_errno,
                      "OpenEvent(\"%s\") failed", mevn);
        goto failed;
    }

    if (SetEvent(mev) == 0) {
        ngx_log_error(NGX_LOG_ALERT, log, ngx_errno,
                      "SetEvent(\"%s\") failed", mevn);
        goto failed;
    }


    ngx_sprintf((u_char *) ngx_cache_manager_mutex_name,
                "ngx_cache_manager_mutex_%s%Z", ngx_unique);

    ngx_cache_manager_mutex = OpenMutex(SYNCHRONIZE, 0,
                                        ngx_cache_manager_mutex_name);
    if (ngx_cache_manager_mutex == NULL) {
        ngx_log_error(NGX_LOG_ALERT, log, ngx_errno,
                      "OpenMutex(\"%s\") failed", ngx_cache_manager_mutex_name);
        goto failed;
    }

    ngx_cache_manager_event = CreateEvent(NULL, 1, 0, NULL);
    if (ngx_cache_manager_event == NULL) {
        ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                      "CreateEvent(\"ngx_cache_manager_event\") failed");
        goto failed;
    }


    if (ngx_create_thread(&wtid, ngx_worker_thread, NULL, log) != 0) {
        goto failed;
    }

    if (ngx_create_thread(&cmtid, ngx_cache_manager_thread, NULL, log) != 0) {
        goto failed;
    }

    if (ngx_create_thread(&cltid, ngx_cache_loader_thread, NULL, log) != 0) {
        goto failed;
    }

    for ( ;; ) {
        ev = WaitForMultipleObjects(3, events, 0, INFINITE);

        err = ngx_errno;
        ngx_time_update();

        ngx_log_debug1(NGX_LOG_DEBUG_CORE, log, 0,
                       "worker WaitForMultipleObjects: %ul", ev);

        if (ev == WAIT_OBJECT_0) {
            ngx_terminate = 1;
            ngx_log_error(NGX_LOG_NOTICE, log, 0, "exiting");

            if (ResetEvent(events[0]) == 0) {
                ngx_log_error(NGX_LOG_ALERT, log, 0,
                              "ResetEvent(\"%s\") failed", wtevn);
            }

            break;
        }

        if (ev == WAIT_OBJECT_0 + 1) {
            ngx_quit = 1;
            ngx_log_error(NGX_LOG_NOTICE, log, 0, "gracefully shutting down");
            break;
        }

        if (ev == WAIT_OBJECT_0 + 2) {
            ngx_reopen = 1;
            ngx_log_error(NGX_LOG_NOTICE, log, 0, "reopening logs");

            if (ResetEvent(events[2]) == 0) {
                ngx_log_error(NGX_LOG_ALERT, log, 0,
                              "ResetEvent(\"%s\") failed", wroevn);
            }

            continue;
        }

        if (ev == WAIT_FAILED) {
            ngx_log_error(NGX_LOG_ALERT, log, err,
                          "WaitForMultipleObjects() failed");

            goto failed;
        }
    }

    /* wait threads */

    if (SetEvent(ngx_cache_manager_event) == 0) {
        ngx_log_error(NGX_LOG_ALERT, log, ngx_errno,
                      "SetEvent(\"ngx_cache_manager_event\") failed");
    }

    events[1] = wtid;
    events[2] = cmtid;

    nev = 3;

    for ( ;; ) {
        ev = WaitForMultipleObjects(nev, events, 0, INFINITE);

        err = ngx_errno;
        ngx_time_update();

        ngx_log_debug1(NGX_LOG_DEBUG_CORE, log, 0,
                       "worker exit WaitForMultipleObjects: %ul", ev);

        if (ev == WAIT_OBJECT_0) {
            break;
        }

        if (ev == WAIT_OBJECT_0 + 1) {
            if (nev == 2) {
                break;
            }

            events[1] = events[2];
            nev = 2;
            continue;
        }

        if (ev == WAIT_OBJECT_0 + 2) {
            nev = 2;
            continue;
        }

        if (ev == WAIT_FAILED) {
            ngx_log_error(NGX_LOG_ALERT, log, err,
                          "WaitForMultipleObjects() failed");
            break;
        }
    }

    ngx_close_handle(ngx_cache_manager_event);
    ngx_close_handle(events[0]);
    ngx_close_handle(events[1]);
    ngx_close_handle(events[2]);
    ngx_close_handle(mev);

    ngx_worker_process_exit(cycle);

failed:

    exit(2);
}
Beispiel #25
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);    
} 
static int
evthread_win32_cond_wait(void *_cond, void *_lock, const struct timeval *tv)
{
    struct evthread_win32_cond *cond = _cond;
    CRITICAL_SECTION *lock = _lock;
    int generation_at_start;
    int waiting = 1;
    int result = -1;
    DWORD ms = INFINITE, ms_orig = INFINITE, startTime, endTime;
    if (tv)
        ms_orig = ms = evutil_tv_to_msec(tv);

    EnterCriticalSection(&cond->lock);
    ++cond->n_waiting;
    generation_at_start = cond->generation;
    LeaveCriticalSection(&cond->lock);

    LeaveCriticalSection(lock);

    startTime = GetTickCount();
    do {
        DWORD res;
        res = WaitForSingleObject(cond->event, ms);
        EnterCriticalSection(&cond->lock);
        if (cond->n_to_wake &&
            cond->generation != generation_at_start) {
            --cond->n_to_wake;
            --cond->n_waiting;
            result = 0;
            waiting = 0;
            goto out;
        } else if (res != WAIT_OBJECT_0) {
            result = (res==WAIT_TIMEOUT) ? 1 : -1;
            --cond->n_waiting;
            waiting = 0;
            goto out;
        } else if (ms != INFINITE) {
            endTime = GetTickCount();
            if (startTime + ms_orig <= endTime) {
                result = 1; /* Timeout */
                --cond->n_waiting;
                waiting = 0;
                goto out;
            } else {
                ms = startTime + ms_orig - endTime;
            }
        }
        /* If we make it here, we are still waiting. */
        if (cond->n_to_wake == 0) {
            /* There is nobody else who should wake up; reset
             * the event. */
            ResetEvent(cond->event);
        }
    out:
        LeaveCriticalSection(&cond->lock);
    } while (waiting);

    EnterCriticalSection(lock);

    EnterCriticalSection(&cond->lock);
    if (!cond->n_waiting)
        ResetEvent(cond->event);
    LeaveCriticalSection(&cond->lock);

    return result;
}
Beispiel #27
0
int cmd_run(connection_context *c)
{
    char buf[256];
    int res = 0;
    int wres;
    char *cmdline;
    DWORD pipe_nr;

    cmdline = strchr(c->cmd, ' ');
    if (!cmdline) {
        goto finish;
    }
    ++cmdline;

    if (!get_token(c))
        return 0;

    pipe_nr = (GetCurrentProcessId() << 16) + (DWORD) c->conn_number;

    sprintf(buf, "\\\\.\\pipe\\" PIPE_NAME_IN, pipe_nr);
    c->pin = CreateNamedPipe(buf,
                             PIPE_ACCESS_DUPLEX,
                             PIPE_WAIT,
                             1,
                             BUFSIZE,
                             BUFSIZE,
                             NMPWAIT_USE_DEFAULT_WAIT,
                             &sa);
    if (c->pin == INVALID_HANDLE_VALUE) {
        hprintf(c->pipe, "error Cannot create in pipe(%s), error 0x%08X\n", buf, GetLastError());
        goto finishCloseToken;
    }

    sprintf(buf, "\\\\.\\pipe\\" PIPE_NAME_OUT, pipe_nr);
    c->pout = CreateNamedPipe(buf,
                              PIPE_ACCESS_DUPLEX,
                              PIPE_WAIT,
                              1,
                              BUFSIZE,
                              BUFSIZE,
                              NMPWAIT_USE_DEFAULT_WAIT,
                              &sa);
    if (c->pout == INVALID_HANDLE_VALUE) {
        hprintf(c->pipe, "error Cannot create out pipe(%s), error 0x%08X\n", buf, GetLastError());
        goto finishClosePin;
    }

    sprintf(buf, "\\\\.\\pipe\\" PIPE_NAME_ERR, pipe_nr);
    c->perr = CreateNamedPipe(buf,
                              PIPE_ACCESS_DUPLEX,
                              PIPE_WAIT,
                              1,
                              BUFSIZE,
                              BUFSIZE,
                              NMPWAIT_USE_DEFAULT_WAIT,
                              &sa);
    if (c->perr == INVALID_HANDLE_VALUE) {
        hprintf(c->pipe, "error Cannot create err pipe(%s), error 0x%08x\n", buf, GetLastError());
        goto finishClosePout;
    }

    /* Send handle to client (it will use it to connect pipes) */
    hprintf(c->pipe, CMD_STD_IO_ERR " %08X\n", pipe_nr);

    wres = ConnectNamedPipe(c->pin, NULL);
    if (!wres)
        wres = (GetLastError() == ERROR_PIPE_CONNECTED);
    if (!wres) {
        hprintf(c->pipe, "error ConnectNamedPipe(pin)\n");
        goto finishClosePerr;
    }

    wres = ConnectNamedPipe(c->pout, NULL);
    if (!wres)
        wres = (GetLastError() == ERROR_PIPE_CONNECTED);
    if (!wres) {
        hprintf(c->pipe, "error ConnectNamedPipe(pout)\n");
        goto finishDisconnectPin;
    }

    wres = ConnectNamedPipe(c->perr, NULL);
    if (!wres)
        wres = (GetLastError() == ERROR_PIPE_CONNECTED);
    if (!wres) {
        hprintf(c->pipe, "error ConnectNamedPipe(perr)\n");
        goto finishDisconnectPout;
    }

    SetHandleInformation(c->pin, HANDLE_FLAG_INHERIT, 1);
    SetHandleInformation(c->pout, HANDLE_FLAG_INHERIT, 1);
    SetHandleInformation(c->perr, HANDLE_FLAG_INHERIT, 1);

    SECURITY_ATTRIBUTES sattr;
    sattr.nLength = sizeof(SECURITY_ATTRIBUTES);
    sattr.bInheritHandle = TRUE;
    sattr.lpSecurityDescriptor = NULL;

    PROCESS_INFORMATION pi;
    ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));

    STARTUPINFO si;
    ZeroMemory(&si, sizeof(STARTUPINFO));
    si.cb = sizeof(STARTUPINFO);
    si.hStdInput = c->pin;
    si.hStdOutput = c->pout;
    si.hStdError = c->perr;
    si.dwFlags |= STARTF_USESTDHANDLES;

    if (CreateProcessAsUser(
                c->token,
                NULL,
                cmdline,	/* command line */
                NULL,	/* process security attributes */
                NULL,	/* primary thread security attributes */
                TRUE,	/* handles are inherited */
                0,	/* creation flags */
                NULL,	/* use parent's environment */
                NULL,	/* use parent's current directory */
                &si,	/* STARTUPINFO pointer */
                &pi))	/* receives PROCESS_INFORMATION */
    {
        HANDLE hlist[2] = {c->pipe->o.hEvent, pi.hProcess};
        DWORD ec;
        char str[1];

        if (!ResetEvent(c->pipe->o.hEvent))
            SvcDebugOut("ResetEvent error - %d\n", GetLastError());
        if (!ReadFile(c->pipe->h, str, 1, NULL, &c->pipe->o) && GetLastError() != ERROR_IO_PENDING)
            SvcDebugOut("ReadFile(control_pipe) error - %d\n", GetLastError());
        ec = WaitForMultipleObjects(2, hlist, FALSE, INFINITE);
        SvcDebugOut("WaitForMultipleObjects=%d\n", ec - WAIT_OBJECT_0);
        if (ec != WAIT_OBJECT_0)
            GetExitCodeProcess(pi.hProcess, &ec);
        else
            TerminateProcess(pi.hProcess, ec = 0x1234);
        FlushFileBuffers(c->pout);
        FlushFileBuffers(c->perr);
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
        hprintf(c->pipe, CMD_RETURN_CODE " %08X\n", ec);
    } else {
        hprintf(c->pipe, "error Creating process(%s) %d\n", cmdline, GetLastError());
    }

    DisconnectNamedPipe(c->perr);
finishDisconnectPout:
    DisconnectNamedPipe(c->pout);
finishDisconnectPin:
    DisconnectNamedPipe(c->pin);
finishClosePerr:
    CloseHandle(c->perr);
finishClosePout:
    CloseHandle(c->pout);
finishClosePin:
    CloseHandle(c->pin);
finishCloseToken:
    CloseHandle(c->token);
finish:
    return res;
}
//+ ----------------------------------------------------------------------------------------
int main(int argc, char* argv[])
{
	BYTE* pEvt;

	gpModuleName = GetProcessName(gModuleName, sizeof(gModuleName));

	if (gpModuleName == NULL)
		return -1;

	HANDLE hEventAppear = CreateEvent(NULL, FALSE, FALSE, NULL);
	if (hEventAppear == NULL)
		return -2;
	//+ ----------------------------------------------------------------------------------------
	//+ system test
#ifdef _check_system
	Log.AddToLog(L"Starting system interceptor check...\n");
	{
		CheckJob_System SystemJob(&gDrvEventList);
		if (false == SystemJob.Start())
		{
			Log.AddToLog(L"Can't start check system !");
			gDrvEventList.SetError(_ERR_DRVFAULT);
		}
		else
		{
			SystemJob.ChangeActiveStatus(true);
			
			//+ ----------------------------------------------------------------------------------------
			//+ open process
			HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId());
			if (hProcess != NULL)
			{
				Log.AddToLog(L"protection fault - process opened!");
				gDrvEventList.SetError(_ERR_DRVFAULT);
				CloseHandle(hProcess);
			}
			
			//+ ----------------------------------------------------------------------------------------
			//+ create process (ex)
			PROCESS_INFORMATION pi;
			STARTUPINFO si;
			
			ZeroMemory( &si, sizeof(si) );
			si.cb = sizeof(si);
			ZeroMemory( &pi, sizeof(pi) );
			
			WCHAR cmdline[1024];
			if (!ExpandEnvironmentStrings(L"\"%ComSpec%\" /C echo app launched!", cmdline, sizeof(cmdline)))
				gDrvEventList.SetError(_ERR_INTERNAL);
			else
			{
				if (CreateProcess(NULL, cmdline, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi))
				{
					Log.AddToLog(L"protection fault - process started!");
					gDrvEventList.SetError(_ERR_DRVFAULT);
					WaitForSingleObject(pi.hProcess,INFINITE);
				}
			}
			
			//+ ----------------------------------------------------------------------------------------
			//+ terminate process
			TerminateProcess((HANDLE) -1, -2);
			
			SystemJob.ChangeActiveStatus(false);
		}
		
		while ((pEvt = gDrvEventList.GetFirst()) != NULL)
		{
			Log.AddToLog((PEVENT_TRANSMIT) pEvt);
			gDrvEventList.Free(pEvt);
		}
	}
#endif

	//- end system test
	//- ----------------------------------------------------------------------------------------

	//+ ----------------------------------------------------------------------------------------
	//+ file test
#ifdef _check_file
	Log.AddToLog(L"Starting file interceptor check...\n");
	{

		CheckJob_File FileJob(&gDrvEventList);
		if (false == FileJob.Start())
		{
			Log.AddToLog(L"Can't start check file interceptor!");
			gDrvEventList.SetError(_ERR_DRVFAULT);
		}
		else
		{
			FileJob.SetAllowEvents(true);
			FileJob.ChangeActiveStatus(true);

	#define _testfilename			L"TestFile.tst"
	#define _testfilename_renamed	L"TestFile renamed.tst"
	#define _testfilename_create	L"TestFile check create.tst"

			HANDLE hTestFile = CreateFile(_testfilename, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
			if (hTestFile == INVALID_HANDLE_VALUE)
			{
				FileJob.ChangeActiveStatus(false);

				Log.AddToLog(L"Can't create file TestFile.tst for test");
				gDrvEventList.SetError(_ERR_DRVFAULT);

				FileJob.ChangeActiveStatus(true);
			}
			else
			{
				DWORD dwBytes;

				BYTE buf[1024];
				ZeroMemory(buf, sizeof(buf));

				WriteFile(hTestFile, buf, sizeof(buf), &dwBytes, NULL);
				if (dwBytes != sizeof(buf))
				{
					Log.AddToLog(L"!Write to TestFile.tst failed");
					gDrvEventList.SetError(_ERR_INTERNAL);
				}
				
				FlushFileBuffers(hTestFile);

				SetFilePointer(hTestFile, 0, NULL, FILE_BEGIN);

				ReadFile(hTestFile, buf, sizeof(buf), &dwBytes, NULL);
				if (dwBytes != sizeof(buf))
				{
					Log.AddToLog(L"!Read from TestFile.tst failed");
					gDrvEventList.SetError(_ERR_INTERNAL);
				}

				CloseHandle(hTestFile);
				
				MoveFile(_testfilename, _testfilename_renamed);

				DeleteFile(_testfilename_renamed);

				// check deny create file
				FileJob.SetAllowEvents(false);
				hTestFile = CreateFile(_testfilename_create, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, NULL);
				if (hTestFile != INVALID_HANDLE_VALUE)
				{
					Log.AddToLog(L"protection fault - file "_testfilename_create L" opened");
					gDrvEventList.SetError(_ERR_DRVFAULT);
					CloseHandle(hTestFile);
				}
			}
			
			FileJob.ChangeActiveStatus(false);

			Sleep(100);
		}

		while ((pEvt = gDrvEventList.GetFirst()) != NULL)
		{
			Log.AddToLog((PEVENT_TRANSMIT) pEvt);
			gDrvEventList.Free(pEvt);
		}
	}
#endif
	//- end files test
	//- ----------------------------------------------------------------------------------------

	//+ ----------------------------------------------------------------------------------------
	//+ registry
#ifdef _check_regestry
	Log.AddToLog(L"Starting registry interceptor check...\n");
	{
		CheckJob_Reg RegJob(&gDrvEventList);
		if (false == RegJob.Start())
		{
			Log.AddToLog(L"Can't start check file interceptor!");
			gDrvEventList.SetError(_ERR_DRVFAULT);
		}
		else
		{
			RegJob.SetAllowEvents(true);
			RegJob.ChangeActiveStatus(true);

			HKEY hKey = NULL;
			if (ERROR_SUCCESS == RegOpenKey(HKEY_CURRENT_USER, L"Software", &hKey))
			{
				DWORD type;
				DWORD cbData = 0;
				RegQueryValueEx(hKey, NULL, 0, &type, NULL, &cbData);

				RegCloseKey(hKey);

				//+ ----------------------------------------------------------------------------------------
				//+ enum
				{
					HKEY hKey;
					if(ERROR_SUCCESS == RegOpenKey(HKEY_CURRENT_USER, L"SOFTWARE", &hKey))
					{
						TCHAR SubkeyName[512];
						DWORD dwSubkeyName = sizeof(SubkeyName);
						
						DWORD dwIndex = 0;
						
						if (RegEnumKey(hKey, dwIndex, SubkeyName, dwSubkeyName) == ERROR_SUCCESS)
						{
							// empty if
						}
						
						RegCloseKey(hKey);
					}
				}

				//+ ----------------------------------------------------------------------------------------

			}
			
			RegJob.ChangeActiveStatus(false);
		}

		while ((pEvt = gDrvEventList.GetFirst()) != NULL)
		{
			Log.AddToLog((PEVENT_TRANSMIT) pEvt);
			gDrvEventList.Free(pEvt);
		}
	}
#endif
	//- end registry test
	//- ----------------------------------------------------------------------------------------

	//+ ----------------------------------------------------------------------------------------
	//+ filter's queue - add (top, bottom, position), enumerate, /*find*/, enable, disable, delete, reset
#ifdef _check_flt
	Log.AddToLog(L"Starting check filtering system\n");
	{
		CheckJob_Flt FltJob(&gDrvEventList, hEventAppear);
		if (false == FltJob.Start())
		{
			Log.AddToLog(L"Can't start check filtering system!");
			gDrvEventList.SetError(_ERR_DRVFAULT);
		}
		else
		{
			VERDICT Verdict;
			byte SinglEevent[512];
			PFILTER_EVENT_PARAM pSignleEvt = (PFILTER_EVENT_PARAM) SinglEevent;
			ZeroMemory(SinglEevent, sizeof(SinglEevent));

			pSignleEvt->HookID = FLTTYPE_FLT;
			pSignleEvt->FunctionMj = 0;
			pSignleEvt->FunctionMi = 0;
			pSignleEvt->ParamsCount = 1;
			pSignleEvt->ProcessingType = PreProcessing;
			
			PSINGLE_PARAM pSingleParam = (PSINGLE_PARAM) pSignleEvt->Params;

			BYTE FltTransmit[4095];
			PFILTER_TRANSMIT pFlt = (PFILTER_TRANSMIT) FltTransmit;
			ZeroMemory(FltTransmit, sizeof(FltTransmit));

			FltJob.SetAllowEvents(true);
			if (false == FltJob.ChangeActiveStatus(true))
			{
				Log.AddToLog(L"Can't activate check filtering system!");
				gDrvEventList.SetError(_ERR_DRVFAULT);
			}
			else
			{
				Log.AddToLog(L"check filter's order...");

				ULONG FltArr[4] = {0};

				FltArr[1] = AddFSFilter2(FltJob.m_hDevice, FltJob.m_AppID, gpModuleName, 5, FLT_A_DEFAULT, 
					FLTTYPE_FLT, 0, 0, 0, PreProcessing, NULL, NULL);

				FltArr[3] = AddFSFilter2(FltJob.m_hDevice, FltJob.m_AppID, gpModuleName, 5, FLT_A_DEFAULT, 
					FLTTYPE_FLT, 0, 0, 0, PreProcessing, NULL, NULL);

				if (!FltArr[1] || !FltArr[3])
				{
					Log.AddToLog(L"Add filter to FLTTYPE_FLT failed!");
					gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
				}
				else
				{
					DWORD site = 0;
					FltArr[0] = AddFSFilter2(FltJob.m_hDevice, FltJob.m_AppID, gpModuleName, 5, FLT_A_DEFAULT, 
						FLTTYPE_FLT, 0, 0, 0, PreProcessing, &site, NULL);

					site = FltArr[1];
					FltArr[2] = AddFSFilter2(FltJob.m_hDevice, FltJob.m_AppID, gpModuleName, 5, FLT_A_DEFAULT, 
						FLTTYPE_FLT, 0, 0, 0, PreProcessing, &site, NULL);
				}

				if (!FltArr[0] || !FltArr[2])
				{
					Log.AddToLog(L"Add filter to FLTTYPE_FLT failed!");
					gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
				}
				else
				{
					pFlt->m_AppID = FltJob.m_AppID;
					pFlt->m_FltCtl = FLTCTL_FIRST;
					
					if (FALSE == IDriverFilterTransmit(FltJob.m_hDevice, pFlt, pFlt, sizeof(FltTransmit), sizeof(FltTransmit)))
					{
						Log.AddToLog(L"Enumerating filter's failed!");
						gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
					}
					else
					{
						int ienum = 0;
						pFlt->m_FltCtl = FLTCTL_NEXT;
						do
						{
							if (ienum > sizeof(FltArr) / sizeof(FltArr[0]))
							{
								Log.AddToLog(L"Filter's count mismatch!");
								gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
							}
							else
							{
								if (FltArr[ienum] != pFlt->m_FilterID)
								{
									Log.AddToLog(L"Filter's order mismatch!");
									gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
								}

								ienum++;
							}

						} while (TRUE == IDriverFilterTransmit(FltJob.m_hDevice, pFlt, pFlt, sizeof(FltTransmit), sizeof(FltTransmit)));
					}
				}

				if (_ERR_DRVFAULT_FLT & gDrvEventList.m_ErrorFlags)
				{
					Log.AddToLog(L"further filter's check skipped - errors...");
				}
				else
				{
					Log.AddToLog(L"checking enable/disable...");
					pFlt->m_FilterID = FltArr[2];
					pFlt->m_FltCtl = FLTCTL_DISABLE_FILTER;
					if (FALSE == IDriverFilterTransmit(FltJob.m_hDevice, pFlt, pFlt, sizeof(FltTransmit), sizeof(FltTransmit)))
					{
						Log.AddToLog(L"Disable filter failed!");
						gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
					}

					pFlt->m_FltCtl = FLTCTL_ENABLE_FILTER;
					if (FALSE == IDriverFilterTransmit(FltJob.m_hDevice, pFlt, pFlt, sizeof(FltTransmit), sizeof(FltTransmit)))
					{
						Log.AddToLog(L"Enable filter failed!");
						gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
					}

					Log.AddToLog(L"checking delete/reset...");

					ResetEvent(hEventAppear);
					pFlt->m_FltCtl = FLTCTL_DEL;
					if (FALSE == IDriverFilterTransmit(FltJob.m_hDevice, pFlt, pFlt, sizeof(FltTransmit), sizeof(FltTransmit)))
					{
						Log.AddToLog(L"Delete filter failed!");
						gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
					}

					pFlt->m_FltCtl = FLTCTL_RESET_FILTERS;
					if (FALSE == IDriverFilterTransmit(FltJob.m_hDevice, pFlt, pFlt, sizeof(FltTransmit), sizeof(FltTransmit)))
					{
						Log.AddToLog(L"Reset filter failed!");
						gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
					}

					if (WAIT_OBJECT_0 != WaitForSingleObject(hEventAppear, 1000 * 60 * 3))	// 3 min
					{
						Log.AddToLog(L"Error: change filter's queue not detected!");
						gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
					}
				}
			}

#define _flt_timeout	20 /*sec*/
			Log.AddToLog(L"checking filter with timeout...");

			FILETIME STasFT;
			ULARGE_INTEGER ExpTime;
			
			GetSystemTimeAsFileTime(&STasFT);
			ExpTime.LowPart=STasFT.dwLowDateTime;
			ExpTime.HighPart=STasFT.dwHighDateTime;
			STasFT.dwLowDateTime=_flt_timeout;
			ExpTime.QuadPart=ExpTime.QuadPart+(LONGLONG)STasFT.dwLowDateTime * 6000000;	//600000000

			ULONG FltTimeout = AddFSFilter2(FltJob.m_hDevice, FltJob.m_AppID, gpModuleName, 5, FLT_A_INFO, 
					FLTTYPE_FLT, 0, 0, *((__int64*)&ExpTime), PreProcessing, NULL, NULL);
			if (FltTimeout == 0)
			{
				Log.AddToLog(L"Error: add filter with timeout failed!");
				gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
			}
			else
			{
				pSingleParam->ParamFlags = _SINGLE_PARAM_FLAG_NONE;
				pSingleParam->ParamID = _PARAM_OBJECT_URL_W;
				lstrcpy((PWCHAR)pSingleParam->ParamValue, L"this is test filter with timeout...");
				pSingleParam->ParamSize = (lstrlen((PWCHAR)pSingleParam->ParamValue) + 1) * sizeof(WCHAR);

				if (FALSE == IDriverFilterEvent(FltJob.m_hDevice, pSignleEvt, FALSE, &Verdict))
				{
					Log.AddToLog(L"Error: check filter with timeout failed!");
					gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
				}
				else
				{
					Sleep((_flt_timeout + 1) * 1000);
					
					lstrcpy((PWCHAR)pSingleParam->ParamValue, L"Error: filter with timeout is present in queue after timeout!");
					pSingleParam->ParamSize = (lstrlen((PWCHAR)pSingleParam->ParamValue) + 1) * sizeof(WCHAR);

					if (FALSE == IDriverFilterEvent(FltJob.m_hDevice, pSignleEvt, FALSE, &Verdict))
					{
						Log.AddToLog(L"Error: check filter with timeout failed!");
						gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
					}
				}
			}
	
			while ((pEvt = gDrvEventList.GetFirst()) != NULL)
			{
				Log.AddToLog((PEVENT_TRANSMIT) pEvt);
				gDrvEventList.Free(pEvt);
			}

			// params and cache
#define _test_params			20
			BYTE pbParams[_test_params][sizeof(FILTER_PARAM) + 0x100];
			ZeroMemory(pbParams, sizeof(pbParams));

			if (!(_ERR_DRVFAULT_FLT & gDrvEventList.m_ErrorFlags))
			{
				PFILTER_PARAM pArrFltParam[_test_params];

				// dword - FLT_PARAM_AND, FLT_PARAM_EUA, FLT_PARAM_ABV, FLT_PARAM_BEL, FLT_PARAM_MORE, FLT_PARAM_LESS, FLT_PARAM_MASK, FLT_PARAM_EQU_LIST
				// string - FLT_PARAM_WILDCARD

#define FltParam(_idx, _type, _value) { pArrFltParam[_idx] = (PFILTER_PARAM) pbParams[_idx];\
				pArrFltParam[_idx]->m_ParamFlags = _FILTER_PARAM_FLAG_CACHABLE;\
				pArrFltParam[_idx]->m_ParamFlt = _idx;\
				pArrFltParam[_idx]->m_ParamID = _idx;\
				pArrFltParam[_idx]->m_ParamSize = sizeof(_type);\
				*(_type*)(pArrFltParam[_idx]->m_ParamValue) = _value;}


				FltParam(FLT_PARAM_AND, BYTE, 1);
				FltParam(FLT_PARAM_ABV, DWORD, 50001);
				FltParam(FLT_PARAM_BEL, DWORD, 50001);
				FltParam(FLT_PARAM_MORE, DWORD, 0x2000003);
				FltParam(FLT_PARAM_LESS, DWORD, 0x2000003);

				ULONG FltTimeout = AddFSFilter2(FltJob.m_hDevice, FltJob.m_AppID, gpModuleName, 5, FLT_A_INFO | FLT_A_SAVE2CACHE | FLT_A_USECACHE | FLT_A_RESETCACHE, 
					FLTTYPE_FLT, 0, 0, 0, PreProcessing, NULL, 
					pArrFltParam[FLT_PARAM_AND], pArrFltParam[FLT_PARAM_ABV], 
					pArrFltParam[FLT_PARAM_BEL], pArrFltParam[FLT_PARAM_MORE], pArrFltParam[FLT_PARAM_LESS],
					NULL);

				if (FltTimeout == 0)
				{
					Log.AddToLog(L"Error: add filter with parameters failed!");
					gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
				}
				else
				{
					VERDICT VerdictOk, VerdictBad;
					
					pSingleParam->ParamFlags = _SINGLE_PARAM_FLAG_NONE;

#define _check_flt_op(_str, _op, _type, _val1, _val2) Log.AddToLog(L"Checking flt op " _str L"...");\
					pSingleParam->ParamID = _op;\
					*(_type*)pSingleParam->ParamValue = _val1;\
					pSingleParam->ParamSize = sizeof(_type);\
					if (FALSE == IDriverFilterEvent(FltJob.m_hDevice, pSignleEvt, TRUE, &VerdictOk))\
						 VerdictOk = Verdict_Debug;\
					*(_type*)pSingleParam->ParamValue = _val2;\
					if (FALSE == IDriverFilterEvent(FltJob.m_hDevice, pSignleEvt, TRUE, &VerdictBad))\
						 VerdictBad = Verdict_Debug;\
					if (VerdictOk != Verdict_Pass || VerdictBad != Verdict_NotFiltered)\
					{\
						Log.AddToLog(L"Flt operation" _str L" returned bad result");\
						gDrvEventList.SetError(_ERR_DRVFAULT_FLT);\
					}
//+ ----------------------------------------------------------------------------------------
					_check_flt_op(L"AND", FLT_PARAM_AND, BYTE, 1, 2);
//+ ----------------------------------------------------------------------------------------
					_check_flt_op(L"ABV", FLT_PARAM_ABV, DWORD, 50001, 50000);
//+ ----------------------------------------------------------------------------------------
					_check_flt_op(L"BEL", FLT_PARAM_BEL, DWORD, 50001, 50002);
//+ ----------------------------------------------------------------------------------------
					_check_flt_op(L"MORE", FLT_PARAM_MORE, DWORD, 0x2000003, 0x2000004);
//+ ----------------------------------------------------------------------------------------
					_check_flt_op(L"LESS", FLT_PARAM_LESS, DWORD, 0x2000003, 0x2000002);
				}
			}
			
			if (!(_ERR_DRVFAULT_FLT & gDrvEventList.m_ErrorFlags))
			{
				pFlt->m_FltCtl = FLTCTL_RESET_FILTERS;
				if (FALSE == IDriverFilterTransmit(FltJob.m_hDevice, pFlt, pFlt, sizeof(FltTransmit), sizeof(FltTransmit)))
				{
					Log.AddToLog(L"Reset filter failed!");
					gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
				}
			}
			
			if (!(_ERR_DRVFAULT_FLT & gDrvEventList.m_ErrorFlags))
			{
				PFILTER_PARAM pCacheParam = (PFILTER_PARAM) pbParams;
				pCacheParam->m_ParamFlags = _FILTER_PARAM_FLAG_CACHABLE;
				pCacheParam->m_ParamFlt = FLT_PARAM_WILDCARD;
				pCacheParam->m_ParamID = _PARAM_OBJECT_URL_W;
				lstrcpy((PWCHAR)pCacheParam->m_ParamValue, L"*");
				pCacheParam->m_ParamSize = (lstrlen((PWCHAR)pCacheParam->m_ParamValue) + 1) * sizeof(WCHAR);

				ULONG FltCache = AddFSFilter2(FltJob.m_hDevice, FltJob.m_AppID, gpModuleName, 0, FLT_A_POPUP | FLT_A_SAVE2CACHE | FLT_A_USECACHE, 
					FLTTYPE_FLT, 0, 0, 0, PreProcessing, NULL, pCacheParam, NULL);
				if (!FltCache)
				{
					Log.AddToLog(L"Error: can't add filter for checking cache!");
					gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
				}
				else
				{
					VERDICT Verdict1, Verdict2;
					pSignleEvt->ProcessingType = PreProcessing;
					
					pSingleParam->ParamFlags = _SINGLE_PARAM_FLAG_NONE;
					pSingleParam->ParamID = _PARAM_OBJECT_URL_W;
					lstrcpy((PWCHAR)pSingleParam->ParamValue, L"check cache (must be one such string in log!)");
					pSingleParam->ParamSize = (lstrlen((PWCHAR)pSingleParam->ParamValue) + 1) * sizeof(WCHAR);

					if (FALSE == IDriverFilterEvent(FltJob.m_hDevice, pSignleEvt, FALSE, &Verdict1))
					{
						Log.AddToLog(L"Error: check driver cache!");
						gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
					}
					else
					{
						if (FALSE == IDriverFilterEvent(FltJob.m_hDevice, pSignleEvt, FALSE, &Verdict2))
						{
							Log.AddToLog(L"Error: check driver cache (second event)!");
							gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
						}
						else
						{
							if ((Verdict1 != Verdict_Pass) || (Verdict2 != Verdict_Pass))
							{
								Log.AddToLog(L"Error: check driver cache failed!");
								gDrvEventList.SetError(_ERR_DRVFAULT_FLT);
							}
						}
					}
				}
			}

 			FltJob.ChangeActiveStatus(false);

			while ((pEvt = gDrvEventList.GetFirst()) != NULL)
			{
				Log.AddToLog((PEVENT_TRANSMIT) pEvt);
				gDrvEventList.Free(pEvt);
			}
		}
	}
#endif
	//-
	//- ----------------------------------------------------------------------------------------

	Log.AddToLog(L"\nTest finished.");

	if (gDrvEventList.m_Errors)
	{
		WCHAR err[128];
		wsprintf(err, L"Errors %d, mask %x", gDrvEventList.m_Errors, gDrvEventList.m_ErrorFlags);
		Log.AddToLog(err);
		
		return gDrvEventList.m_ErrorFlags;
	}

	Log.AddToLog(L"\n\nNo errors.");
	
	return 0;
}
Beispiel #29
0
int CServerSocket::Run()
{
	// Accept 실행
	long i = 0 ;
	long nDef = ( m_nMinPendingAccept + m_nMaxPendingAccept ) / 2 ;
	for( i = 0 ; i < nDef ; i++ )
	{
		Accept() ;
	}

	HANDLE WaitHandles[3] ;

	if( SOCKET_ERROR == WSAEventSelect( m_listensocket, m_hNoAcceptWaitEvent, FD_ACCEPT ) )
	{
		printf( "WSAEventSelect Error : %d\n", ::WSAGetLastError() ) ;
		printf( "CServerSocket Run Return\n" ) ;
		return 0 ;
	}

	WaitHandles[0] = m_hAcceptPostEvent ;		// Accept 신청이 들어오면.
	WaitHandles[1] = m_hNoAcceptWaitEvent ;		// 대기중인 Accept가 없을 때.
	WaitHandles[2] = m_hShutDownEvent ;			// 서버 닫기 요청이 들어오면.

	DWORD WaitResult ; 
	BOOL bContineServer = TRUE ;
	long temp ;

	while( bContineServer ) 
	{
		WaitResult = ::WaitForMultipleObjects( 3, WaitHandles, FALSE, 3000 ) ;
		
		switch( WaitResult ) {
		case WAIT_OBJECT_0:		// Accept 요청이 들어왔다. 비교하고 호출.
			//printf( "   ++ AcceptPostEvent ++  \n" ) ;
			ResetEvent( m_hAcceptPostEvent ) ;
			
			if( m_nCurPendingAccept < m_nMaxPendingAccept )
			{
				Accept() ;
			}
			else
			{
				printf( " cur accept pending (cur: %d, max: %d) \n", m_nCurPendingAccept, m_nMaxPendingAccept ) ;
			}
			break;

		case WAIT_OBJECT_0 + 1:	// 대기중인 Accept 가 없다. 이거 들어오면 무조건 10번씩 호출하자.
			
			ResetEvent( m_hNoAcceptWaitEvent ) ;


			/*
			if( m_nMaxPoolCount > (m_queuePool.size() + m_nCurPendingAccept + 100) )
			{
				CSocketBuffer * pBuf = NULL ;
				try{
					temp = m_nMaxPoolCount - m_queuePool.size() - m_nCurPendingAccept ;

					if( temp < 0 || temp > m_nMaxPoolCount )
					{
						::PrintConsole( "[EXCEPTION] if( temp < 0 || temp > m_nMaxPoolCount )  temp:%d \n", temp ) ;
						continue ;
					}

					printf( " new socketbuffer (count : %d) \n", temp ) ;

					for( int i = 0 ; i < temp && i < 100 ; i++ )
					{
						pBuf = new CSocketBuffer(*this) ;
						if( pBuf ){

							//pBuf->reset() ;
							pool_lock() ;
							try{
								m_queuePool.push( pBuf ) ;
							}
							catch (...) {
								::PrintConsole( "[EXCEPTION] %s, %d\n", __FILE__, __LINE__  ) ;
							}							
							pool_unlock() ;
							
							if( m_iocp.AssociateSocket( pBuf ) == false )
							{
								int iError = WSAGetLastError() ;
								printf( " m_iocp.AssociateSocket( pBuf ) == false (err_code :%d)\n", iError ) ;							
							}
						}
					}
					printf(" ** create socket buffer (count :%d) \n", i ) ;
				}
				catch (...) {					
					::PrintConsole( "[EXCEPTION] %s, %d\n", __FILE__, __LINE__  ) ;
				}		
			}
			*/


			
			if( m_nCurPendingAccept < m_nMinPendingAccept )
				temp = m_nMinPendingAccept - m_nCurPendingAccept ;
			//else if( m_nCurPendingAccept > m_nMaxPendingAccept )
			else
				temp = 0 ;
			//else
			//	temp = 10 ;

			if( temp < 0 || temp > m_nMaxPendingAccept )
			{
				::PrintConsole( "[EXCEPTION] if( temp < 0 || temp > m_nMaxPendingAccept )  temp:%d \n", temp ) ;
				continue ;
			}

			/*
#ifdef _TRACE_
			g_pTrace->OutputString( _TRACE_CLASS_SYSTEM, "****  NoAcceptWait Event : Accept %d  , cur:%d, min : %d, max:%d \n", temp, m_nCurPendingAccept, m_nMinPendingAccept, m_nMaxPendingAccept ) ;
#endif
			*/

			for( i = 0 ; i < temp && i < 100 ; i++ )
			{
				Accept() ;
			}
			break;

		case WAIT_OBJECT_0 + 2:	// ShutDown 시키자.
			ResetEvent( m_hShutDownEvent ) ;
			bContineServer = FALSE ;
			break ;

		case WAIT_TIMEOUT:
			//printf( "Timeout : Cur Pending = %u\n", m_nCurPendingAccept ) ;
			SetEvent( m_hNoAcceptWaitEvent ) ;
			break ;

		default:
			::PrintConsole( "Error : WaitForMultipleObjects Return %u\n", WaitResult ) ;
		}
	}

	::PrintConsole( "CServerSocket Run Thread Return\n" ) ;

	return 0 ;
}
Beispiel #30
0
/***********************************************************************
 *           ResetW32Event (KERNEL.459)
 */
BOOL WINAPI ResetW32Event( HANDLE handle )
{
    return ResetEvent( handle );
}