Ejemplo n.º 1
0
// ----------------------------------------------------------------------------
// CClientEngine::IssueHTTPGetL()
//
// Start a new HTTP GET transaction.
// ----------------------------------------------------------------------------
void CClientEngine::IssueHTTPGetL(const TDesC8& aUri)
	{
	SetupConnectionL();	
		
	// Parse string to URI (as defined in RFC2396)
	TUriParser8 uri;
	uri.Parse(aUri);

	// Get request method string for HTTP GET
	RStringF method = iSession.StringPool().StringF(HTTP::EGET,
		RHTTPSession::GetTable());

	// Open transaction with previous method and parsed uri. This class will
	// receive transaction events in MHFRunL and MHFRunError.
	iTransaction = iSession.OpenTransactionL(uri, *this, method);

	// Set headers for request; user agent and accepted content type
	RHTTPHeaders hdr = iTransaction.Request().GetHeaderCollection();
	SetHeaderL(hdr, HTTP::EUserAgent, KUserAgent);
	SetHeaderL(hdr, HTTP::EAccept, KAccept);

	// Submit the transaction. After this the framework will give transaction
	// events via MHFRunL and MHFRunError.
	iTransaction.SubmitL();

	iRunning = ETrue;
	_LIT(KConnecting,"Connecting...");
	iObserver.ClientEvent(KConnecting);
	}
Ejemplo n.º 2
0
void CSTTrackerConnection::HTTPSessionOpenedL(TBool aResult, RHTTPSession& /*aHTTPSession*/)
{
	if (aResult)
	{
		// starts listening before connecting to the tracker
		// TODO this should be called from the torrent / torrentmanager
		iTorrent.TorrentMgr()->NetworkManager()->StartListeningL(
				0, iTorrent.Preferences()->IncomingPort());
		
		CreateUriL();
		
		// Parse string to URI (as defined in RFC2396)
		TUriParser8 uri;
		uri.Parse(*iUri);

		// Get request method string for HTTP GET
		RStringF method = iSession.StringPool().StringF(HTTP::EGET,
			RHTTPSession::GetTable());
			


		// Open transaction with previous method and parsed uri. This class will
		// receive transaction events in MHFRunL and MHFRunError.
		iTransaction = iSession.OpenTransactionL(uri, *this, method);

		// Set headers for request; user agent and accepted content type
		RHTTPHeaders hdr = iTransaction.Request().GetHeaderCollection();
		SetHeaderL(hdr, HTTP::EUserAgent, KUserAgent);
		SetHeaderL(hdr, HTTP::EAccept, KAccept);

		// Submit the transaction. After this the framework will give transaction
		// events via MHFRunL and MHFRunError.
		LWRITE(iLog, _L("[Trackerconnection] Starting transaction: GET "));
		LWRITELN(iLog, *iUri);
		iTransaction.SubmitL();

		iRunning = ETrue;
		iConnectionTimeout->Reset(KMaxTrackerAnnounceTime * 1000);
	}
	else
	{
		LWRITE(iLog, _L("[Trackerconnection] Failed "));
		if (iObserver)
			iObserver->TrackerConnectionFailedL();
		
		/*iTorrent.SetFailedL(_L("Failed to establish network connection."));*/
	}
}
void CHttpController::SendRequestL( TInt aMethodIndex, const TDesC8& aUri, CHttpHeaders* aHeaders )
	{
	if ( !iObserver )
		{
		User::Leave( KErrHttpInvalidObserver );
		}
	RStringF method = iSession.StringPool().StringF( aMethodIndex, RHTTPSession::GetTable() );

	TUriParser8 uri;
	uri.Parse( aUri );
	iTransaction = iSession.OpenTransactionL( uri, *this, method );
	RHTTPHeaders hdr = iTransaction.Request().GetHeaderCollection();

	RArray< TInt > addedElements;
	CleanupClosePushL( addedElements );

	SetHeaderL( HTTP::EUserAgent, hdr, KUserAgent, addedElements );
	SetHeaderL( HTTP::EConnection, hdr, KClose, addedElements );
	SetHeaderL( HTTP::EAccept, hdr, KAccept, addedElements );
	SetHeaderL( HTTP::EHost, hdr, uri.Extract( EUriHost ), addedElements );

	TInt count( iPersistentHeaders->Count() );
	for ( TInt i( 0 ); i < count; ++i )
		{
		if ( addedElements.FindInOrder( i ) >= 0 )
			{
			continue;
			}
		SetHeaderL( hdr, iPersistentHeaders->Key( i ), iPersistentHeaders->Value( i ) );
		}

	CleanupStack::PopAndDestroy( &addedElements );
	if ( aHeaders )
		{
		TInt count( aHeaders->Count() );
		for ( TInt i( 0 ); i < count; ++i )
			{
			SetHeaderL( hdr, aHeaders->Key( i ), aHeaders->Value( i ) );
			}
		}

	if ( aMethodIndex == HTTP::EPOST )
		{
		const TInt KMaxContentLenBufferLength = 100;
		TBuf8< KMaxContentLenBufferLength > contentLength;
		contentLength.Num( iOutputEncoder->OverallDataSize() );
		SetHeaderL( hdr, HTTP::EContentLength, contentLength );
		SetHeaderL( hdr, HTTP::EContentType, KUrlEncodedContentType );
		iTransaction.Request().SetBody( *iOutputEncoder );
		}
	iTransaction.SubmitL();
	StartTimeout();
	iState = EHttpActive;
	}
