void CSocketReader::RunL()
    {
        // Active object request complete handler
        TRACE_INFO((_L("CSocketReader::RunL(), iStatus.Int()=%d, socketID=%d"),iStatus.Int(), iSocketID));

    switch (iStatus.Int())
        {
        case KErrNone:
            {
            // Data has been read from socket
            // Inform the observer and issue another read if we want
            // to continue listening
            if (iObserver.HandleDataReceived(iSocketID, iBufferPtr))
                {
                IssueRead();
                }
            break;
            }

        default:
            {
            // A read error has occurred. Inform the observer the connection is lost
            iObserver.HandleSocketError(iSocketID, ETrue, iStatus.Int());
            break;
            }
        }
    }
void CKiConnectedSocketReader::RunL()
{
    // Active object request complete handler
    switch (iStatus.Int())
    {
        case KErrNone:
            // Character has been read from socket			
			iLongBuffer.AppendL(iBuffer);
			
			//iLog->WriteL(_L8("[Socket] in  ::::"));
			//iLog->WriteLineL(iBuffer);

			
			iBuffer.SetLength(0);			
		    IssueRead(); // Immediately start another read		
			
            iSocketBase.OnReceiveL();
			
            break;
			
        default:
			LWRITE(iLog, _L8("(reader) socket error "));
			LWRITELN(iLog, iStatus.Int());

			// closing connection
			iSocketBase.HandleReadErrorL();
            break;
    }	
}
void CSocketsReader::CheckedRunL()
{
    CALLSTACKITEM_N(_CL("CSocketsReader"), _CL("CheckedRunL"));

    iReadTimer->Reset();
    switch (iStatus.Int())
    {
    case KErrNone:
        //Log(iBuffer);
        iHasRead=ETrue;
        iEngineNotifier.UpdateByteCount(iBuffer.Length(), 0);

        TBool live;
        iLive=&live;
        live=ETrue;
        iEngineNotifier.ResponseReceived(iBuffer);
        if (live && issueRead) {
            IssueRead();
            iLive=0;
        }
        break;

    case KErrDisconnected:
        iEngineNotifier.ReportError(MEngineNotifier::EDisconnected,iStatus.Int());
        break;

    default:
        iEngineNotifier.ReportError(MEngineNotifier::EGeneralReadError,iStatus.Int());
        break;
    }
}
Example #4
0
void CKiUDPSocketReader::RunL()
{
    // Active object request complete handler
    switch (iStatus.Int())
    {
        case KErrNone:		
        {
        	HLWRITELN(iLog, _L("[CKiUDPSocketReader] UDP datagram received"));
			//iLog->WriteL(_L8("[Socket] In: "));
			//iLog->WriteLineL(iBuffer);
        
        	iSocket.IncIncomingTraffic(iBuffer.Length());
			
            iSocket.OnReceiveL(iRemoteAddress, iBuffer);
        }
        break;
			
        default:
        {
        	HLWRITE(iLog, _L("[CKiUDPSocketReader] UDP read error"));
        	HLWRITELN(iLog, iStatus.Int());
			//iLog->WriteL(_L8("[Socket] Recv error: "));
			//iLog->WriteLineL(iStatus.Int());

			// closing connection
			iSocket.HandleReadErrorL();
		}
        break;
    }
    if (!iStopped)
    	IssueRead(); // Immediately start another read
}
// -----------------------------------------------------------------------------
// CSocketReader::RunError
// -----------------------------------------------------------------------------
//
TInt CSocketReader::RunError( TInt aError )
    {
    iObserver->ObserverLeaved( aError );
    iReadBuffer.SetLength( 0 );
    IssueRead();
    return KErrNone;
    }