void CHttpController::SetHeaderL( TInt aHeaderId, RHTTPHeaders& aHeaders,
		const TDesC8& aHdrDefaultValue, RArray< TInt >& aAddedElements )
	{
	HBufC8* headerName = HeaderNameLC( aHeaderId );
	TInt error = iPersistentHeaders->Find( *headerName );
	SetHeaderL( aHeaders, *headerName, error >= 0 ? iPersistentHeaders->Value( error ) : aHdrDefaultValue );
	CleanupStack::PopAndDestroy( headerName );
	if ( error >= 0 )
		{
		aAddedElements.InsertInOrderL( error );
		}
	}
/**
 * CSymbianTransportAgent::sendMessage()
 */
char* CSymbianTransportAgent::sendMessage(const char* msg)
{
    LOG.debug("entering CSymbianTransportAgent::sendMessage"); 
    
    // Check if user aborted current sync.
    if (getLastErrorCode() == KErrCancel) {
        LOG.debug("Leaving sendMessage - lastErrorCode is %d", getLastErrorCode());
        User::Leave(KErrCancel);    // leave is trapped at SyncActiveObject::RunL().
    }
    
    // Just to be sure the response buffer is ok
    //TO BE VERIFIED!!!!
    delete iResponseBody;
    iResponseBody = NULL; 
    
    // Set the POST body
    delete iPostBody;
    iPostBody = NULL;

    if (url.fullURL == NULL) {
        setErrorF(ERR_CONNECT, "Empty URL"); 
        LOG.error("Transport Agent: empty URL");
        return NULL;
    }

    char* response = NULL;
    RStringF method;
    RHTTPHeaders hdr;
    // Parse string to URI (as defined in RFC2396)
    TUriParser8 uri;
    HBufC8* fullUrl = charToNewBuf8(url.fullURL); 
    TInt parseErr = uri.Parse(*fullUrl);
    if (parseErr != KErrNone) {
        setErrorF(ERR_CONNECT, "Malformed URL"); 
        LOG.error("Transport Agent: malformed url");
        goto finally;
    }

    {
        TPtrC8 ptr(reinterpret_cast<const TUint8*>(msg));
        iPostBody = HBufC8::NewL(ptr.Length());
        iPostBody->Des().Copy(ptr);
    }
    
    FConnection* connection = FConnection::getInstance();
    if (connection->isConnected() == false) {
        int res = connection->startConnection();
        if (res) {
            setErrorF(ERR_CONNECT, "Connection error (%d): please check your internet settings.", res); 
            LOG.error("%s", getLastErrorMsg());
            goto finally;
        }
    }

    // Get request method string for HTTP POST
    method = iHttpSession.StringPool().StringF( HTTP::EPOST, RHTTPSession::GetTable());

    // Open transaction with previous method and parsed uri. This class will 
    // receive transaction events in MHFRunL and MHFRunError.
    iHttpTransaction = iHttpSession.OpenTransactionL( uri, *this, method );

    // Set headers for request; user agent, accepted content type and body's 
    // content type.
    hdr = iHttpTransaction.Request().GetHeaderCollection();
    SetHeaderL(hdr, HTTP::EUserAgent, _L8("Funambol Symbian SyncML client"));
    SetHeaderL(hdr, HTTP::EAccept, _L8("*/*"));
    SetHeaderL(hdr, HTTP::EContentType, _L8("application/vnd.syncml+xml"));

    LOG.debug("Sending message:");
    LOG.debug("%s", msg);

    // Set data supplier for POST body
    // Please see  » Symbian OS v9.1 » Symbian OS guide » Using HTTP Client »
    // Handling request body data for explanation on this part
    iDataSupplier = this;
    iHttpTransaction.Request().SetBody(*iDataSupplier);     

    // Submit the transaction. After this the framework will give transaction
    // events via MHFRunL and MHFRunError.
    iHttpTransaction.SubmitL();

    // Start the scheduler, once the transaction completes or is cancelled on an
    // error the scheduler will be stopped in the event handler
    // This is a trick to implement a synchronous method
    LOG.debug("starting ASync scheduler...");
    iASWait->Start();  // TO BE VERIFIED!!!!
    LOG.debug("ASync scheduler stopped");
    
    
    // Check if user aborted current sync.
    if (getLastErrorCode() == KErrCancel) {
        LOG.debug("Leaving sendMessage - lastErrorCode is %d", getLastErrorCode());
        User::Leave(KErrCancel);    // leave is trapped at SyncActiveObject::RunL().
    }
    
    // when all is finished, return char* to be delete []
    if(!iTransFailed) {
        TInt length = iResponseBody->Des().Length();
        response = new char[length+1];
        Mem::Copy(response, iResponseBody->Ptr(), length);
        response[length] = '\0';

        LOG.debug("Message received:");
        LOG.debug("%s", response);
    }
    else {
        LOG.debug("HTTP transaction failed");
        setErrorF(ERR_HTTP, "HTTP request error: request timed out waiting for response");
    }

finally:

    // Transaction can be closed now. It's not needed anymore.
    LOG.debug("closing HTTP transaction");
    iHttpTransaction.Close();

    delete fullUrl;
    LOG.debug("exiting CSymbianTransportAgent::sendMessage");
    return response;
}
// ----------------------------------------------------------------------------
// CWmDrmDlaDefaultHttpManager::SubmitL
// Handler for the states EOpen and EReconnect.
// ----------------------------------------------------------------------------
void CWmDrmDlaDefaultHttpManager::SubmitL()
    {
    LOGFN( "CWmDrmDlaDefaultHttpManager::SubmitL" );

    TConnectionInfo info;
    GetConnectionInfoL( info );
    iIapNumber = info.iIapId;

    // Close old session:
    iHttpSession.Close();    

    // Open session
    iHttpSession.OpenL();
    RStringPool pool = iHttpSession.StringPool();

    // Associate HTTP session with connection
    RHTTPConnectionInfo connInfo = iHttpSession.ConnectionInfo();

    // Specify socket server
    SET_HTTP_PROPERTY( connInfo, pool, HTTP::EHttpSocketServ,
        iSocketServer.Handle() );
    // Specify connectionn to use
    TInt connPtr = reinterpret_cast<TInt>(&iConnection);
    SET_HTTP_PROPERTY( connInfo, pool, HTTP::EHttpSocketConnection, connPtr );

    // Install HTTP authentication filter
    InstallAuthenticationL( iHttpSession );

    CHttpCookieFilter::InstallFilterL( iHttpSession );

    RHTTPFilterCollection filterColl = iHttpSession.FilterCollection();
    filterColl.RemoveFilter(
        iHttpSession.StringPool().StringF(
            HTTP::ERedirect, RHTTPSession::GetTable() ) );

    CHttpUAProfFilterInterface::InstallFilterL( iHttpSession );

    // Parse URI
    TUriParser8 srcAddress;
    User::LeaveIfError( srcAddress.Parse( *iSrcAddress ) );

    // Open HTTP transaction
    iHttpTransaction = iHttpSession.OpenTransactionL( srcAddress, *this,
        HTTP_STRING( (EGet == iOperation) ? HTTP::EGET : HTTP::EPOST ) );
    iTransactionOpen = ETrue;

    // Set the data supplier if a POST operation
    if ( EPost == iOperation )
        {
        iHttpTransaction.Request().SetBody( *iDataSupplier );
        }


    TInt pos = iSrcAddress->Locate( '?' );

    // If no query ('?') pos is rightmost character
    pos = (pos != KErrNotFound) ? pos : iSrcAddress->Length();
    TPtrC8 ptrUrl = iSrcAddress->Left( pos );

    // Only print if there is a ('?') and something to print after it
    if ( pos < iSrcAddress->Length() )
      {
      TPtrC8 ptrQs = iSrcAddress->Mid( pos );
      }
    // Set HTTP headers for the transaction
    RHTTPHeaders hdr = iHttpTransaction.Request().GetHeaderCollection();
    TInt nofheaders = iHdrValues.Count();

    for ( TInt i = 0; i < nofheaders; i++ )
        {
        TInt field = iHdrFields[i];
        const TDesC8& fieldStr = HTTP_STRING( field ).DesC();
        HBufC8* pValue = iHdrValues[i];
        SetHeaderL( hdr, field, *pValue );
        }

    // Submit HTTP transaction
    // This will set in motion the HTTP download
    iHttpTransaction.SubmitL();
    iState = ESubmit;
    }