void CKiConnectedSocketReader::Start()
{
    // Initiate a new read from socket into iBuffer
    if (!IsActive())
    {
        IssueRead();
    }
}
void CSocketReader::RunL()
	{
	SUPLLOG(ELogP1, "CSocketReader::RunL() Begin\n");
	TBool cleanup = EFalse;
	if (iStatus == KErrNone)
		{
		iReadSoFar += iBufferRead();
		if (iIsFirstFragment && (iReadSoFar > 1)) // If first fragment we need to get the size of the data
			{
			SuplMessageLength();
			iIsFirstFragment = EFalse;
			} // if
		
		if (iReadSoFar == iCurrentMessageSize)
			{
			// Fire observation
			iBuffer.SetLength(iCurrentMessageSize);
			FireObservation();
			
			iIsFirstFragment = ETrue;
			iCurrentMessageSize = 0;
			iReadSoFar = 0;
			iBuffer.SetLength(iBuffer.MaxLength());
			} // if
		else if (iReadSoFar > iCurrentMessageSize)
			{
			SUPLLOG(ELogP1, "CSocketReader::RunL(), ReadSoFar > CurrentMessageSize\n");
			SUPLLOG(ELogP1, "CSocketReader::FireObservation() Firing ConnectionError\n");

			iObserver.ConnectionError(MSuplSocketObserver::ETooMuchDataRead, iCallbackId, 0, cleanup);
			if (cleanup)
				{
				delete this;
				}
			} // else if
		else
			{
			// Do nothing.
			}
		
		// Kick off the read again
		if (!cleanup)	//cleanup status from iObserver.ConnectionError
			{
			IssueRead();
			}
		} // if
	else
		{
		SUPLLOG(ELogP1, "CSecureSocketReader::FireObservation() Firing ConnectionError\n");

		iObserver.ConnectionError(MSuplSocketObserver::EFailedToRead, iCallbackId, 0, cleanup);
		if (cleanup)
			{
			delete this;
			}
		}
	SUPLLOG(ELogP1, "CSocketReader::RunL() End\n");
	}
Example #8
0
void CKiUDPSocketReader::Start()
{
	if (!IsActive())
	{
		iStopped = EFalse;
		IssueRead();
	}
		
}
// -----------------------------------------------------------------------------
// CSocketReader::Start
// -----------------------------------------------------------------------------
//
void CSocketReader::Start()
    {
    DEBUG_PRINT( DEBUG_STRING(
        "CSocketReader::Start" ) );
    if ( !IsActive() )
        {
        IssueRead();
        }
    }
// ---------------------------------------------------------------------------
// CUpnpTcpSessionReader::Start
// Starts reading.
// ---------------------------------------------------------------------------
//
void CUpnpTcpSessionReader::Start()
    {
    LOGS1( "%i, CUpnpTcpSessionReader::Start", iSession.Id() );
    // Initiate a new read from socket into iBuffer
    if ( !IsActive() )
        {
        IssueRead();
        }
    }    
Example #11
0
void CSocketReader::ConstructL()
	{
	SUPLLOG(ELogP1, "CSocketReader::ConstructL() Begin\n");
	iBuffer.CreateL(KSuplMaxMessageLength);
	iBuffer.SetLength(iBuffer.MaxLength());
	iDecoder = CSuplAsn1Decoder::NewL();
	
	IssueRead();
	SUPLLOG(ELogP1, "CSocketReader::ConstructL() End\n");
	}
// -----------------------------------------------------------------------------
// CUpnpTcpSessionReader::TimerEventL
// Retry read
// -----------------------------------------------------------------------------
//        
void CUpnpTcpSessionReader::TimerEventL( CUpnpNotifyTimer* aTimer )
    {
    if( aTimer == iCancelTimer )
        {
        iCancelFromTimer = ETrue;
        iSocket.CancelRecv();
        }
    else if( aTimer == iRetryTimer )
        {
        IssueRead();
        }
    }
Example #13
0
void CKiUDPSocketReader::StartL(TUint aPort)
{
	HLWRITELN(iLog, _L("[CKiUDPSocketReader] Starting"));
    // Initiate a new read from socket into iBuffer
    if (!IsActive())
    {
	    TInetAddr addr(KInetAddrAny, aPort);
		User::LeaveIfError( iSocket.Socket().Bind(addr) );
		
		iStopped = EFalse;
		
        IssueRead();
    }
}
// -----------------------------------------------------------------------------
// CSocketReader::RunL
// -----------------------------------------------------------------------------
//
void CSocketReader::RunL()
    {
    TInt status = iStatus.Int();
    if ( status == KErrNone )
        {
        iObserver->DataReceivedL( iReadBuffer );
        iReadBuffer.SetLength( 0 );
        IssueRead();
        }
    else
        {
        iObserver->ReaderErrorL( status );
        }
    }