Ejemplo n.º 7
0
// ---------------------------------------------------------
// CMmsSession::OpenL
// ---------------------------------------------------------
//
EXPORT_C void CMmsSession::OpenL( 
    const TDesC8& aProxyAddress,
    const TBool aUseProxy,  
    const TInt32 aMaxReceiveSize,
    const TInt32 aMaxSendSize,
    TRequestStatus& aStatus )
    {
    LOG( _L("CMmsSession::OpenL") );
    __ASSERT_DEBUG( iSessionStatus == ESessionIdle, gPanic( EMmsAlreadyBusy ) );

    iError = KErrNone;
    iRequestStatus = &aStatus;

    // 
    // Setting max send/receive sizes. 0 means not limited.
    // Values always come from CMmsSettings.
    // 
    iMaxReceiveSize = aMaxReceiveSize;
    iMaxSendSize = aMaxSendSize;
  
    // Get pointer HTTP session headers
    iSessionHeaders = iHTTPSession.RequestSessionHeadersL();
    iHeadersCreated = ETrue;

    // Check if we are connected already
    if ( iConnected )
        {
        aStatus = KRequestPending;                             
        User::RequestComplete( iRequestStatus, KMmsErrorSessionAlreadyOpen );
        }
    else 
        {

        // set the session properties
        // the handle comes from iHTTP session. I think we should not close it.
        RStringPool strPool = iHTTPSession.StringPool();
        RHTTPConnectionInfo connInfo = iHTTPSession.ConnectionInfo();
        connInfo.SetPropertyL( strPool.StringF( HTTP::EHttpSocketServ, RHTTPSession::GetTable() ),
            THTTPHdrVal( iSocketServ->Handle() ) );
        TInt connPtr = REINTERPRET_CAST( TInt, iConnection );
        connInfo.SetPropertyL(
            strPool.StringF( HTTP::EHttpSocketConnection, RHTTPSession::GetTable() ),
            THTTPHdrVal( connPtr ) );

        // Add proxy usage if requested
        if ( aUseProxy )
            {
            THTTPHdrVal proxyUsage( strPool.StringF( HTTP::EUseProxy, RHTTPSession::GetTable() ) );
            connInfo.SetPropertyL(
                strPool.StringF( HTTP::EProxyUsage, RHTTPSession::GetTable() ), proxyUsage );
        
            RStringF proxyString = strPool.OpenFStringL( aProxyAddress );
            CleanupClosePushL( proxyString );
            THTTPHdrVal proxyAddr( proxyString );
            connInfo.SetPropertyL(
                strPool.StringF( HTTP::EProxyAddress, RHTTPSession::GetTable() ), proxyAddr );
            CleanupStack::PopAndDestroy( &proxyString );
            }
            
		// Install MMS X-id header filter if required
    	FeatureManager::InitializeLibL();
    	if ( FeatureManager::FeatureSupported( KFeatureIdMmsXidHeaderHttpFilter ) )  
	        {
	        // Install the MMS X-id header filter explicitly, since only MMS requires this filter.
			const TUid KHttpFilterMmsXidHeaderImplementationUid = { 0x1020738D };
			CEComFilter::InstallFilterL(iHTTPSession, KHttpFilterMmsXidHeaderImplementationUid);
	        }
    	FeatureManager::UnInitializeLib();
    	
        // Install UAProf filter
        TInt error = KErrNotFound;
        TRAP( error, CHttpUAProfFilterInterface::InstallFilterL( iHTTPSession ) );
        if ( error != KErrNone )
            {
            LOG2( _L("ERROR: UAProf filter left with code %d. Using hardcoded UserAgent string.."), error );
            
            // Manually set UA string
            SetFixedUserAgentL();

            // UserAgent header must be added always - either hard coded string or string from ini file
            SetHeaderL( iSessionHeaders, HTTP::EUserAgent, iUserAgent->Des() );

            // Add UAProf if available
            if ( iUaProf && iUaProf->Length() > 0 )
                {
                RStringF tempString = strPool.OpenFStringL( iUaProf->Des() );
                CleanupClosePushL( tempString );
                RStringF tempString2 = strPool.OpenFStringL( KXProfile );
                CleanupClosePushL( tempString2 );
                iSessionHeaders.SetFieldL( tempString2, tempString );
                CleanupStack::PopAndDestroy( &tempString2 );
                CleanupStack::PopAndDestroy( &tempString );
                }
            }

        // Accept headers moved to transaction as global filter overrides
        // session headers

        // HTTP session, no need for separate connect procedure
        iConnected = ETrue;
        // We may or may not get
        iHTTPSession.SetSessionEventCallback( this );
        aStatus = KRequestPending;
        User::RequestComplete( iRequestStatus, KErrNone );
        }
    }