Example #15
0
void CSocketReader::StartReadingL(RSocket* aSocket, TInt aMTU)
    {
    // Initiate a new read from socket into iBuffer
    __ASSERT_DEBUG(!IsActive(),
            User::Panic(KPanicSocketsEngineRead, ESocketsBadState));

    if (aMTU > iBufferPtr.MaxLength())
        {
        // Realloc the buffer as it isn't large enough.
        iBufferPtr.Set(0, 0, 0);
        delete iBuffer;
        iBuffer = 0;
        iBuffer = HBufC8::NewL(aMTU);
        iBufferPtr.Set(iBuffer->Des());
        }

    iSocket = aSocket;
    IssueRead();
    }
// ---------------------------------------------------------------------------
// CUpnpTcpSessionReader::RunL
// From class CActive.
// Function is called as a callback when the issued reading is completed.
// ---------------------------------------------------------------------------
//
void CUpnpTcpSessionReader::RunL()
    {
    LOGS2( "%i, CUpnpTcpSessionReader::RunL(), iStatus %i",
    		iSession.Id(), iStatus.Int() );

    // Active object request complete handler
    switch ( iStatus.Int() )
        {
        case KErrNone:
           	iRetryErrorCount = 0;
           	iCancelTimer->Cancel();

            // Forward read data to HTTPSession 
            iSession.ReceivingCompletedL( iReceiveBuffer );
            break;
            
         case KErrCancel:
            if(iCancelFromTimer) 
                {          
                IssueRead();
                iCancelFromTimer = EFalse;
                }
            break;
       
        case KErrNoMemory:
        case KErrNotReady:
        case KErrInet6AddressExpired:
            if( iRetryErrorCount < KMaxRetryErrors )
	            {
	        	iRetryTimer->Cancel();
				iRetryTimer->After( KRetryWaitTime * ++iRetryErrorCount, EFalse );
				break;
	            }
            
        default:
            iSession.HandleErrorL( iStatus.Int() );
            break;
        }
    }