Ejemplo n.º 8
0
//Invoke http method
void CHttpClient::InvokeHttpMethodL(TInt aCommand)
{
    RStringF method;
    iHasARequestBody = EFalse;

    if ( iConnectionManager && !iConnectionManager->IsOfflineMode())
    {
        iConnectionManager->SetupConnection();

        RStringPool strP = iConnectionManager->GetHTTPSession().StringPool();

        switch (aCommand)
        {
        case CHttpConstants::EGet:
            method = strP.StringF(HTTP::EGET,RHTTPSession::GetTable());
            break;
        case CHttpConstants::EPost:
            method = strP.StringF(HTTP::EPOST,RHTTPSession::GetTable());
            iHasARequestBody = ETrue;
            break;
        default:
            return;//other commands not supported
        }

        //read body and url
        GetRequestBodyL();

        TInt realSize = 0;
        for ( TInt i = 0; i < CHttpConstants::KMaxUrlSize && iUriPtr[i]; i++)
        {
            realSize++;
        }

        TBuf8<CHttpConstants::KMaxUrlSize> tmp;
        tmp.Copy(iUriPtr.Ptr(), realSize);
        tmp.ZeroTerminate();

        TUriParser8 uri;
        uri.Parse(tmp);

        iTrans = iConnectionManager->GetHTTPSession().OpenTransactionL(uri, *iTransObs, method);
        RHTTPHeaders hdr = iTrans.Request().GetHeaderCollection();

        // Add headers appropriate to all methods
        SetHeaderL(hdr, HTTP::EUserAgent, KUserAgent);
        SetHeaderL(hdr, HTTP::EAccept, KAccept);

        // Add headers and body data for methods that use request bodies
        if (iHasARequestBody)
        {
            // Content type header
            TBuf8<CHttpConstants::KMaxContentTypeSize> contTypeBuf;
            contTypeBuf.Copy(_L("text/html"));
            RStringF contTypeStr = iConnectionManager->GetHTTPSession().StringPool().OpenFStringL(contTypeBuf);
            THTTPHdrVal contType(contTypeStr);
            hdr.SetFieldL(iConnectionManager->GetHTTPSession().StringPool().StringF(HTTP::EContentType,RHTTPSession::GetTable()), contType);
            contTypeStr.Close();

            MHTTPDataSupplier* dataSupplier = this;
            iTrans.Request().SetBody(*dataSupplier);
        }

        // submit the transaction
        iTrans.SubmitL();

        // Start the scheduler, once the transaction completes or is cancelled on an error the scheduler will be
        // stopped in the event handler
        CActiveScheduler::Start();

        //close and delete request file
        iReqBodyFile.Close();
        iFileServ.Delete(iReqBodyFilePath);
    }
}