Example #17
0
void CListener::RunL()
	{
	if(iListenerState == EWaitingForConnection)
		{
		// We are here when incoming connection detected and Accepted on Listener.
		if(iStatus != KErrNone)
			{
			// Something went wrong when accepting a remote connection
			// Not much we can do at this point.
			LOGLINE2(_L("Accept returns error! %d"), iStatus.Int());
			LOGLINE1(_L("Leaving....!"))
			DoCancel();
			User::Leave(KErrCommsLineFail);
			}
			
		// iBlankSocket is now ready to communicate with the incoming connection.
		LOGLINE1(_L("Remote connection detected!"));
			
		// Wait for data from remote port
		IssueRead();
		}
	else if(iListenerState == EWaitingForData)
		{
		
		// Check status of Recv operation
		if(iStatus != KErrNone)
			{
			if(iStatus == KErrEof)
				{
				LOGLINE1(_L("Remote party may have closed the connection"));
				}
			// Terminate the active socket
			LOGLINE1(_L("Closing active socket"));
			iBlankSocket.Close();
			
			// Set listening socket to accept new connection
			AcceptL();
			return;
			}

		// Print received data!!!!
		TBuf16<KReqstSocketPreReadSize> Buffer;
		Buffer.Copy(iBufferPreRead);

		// Get msg length from pre-read
		TUint msgLen = CReqstParser::ExtractMsgLenL(iBufferPreRead);
		__ASSERT_ALWAYS(msgLen > KReqstSocketPreReadSize, User::Panic(KPanicMsgFormat, KIncorrectPreReadSize)); 
		
		
		// Now read the rest of msg by creating an Rbuf just large enough according to the msg length
		iBuffer.Close();

		// Create a buffer to recv exact amount of remaining reqst msg
		iBuffer.CreateL(msgLen - KReqstSocketPreReadSize);
		
		// Read remaining msg data.
		// Recv operation should complete immediately if msg has been formatted correctly
		iBlankSocket.Recv(iBuffer, 0, iStatus);
		User::WaitForRequest(iStatus);
		// Check status of Recv operation
		if(iStatus != KErrNone)
			{
			if(iStatus == KErrEof)
				{
				LOGLINE1(_L("Remote party may have closed the connection during 2nd Recv"));
				}
			// Terminate the active socket
			LOGLINE1(_L("Error during 2nd Recv!!"));
			LOGLINE1(_L("Closing active socket"));
			iBlankSocket.Close();
			
			// Set listening socket to accept new connection
			AcceptL();
			return;
			}
		
		// Tell reqst hndlr we have a msg. That thread will parse msg and build the reply which we
		// want to send back to master. The call to ETEL to process the actual reqst
		// will have to be done asynchronously in HandleRequestL().
		iBufferAll.Close();
		iBufferAll.CreateL(msgLen);		// Give HandleRequestL the entire msg!
		iBufferAll += iBufferPreRead;
		iBufferAll += iBuffer;
		const TDesC8& response = iRqstHndlr.HandleRequestL(iBufferAll);
		
		if(response == KNullDesC8)
			{
			LOGLINE1(_L("Response msg is NULL"));
			}
		else
			{
			// Send back the reply msg
			TRequestStatus status;
			//convert to 16 bit
			TBuf16<4*KMaxElementSize> responsebuf16;
			responsebuf16.Copy(response);
			LOGLINE2(_L("Sending data back to sender...%S"), &responsebuf16);
			iBlankSocket.Send(response, 0, status);
			User::WaitForRequest(status);
			// There's a slim chance the remote party has closed the connection since the time a msg 
			// was received
			if(status != KErrNone)
				{
				if(status == KErrEof)
					{
					LOGLINE1(_L("Remote party may have closed the connection before we could send the response"));
					}
				// Terminate the active socket
				LOGLINE1(_L("Closing active socket"));
				iBlankSocket.Close();
				
				// Set listening socket to accept new connection
				AcceptL();
				return;
				}
			
			LOGLINE2(_L("Data sent. Status = %d"), status.Int());
			}
		
		// Wait for data from remote port
		IssueRead();
		}
	}
// -----------------------------------------------------------------------------
// CSocketReader::ConstructL
// -----------------------------------------------------------------------------
//
void CSocketReader::ConstructL()
    {
    CActiveScheduler::Add( this );
    IssueRead();
    }
EXPORT_C void CSocketsReader::Start()
{
    CALLSTACKITEM_N(_CL("CSocketsReader"), _CL("Start"));
    iReadTimeOut=KReadTimeOut;
    if (!IsActive()) IssueRead();
}
Example #20
0
//
// Each worker thread starts here.
DWORD WINAPI ThreadFunc(LPVOID pVoid)
{
    BOOL    bResult;
    DWORD   dwNumRead;
    struct ContextKey *pCntx;
    LPOVERLAPPED lpOverlapped;

    UNREFERENCED_PARAMETER(pVoid);

    // Loop forever on getting packets from
    // the I/O completion port.
    for (;;)
    {
        bResult = GetQueuedCompletionStatus(
                      ghCompletionPort,
                      &dwNumRead,
                      &(DWORD)pCntx,
                      &lpOverlapped,
                      INFINITE
                  );

        if (bResult == FALSE
                && lpOverlapped == NULL)
        {
            FatalError(
                "ThreadFunc - Illegal call to GetQueuedCompletionStatus");
        }

        else if (bResult == FALSE
                 && lpOverlapped != NULL)
        {
            // This happens occasionally instead of
            // end-of-file. Not sure why.
            closesocket(pCntx->sock);
            free(pCntx);
            fprintf(stderr,
                    "ThreadFunc - I/O operation failed\n");
        }

        else if (dwNumRead == 0)
        {
            closesocket(pCntx->sock);
            free(pCntx);
            fprintf(stderr, "ThreadFunc - End of file.\n");
        }

        // Got a valid data block!
        // Save the data to our buffer and write it
        // all back out (echo it) if we have see a \n
        else
        {
            // Figure out where in the buffer to save the character
            char *pch = &pCntx->OutBuffer[pCntx->nOutBufIndex++];
            *pch++ = pCntx->InBuffer[0];
            *pch = '\0';    // For debugging, WriteFile doesn't care
            if (pCntx->InBuffer[0] == '\n')
            {
                WriteFile(
                    (HANDLE)(pCntx->sock),
                    pCntx->OutBuffer,
                    pCntx->nOutBufIndex,
                    &pCntx->dwWritten,
                    &pCntx->ovOut
                );
                pCntx->nOutBufIndex = 0;
                fprintf(stderr, "Echo on socket %x.\n", pCntx->sock);
            }

            // Start a new read
            IssueRead(pCntx);
        }
    }

    return 0;
}
Example #21
0
int main(int argc, char *argv[])
{
    SOCKET  listener;
    SOCKET  newsocket;
    WSADATA WsaData;
    struct sockaddr_in serverAddress;
    struct sockaddr_in clientAddress;
    int     clientAddressLength;
    int     err;

    CheckOsVersion();

    err = WSAStartup (0x0101, &WsaData);
    if (err == SOCKET_ERROR)
    {
        FatalError("WSAStartup Failed");
        return EXIT_FAILURE;
    }

    /*
     * Open a TCP socket connection to the server
     * By default, a socket is always opened
     * for overlapped I/O.  Do NOT attach this
     * socket (listener) to the I/O completion
     * port!
     */
    listener = socket(AF_INET, SOCK_STREAM, 0);
    if (listener < 0)
    {
        FatalError("socket() failed");
        return EXIT_FAILURE;
    }

    /*
     * Bind our local address
     */
    memset(&serverAddress, 0, sizeof(serverAddress));
    serverAddress.sin_family      = AF_INET;
    serverAddress.sin_addr.s_addr = htonl(INADDR_ANY);
    serverAddress.sin_port        = htons(SERV_TCP_PORT);

    err = bind(listener,
               (struct sockaddr *)&serverAddress,
               sizeof(serverAddress)
              );
    if (err < 0)
        FatalError("bind() failed");

    ghCompletionPort = CreateIoCompletionPort(
                           INVALID_HANDLE_VALUE,
                           NULL,   // No prior port
                           0,      // No key
                           0       // Use default  # of threads
                       );
    if (ghCompletionPort == NULL)
        FatalError("CreateIoCompletionPort() failed");

    CreateWorkerThreads(ghCompletionPort);

    listen(listener, 5);

    fprintf(stderr, "Echo Server with I/O Completion Ports\n");
    fprintf(stderr, "Running on TCP port %d\n", SERV_TCP_PORT);
    fprintf(stderr, "\nPress Ctrl+C to stop the server\n");

    //
    // Loop forever accepting requests new connections
    // and starting reading from them.
    //
    for (;;)
    {
        struct ContextKey *pKey;

        clientAddressLength = sizeof(clientAddress);
        newsocket = accept(listener,
                           (struct sockaddr *)&clientAddress,
                           &clientAddressLength);
        if (newsocket < 0)
        {
            FatalError("accept() Failed");
            return EXIT_FAILURE;
        }

        // Create a context key and initialize it.
        // calloc will zero the buffer
        pKey = calloc(1, sizeof(struct ContextKey));
        pKey->sock = newsocket;
        pKey->ovOut.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
        // Set the event for writing so that packets
        // will not be sent to the completion port when
        // a write finishes.
        pKey->ovOut.hEvent = (HANDLE)((DWORD)pKey->ovOut.hEvent | 0x1);

        // Associate the socket with the completion port
        CreateIoCompletionPort(
            (HANDLE)newsocket,
            ghCompletionPort,
            (DWORD)pKey,   // No key
            0              // Use default # of threads
        );

        // Kick off the first read
        IssueRead(pKey);
    }
    return 0;
}