EXPORT_C
#if defined (_DEBUG)
/**
Function to do a write of the supplied data, literally where possible.
@param aData The descriptor that holds the supplied data.
*/
void THttpLogger::WriteComment(const TDesC8& aData)
//Do a write of the supplied data, literally where possible
	{
	if(iLogger)
		{
		// If the connection to flogger was made
		if(iLogger->Handle() != 0)
			{
			TPtrC8 line;
			line.Set(aData);
			while (line.Length() > KMaxLogLineLength)
				{
				iLogger->Write(line.Left(KMaxLogLineLength));
				line.Set(line.Right(line.Length() - KMaxLogLineLength));
				}
			
			iLogger->Write(line.Left(line.Length()));
			}
		}
	}
// -----------------------------------------------------------------------------
// Get value for given id.
// -----------------------------------------------------------------------------
//
HBufC8* CConfigurationHandler::GetTokenValue( const TDesC8& aData, 
											  const TDesC8& aKey )
	{
	if( aData.Find(aKey)==KErrNotFound )
		{
		return NULL;
		}

	// id is in the string
	TLex8 lex(aData);

	while( !lex.Eos() )
		{
		TPtrC8 token = lex.NextToken();

		TInt spos = token.Find(aKey);
		if( spos==KErrNotFound )
			{
			continue;
			}

		// key was found return value		
		
		TPtrC8 value = token.Right(token.Length()-aKey.Length()); 

		HBufC8* retval = HBufC8::NewL(value.Length());
		TPtr8 des = retval->Des();
		des.Append(value);
		return retval;
		}
		
	return NULL;
	}
// -----------------------------------------------------------------------------
// CContactSubscriber::RunL()
// Assyncronous request handler , on completion of notification
// -----------------------------------------------------------------------------
//
void CContactSubscriber::RunL()
{
    __TRACE_CALLSTACK;
    SubscribeChangeNotiFication();
    // property updated, get new value 
    TBuf8 <KBufferSize> value; 
    TPtrC8  id; 
    TPtrC8  sourceType; 
    TPtrC8  addressCount; 
    
    if ( KErrNone == iProperty.Get( value ) )
    { 
        TInt pos =  value.Locate(TChar('-')); 
        id.Set( value.Left(pos) ); 
        
        TPtrC8 ptr = value.Right(3); 
        sourceType.Set(ptr.Left(1)); 
        addressCount.Set(ptr.Right(1)); 
        
        TInt appId = -1, addressType = -1, addressTypeCount = -1; 
        TLex8 lex(id); 
        lex.Val(appId); 
        
        TLex8 lex1(sourceType); 
        lex1.Val( addressType ); 
        
        TLex8 lex2(addressCount); 
        lex2.Val(addressTypeCount); 
        
        iNotifyChange.GetChangeNotificationL( appId, addressType,addressTypeCount ); 
    } 
}
// -----------------------------------------------------------------------------
// CUpnpDevice::DescriptionUrlPort
// Retrun description URL port.
// -----------------------------------------------------------------------------
//
EXPORT_C TInt CUpnpDevice::DescriptionUrlPort() const
    {
    if ( iAddress != TInetAddr( INET_ADDR( 0,0,0,0 ), 0) )
        {
        return iAddress.Port();
        }

    const TDesC8& url = DescriptionUrl();

    if ( url.Length()> KHttp().Length() )
        {
        TPtrC8 addrAndPath = url.Right( url.Length() - KHttp().Length() );

        TInt separIndex = addrAndPath.Find( KSepar() );

        if ( separIndex == KErrNotFound )
            {
            return KDefaultDescriptionUrlPort;
            }

        TInt slashIndex = addrAndPath.Find( KSlash8() );

        if ( slashIndex != KErrNotFound )
            {
            TPtrC8 port = addrAndPath.Mid(
                    separIndex + 1, slashIndex - separIndex
            );

            TLex8 lex( port );
            TInt prt;
            TInt err = lex.Val( prt );
            if( KErrNone != err )
                {
                return KErrNotFound;
                }

            return prt;
            }
        else
            {
            TPtrC8 port = addrAndPath.Right(
                    addrAndPath.Length() - ( separIndex + 1 )
            );

            TLex8 lex( port );
            TInt prt;
            TInt err = lex.Val( prt );
            if( KErrNone != err )
                {
                return KErrNotFound;
                }

            return prt;
            }
        }

    return KDefaultDescriptionUrlPort;
    }
CSenElement* CPolicyNormalizer::ProcessPolicyReferenceL(CSenElement* aPolicy, CPolicyRegistry* aRegistry)
{    //Loop for wsp:PolicyReference element and if found then replace
    // it with wsp:All and copy everything from found policy to here
    if(aRegistry == NULL)
        return NULL;
    //Check if there is a reference if yes then resolve it
    RPointerArray<CSenElement> referenceChildren;
    
    if(aPolicy->ElementsL(referenceChildren, KWsPolicyReference) == KErrNone)
        {
        TInt childCount = referenceChildren.Count();
        TInt i = 0;
        CSenElement* pNextChild;

        while (i < childCount)
            {
            pNextChild = referenceChildren[i];
            TPtrC8 localName = pNextChild->LocalName();
            TPtrC8 uri = GetReferenceUriL(pNextChild);
            _LIT8(KHash, "#");
            
            HBufC8* aRippedUri = NULL;
             
            if(uri.Left(1).Compare(KHash) == 0)
               aRippedUri = uri.Right(uri.Length()-1).AllocL();
            
            if(aRippedUri->Length() > 0)
                {
                CSenElement* referedPolicy = aRegistry->LookupPolicy(aRippedUri->Des());
                if(referedPolicy)
                    {
                    ReplacePolicyReferenceL(pNextChild,referedPolicy);
                    }
                }
                delete aRippedUri;
                
            i++;
            }
        }
        
    //Check in all children recursively PolicyReferences and resolve them
    RPointerArray<CSenElement>& children = aPolicy->ElementsL();
    TInt childCount = children.Count();    

    CSenElement* pNextChild;
    TInt i=0;

    while (i < childCount)
    {
        pNextChild = children[i];
        TPtrC8 localName = pNextChild->LocalName();
        ProcessPolicyReferenceL(pNextChild, aRegistry);
        i++;
    }
    
  return NULL;  
}
Exemple #6
0
// ---------------------------------------------------------
// CDdEng::ParseLicenseL()
// ---------------------------------------------------------
//
void CDdEng::ParseLicenseL()
{
	HBufC8* descriptorBuf = CodUtil::ConvertLC( iCodBuf->Des());
	TPtrC8 license;
	TPtrC8 descriptor (descriptorBuf->Ptr());
	TInt startTag = descriptor.Find(KLicenseStartTag); // "<license"
	if (startTag != KErrNotFound)
	{
		descriptor.Set(descriptor.Right(descriptor.Length()- startTag -1));
		TInt endTag = descriptor.Locate(KElementEnd); //'>'
		if (endTag != KErrNotFound)
		{
			license.Set(descriptor.Right(descriptor.Length()-endTag-1));
			TInt licenseTagEnd = license.Find(KLicenseEndTag); // "</license"
			if (licenseTagEnd != KErrNotFound)
			{
				license.Set(license.Left(licenseTagEnd));
			}
		}
	}
	iSaver->AppendData( license );
	CleanupStack::PopAndDestroy( descriptorBuf );
}
TInt CVersionFileReader::ReadNewVersionFileL(const TDesC& versionFile)
{
   iNewVersionArray->Reset();
   class RFs& fs = CCoeEnv::Static()->FsSession();
   class RFile file;
   TInt ret = file.Open(fs, versionFile, 
                        EFileStreamText | EFileRead);
   if(ret != KErrNone) {
      /* Could not open file, return the error code */
      return ret;
   }
   
   HBufC8* line = HBufC8::NewLC(40);
   TInt pos = -1;
   file.Seek(ESeekStart, pos);
   TPtr8 pLine = line->Des();
   ret = file.Read(pLine);
   if(line->Length() == 0) {
      // Empty file
      file.Close();
      return KErrEof;
   }
   file.Close();

   // The file contains a string that should match this regex:
   // [0-9]+\.[0-9]+\.[0-9]\+:[0-9]+\.[0-9]+\.[0-9]\+:[0-9]\+
   // The string is separated into three parts by ':'. 
   // The first part is the application version
   // The second part is the resource version
   // The third part is the mlfw version.
   const TChar colon = ':';
   const TChar dot = '.';
   while(line->Length() > 0) {
      if(line->Locate(colon) != KErrNotFound) {
         TPtrC8 part = line->Left(line->Locate(colon));
         TPtrC8 version = part.Left(part.LocateReverse(dot));
         TPtrC8 misc = part.Right(part.Length() - part.LocateReverse(dot) - 1);
         iNewVersionArray->AppendL(part);
         iNewVersionArray->AppendL(version);
         iNewVersionArray->AppendL(misc);
         line->Des().CopyF(line->Right(line->Length() - line->Locate(colon) - 1));
      } else {
         iNewVersionArray->AppendL(*line);
         break;
      }
   }
   CleanupStack::PopAndDestroy(line);
   return 0;
}
EXPORT_C
#if defined (_DEBUG)
void TInuLogger::WriteComment(const TDesC8& aData)
//Do a write of the supplied data, literally where possible
	{
	TPtrC8 line;
	line.Set(aData);
	while (line.Length() > KMaxLogLineLength)
		{
		iLogger.Write(line.Left(KMaxLogLineLength));
		line.Set(line.Right(line.Length() - KMaxLogLineLength));
		}
	
	iLogger.Write(line.Left(line.Length()));
	}
// -----------------------------------------------------------------------------
// CUpnpDevice::DescriptionUrlPath
// Return description URL path.
// -----------------------------------------------------------------------------
//
EXPORT_C const TPtrC8 CUpnpDevice::DescriptionUrlPath() const
    {

    const TDesC8& url = DescriptionUrl();

    if ( url.Length()> KHttp().Length() )
        {
        TPtrC8 addrAndPath = url.Right( url.Length() - KHttp().Length() );

        TInt index = addrAndPath.Find( KSlash8() );

        if ( index != KErrNotFound )
            {
            TPtrC8 addr = addrAndPath.Right( addrAndPath.Length() - index );
            return addr;
            }
        }
    return TPtrC8( KNullDesC8 );
    }
Exemple #10
0
// -----------------------------------------------------------------------------
// MceSip::ToSIPExtensionHeadersL
// -----------------------------------------------------------------------------
//
void MceSip::ToSIPExtensionHeadersL( RPointerArray<CSIPHeaderBase>& aSIPHeaders, 
                                     const MDesC8Array& aHeaders )
    {
    
	for ( int i = 0; i < aHeaders.MdcaCount(); i++ )
		{
		TPtrC8 param = aHeaders.MdcaPoint( i );
		TInt index = param.Locate( KMceSipSeparator );
		if ( index != KErrNotFound && 
					param.Left( index ) != KMceSipSubscriptionStateHeader )
			{
    		CSIPExtensionHeader* extHeader = CSIPExtensionHeader::NewL( 
    		                param.Left(index), 
    			            param.Right( param.Length() - ( index + 1 ) ) );
    		CleanupStack::PushL( extHeader );
    		User::LeaveIfError( aSIPHeaders.Append( extHeader ) );
    		CleanupStack::Pop( extHeader );
			}
		}
    }
void CSatNotifySendSs::CheckCallForwarding
		( 
    	TPtrC8 aSource,               
    	RSat::TSsString& aSsString 
    	)
    {
    OstTraceDef0(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CSATNOTIFYSENDSS_CHECKCALLFORWARDING_1, "CSAT:: CSatNotifySendSs::CheckCallForwarding");
    _LIT8(KCFU,"*21*");    // Call forwarding unconditional (CFU)
    _LIT8(KCFB,"*67*");    // Call forwarding on Mobile Subscriber Busy(CFB)
    _LIT8(KCFNRy, "*61*"); // Call forwarding on No Reply (CFNRy)
    _LIT8(KCFNRc, "*62*"); // Call forwarding on Mobile Subscriber Not 
                           // Reachable (CFNRc)    
    // Try to find call forwarding string
    TInt pos( aSource.Find( KCFU ) );
    if ( KErrNotFound == pos )
        {
        pos = aSource.Find( KCFB );
        }
    if ( KErrNotFound == pos )
        {
        pos = aSource.Find( KCFNRy );
        }
    if ( KErrNotFound == pos )
        {
        pos = aSource.Find( KCFNRc );
        }
    if ( KErrNotFound != pos )
        {
        OstTraceDef0(OST_TRACE_CATEGORY_DEBUG, TRACE_INTERNALS, CSATNOTIFYSENDSS_CHECKCALLFORWARDING_2, "CSAT:: CSatNotifySendSs::CheckCallForwarding, String is for call forwarding");
        aSsString.iSsString.Zero();
        aSsString.iSsString.Append( aSource.Left( pos + 4 ) );
        aSsString.iSsString.Append( KPlusMarkCharacterCode );
        aSsString.iSsString.Append( 
            aSource.Right( aSource.Length() - ( pos + 4) ) );
        }
    }
// ---------------------------------------------------------------------------
// CAtSmsReceive::CMTResponseFirstLineL
// other items were commented in a header
// ---------------------------------------------------------------------------
void  CAtSmsReceive::CMTResponseFirstLineL()
	{
	LOGTEXT(_L8("CAtSmsReceive::CMTResponseFirstLineL Enter funciton"));
	iError = KErrNone;
	TPtrC8 firstLineBuf;
	firstLineBuf.Set(Buffer());
	TInt pos = firstLineBuf.FindF(KCMTResponseString);
	if (pos == KErrNotFound)
		{
		LOGTEXT(_L8("CAtSmsReceive::CMTResponseFirstLineL()\tError - Cannot find '+CMT:' string"));
		iError = KErrNotFound;
		return;
		}
	//skip the string of +CMT:
	pos += KCMTResponseString().Length();
	//skip a  "," character
	while(!(TChar(firstLineBuf[pos]).IsDigit()))
		{
		++pos;
		}
	TInt lenPos = firstLineBuf.Length()-pos;
	TPtrC8 pduLenBuf;
	pduLenBuf.Set(firstLineBuf.Right(lenPos));
	
	
	TLex8 lex(pduLenBuf);
	TUint16 val;
	TInt ret = lex.Val(val,EDecimal);
	if(ret != KErrNone)
		{
		iError = ret;
		return;
		}
	iPduLen = val;
    LOGTEXT2(_L8("New SMS detected of length %d"),iPduLen);
	}
// ---------------------------------------------------------------------------
// CUpnpHttpFileTransferWriter::StartL
// Sends the HTTP headers of the content
// ---------------------------------------------------------------------------
//
void CUpnpHttpFileTransferWriter::SendHeadersL()
    {
    if(iState == EHeaders)
    	if( iSession.FileAccess() )
    		if(!IsActive())
    			{ 
    			//in case session not connected,waiting...
    			if(!iSession.IsConnected())
					{
					iWaiting = ETrue;
					return;
					}   			
				iSendBuffer.Zero();
				
				if ( ( iSession.FileAccess()->GetHeaders().Length() -
				       iSession.FileAccess()->TransferredBytes()) <= 
		               iSendBuffer.MaxLength() )
					{
					TPtrC8 headerPointer;
					headerPointer.Set(iSession.FileAccess()->GetHeaders());
					headerPointer.Set( headerPointer.Right( 
		            iSession.FileAccess()->GetHeaders().Length()-
		                iSession.FileAccess()->TransferredBytes()) );
				
					iSendBuffer.Append( headerPointer );			
					iSession.FileAccess()->SetHeadersSent();

                    // Adding file content to the header
                    TInt length = iSendBuffer.MaxLength()-iSendBuffer.Length();
                    						
                    HBufC8* tmpBuffer = HBufC8::NewLC(length);
					
                    iSendPointer.Set(tmpBuffer->Des());
                    if( iSession.FileAccess()->GetL(iSendPointer,length) )
                        {
                        iState = EFinished;
                        }
                    iSendBuffer.Append(iSendPointer);
                    CleanupStack::PopAndDestroy( tmpBuffer );
					}
				else
					{
					TPtrC8 headerPointer;
					headerPointer.Set( iSession.FileAccess()->GetHeaders() );
					headerPointer.Set( headerPointer.Right( 
		            iSession.FileAccess()->GetHeaders().Length() -
		                iSession.FileAccess()->TransferredBytes() ) );
					headerPointer.Set( headerPointer.Left( 
		                iSendBuffer.Length() ) );
					
					iSendBuffer.Append( headerPointer );				
					iSession.FileAccess()->SetPosOfHeader( 
					    iSession.FileAccess()->TransferredBytes() + headerPointer.Length() );							
					}
		    	
		    	iSendPointer.Set((TUint8*)iSendBuffer.Ptr(),iSendBuffer.Length(),iSendBuffer.MaxLength());
    	   		
    	   		iSession.TimerCancel();        
	        	WriteToSocket();
	        	iSession.StartTimeoutTimer(ETrue);
	        	
	        	if(!iHttpPostStarted)
	        		{
	        		iSession.NotifyUpperLayersOnPostL();
	        		iHttpPostStarted = ETrue;
	        		}
	        		
    			}
    }          
// ---------------------------------------------------------------------------
// CNSmlDmACLParser::ParseL()
// Parses ACL data and keeps data until Reset() is called or instance
// is destructed
// ---------------------------------------------------------------------------
TInt CNSmlDmACLParser::ParseL(const TDesC8& aACL)
	{
	Reset();
	for(TInt i=EAclExecute;i>=EAclAdd;i--)
		{
		TInt aclStart = 0;
		TBool found=EFalse;
		switch(i)
			{
			case EAclAdd:
				aclStart = aACL.Find(KNSmlDmAclAddEqual);
				found = aclStart>=0;
				aclStart=aclStart+KNSmlDmAclAddEqual().Length();
				break;
			case EAclReplace:
				aclStart = aACL.Find(KNSmlDmAclReplaceEqual);
				found = aclStart>=0;
				aclStart=aclStart+KNSmlDmAclReplaceEqual().Length();
				break;
			case EAclDelete:
				aclStart = aACL.Find(KNSmlDmAclDeleteEqual);
				found = aclStart>=0;
				aclStart=aclStart+KNSmlDmAclDeleteEqual().Length();
				break;
			case EAclGet:
				aclStart = aACL.Find(KNSmlDmAclGetEqual);
				found = aclStart>=0;
				aclStart=aclStart+KNSmlDmAclGetEqual().Length();
				break;
			case EAclExecute:
				aclStart = aACL.Find(KNSmlDmAclExecEqual);
				found = aclStart>=0;
				aclStart=aclStart+KNSmlDmAclExecEqual().Length();
				break;
			default:
				User::Panic(KSmlDmTreeDbHandlerPanic,KErrArgument);
				break;

			}
		if(found)
			{
			TInt aclStop = aACL.Right(aACL.Length()-aclStart).
				Locate(KNSmlDMAclCommandSeparator);

			if(aclStop<0)
				{
				aclStop = aACL.Length()-aclStart;
				}

			TPtrC8 commandAcl = aACL.Mid(aclStart,aclStop);

			CNSmlAclElement* aclElement = new(ELeave) CNSmlAclElement();

			aclElement->iCommandType = (TNSmlDmCmdType)i;
			aclElement->iNext = iCommandAcls;
			iCommandAcls=aclElement;

			if(commandAcl.Compare(KNSmlDmAclAll)==0)
				{
				aclElement->iAllServers=ETrue;
				}
			else
				{
				TBool end = EFalse;

				TInt serverIdStart=0;
				while(!end)
					{
					TPtrC8 serverIdPtr =
						commandAcl.Right(commandAcl.Length()-serverIdStart);
						
					TInt serverIdStop =
						serverIdPtr.Locate(KNSmlDMAclSeparator);
						
					if(serverIdStop == KErrNotFound)
						{
						serverIdStop=commandAcl.Length();
						end=ETrue;
						}
					HBufC8* serverId =
						serverIdPtr.Left(serverIdStop).AllocL();
						
					aclElement->iServerIds.AppendL(serverId);
					serverIdStart=serverIdStart+serverIdStop+1;
					}
				}
			}
		}
	return KErrNone;
	}
// Parses Ecmt packets
void CEcmtMidpDebugPlugin::HandleNotifyL(const CEcmtMessageEvent& aEvent)
{
    static const TInt KMinMsgSize[] = {
        0,
        ECMT_MIDP_DEBUG_OPEN_SIZE,
        ECMT_MIDP_DEBUG_CLOSE_SIZE,
        ECMT_MIDP_DEBUG_SEND_MIN_SIZE,
        ECMT_MIDP_DEBUG_CONNECT_SIZE,
        ECMT_MIDP_DEBUG_RESET_SIZE
    };

    static const TInt KMaxMsgSize[] = {
        0,
        ECMT_MIDP_DEBUG_OPEN_SIZE,
        ECMT_MIDP_DEBUG_CLOSE_SIZE,
        ECMT_MIDP_DEBUG_SEND_MAX_SIZE,
        ECMT_MIDP_DEBUG_CONNECT_SIZE,
        ECMT_MIDP_DEBUG_RESET_SIZE
    };

    const TPtrC8 msg = iMessaging->Message(aEvent);
    TInt msglen = msg.Length();
    if (msglen >= ECMT_MIDP_DEBUG_HEADER_SIZE)
    {
        // Decode the header
        TUint opcode = msg[ECMT_MIDP_DEBUG_HEADER_OPCODE_OFFSET];
        TUint sid = (msg[ECMT_MIDP_DEBUG_HEADER_SID_OFFSET] << 24) | 
            (msg[ECMT_MIDP_DEBUG_HEADER_SID_OFFSET+1] << 16) |
            (msg[ECMT_MIDP_DEBUG_HEADER_SID_OFFSET+2] << 8) |
            (msg[ECMT_MIDP_DEBUG_HEADER_SID_OFFSET+3]);

        // Check opcode
        if (opcode < ECMT_MIDP_DEBUG_OPCODE_MIN ||
            opcode > ECMT_MIDP_DEBUG_OPCODE_MAX)
        {
            TRACE1("invalid opcode: %u",opcode);
            return;
        }

        // Check message size
        if (msglen < KMinMsgSize[opcode] || 
            msglen > KMaxMsgSize[opcode])
        {
            TRACE2("opcode %u, invalid message size %u",opcode,msglen);
            return;
        }

        // Try to find existing session
        TInt index = -1;
        CEcmtMidpDebugSession* session = FindSession(sid, index);
        switch (opcode) {
        case ECMT_MIDP_DEBUG_OPCODE_OPEN:
            if (session)
            {
                TRACE2("OPEN: destroying session %08X (%d)",session,sid);
                delete session;
                iSessions.Remove(index);
            }
            session = CEcmtMidpDebugSession::NewL(sid,this,iMessaging);
            CleanupStack::PushL(session);
            LEAVE_IF_ERROR(iSessions.Append(session));
            CleanupStack::Pop(session);
            TRACE2("OPEN: created new session %08X (%u)",session,sid);
            break;
                
        case ECMT_MIDP_DEBUG_OPCODE_CLOSE:
            if (session)
            {
                TRACE2("CLOSE: destroying session %08X (%u)",session,sid);
                delete session;
                iSessions.Remove(index);
            }
            else
            {
                TRACE1("CLOSE: no such session: %u",sid); 
            }
            break;

        case ECMT_MIDP_DEBUG_OPCODE_SEND:
            if (session)
            {
                TUint cid = (msg[ECMT_MIDP_DEBUG_SEND_CID_OFFSET] << 24) | 
                    (msg[ECMT_MIDP_DEBUG_SEND_CID_OFFSET+1] << 16) |
                    (msg[ECMT_MIDP_DEBUG_SEND_CID_OFFSET+2] << 8) |
                    (msg[ECMT_MIDP_DEBUG_SEND_CID_OFFSET+3]);
                TUint seq = (msg[ECMT_MIDP_DEBUG_SEND_SEQ_OFFSET] << 24) | 
                    (msg[ECMT_MIDP_DEBUG_SEND_SEQ_OFFSET+1] << 16) |
                    (msg[ECMT_MIDP_DEBUG_SEND_SEQ_OFFSET+2] << 8) |
                    (msg[ECMT_MIDP_DEBUG_SEND_SEQ_OFFSET+3]);
                session->Send(cid, seq,
                    msg.Right(msglen - ECMT_MIDP_DEBUG_SEND_DATA_OFFSET));
            }
            else
            {
                // Tell the other side that this session id is invalid
                TRACE1("SEND: invalid sid %u",sid);
                SendSessionCloseMessage(sid);
            }
            break;

        case ECMT_MIDP_DEBUG_OPCODE_CONNECT:
            if (session)
            {
                TUint cid = (msg[ECMT_MIDP_DEBUG_CONNECT_CID_OFFSET] << 24) | 
                    (msg[ECMT_MIDP_DEBUG_CONNECT_CID_OFFSET+1] << 16) |
                    (msg[ECMT_MIDP_DEBUG_CONNECT_CID_OFFSET+2] << 8) |
                    (msg[ECMT_MIDP_DEBUG_CONNECT_CID_OFFSET+3]);
                TUint port = (msg[ECMT_MIDP_DEBUG_CONNECT_PORT_OFFSET] << 8) | 
                    (msg[ECMT_MIDP_DEBUG_CONNECT_PORT_OFFSET+1]);
                session->ConnectL(cid, port);
            }
            else
            {
                // Tell the other side that this session id is invalid
                TRACE1("CONNECT: invalid sid %u",sid);
                SendSessionCloseMessage(sid);
            }
            break;


        case ECMT_MIDP_DEBUG_OPCODE_RESET:
            if (session)
            {
                TUint cid = (msg[ECMT_MIDP_DEBUG_RESET_CID_OFFSET] << 24) | 
                    (msg[ECMT_MIDP_DEBUG_RESET_CID_OFFSET+1] << 16) |
                    (msg[ECMT_MIDP_DEBUG_RESET_CID_OFFSET+2] << 8) |
                    (msg[ECMT_MIDP_DEBUG_RESET_CID_OFFSET+3]);
                session->Reset(cid);
            }
            else
            {
                // Tell the other side that this session id is invalid
                TRACE1("RESET: invalid sid %u",sid);
                SendSessionCloseMessage(sid);
            }
            break;

        }
    }
}
void CSyncHttpConnection::StateChange(THttpEngineState aState)
{
	iEngineStatus = aState;
	//CommonUtils::WriteLogL(_L("CSyncHttpConnection::StateChange  iEngineStatus = "), iEngineStatus);


	
	switch (aState)
	{
	case EHttpError:
	case EHttpGetHeaderTimeOut:
	case EHttpGetBodyTimeOut:
	case EHttpFinished:
		if (iWait->IsStarted())
		{
			iWait->AsyncStop();
		}
		break;
	case EGetHeader:
		break;
	case ERedirect:
	{
		HBufC8* head = iConnection->GetResponeHeader();
		TPtrC8 redirectUrl;
		if (head)
		{
			_LIT8(GOHREF, "Location:");
			TInt redirectUrlIndex = head->FindC(GOHREF);
			if (redirectUrlIndex >= 0)
			{
				redirectUrl.Set(head->Right(head->Length() - redirectUrlIndex - GOHREF().Length()));
				_LIT8(SPACE, " ");
				redirectUrlIndex = redirectUrl.FindC(SPACE);
				while (redirectUrlIndex == 0)
				{
					redirectUrl.Set(redirectUrl.Right(redirectUrl.Length() - redirectUrlIndex - SPACE().Length()));
					redirectUrlIndex = redirectUrl.FindC(SPACE);
				}
				redirectUrlIndex = redirectUrl.FindC(_L8("\r\n"));
				if (redirectUrlIndex >= 0)
				{
					redirectUrl.Set(redirectUrl.Left(redirectUrlIndex));
				}
			}
		}
		if (redirectUrl.Length() > 0)
		{
			TBuf<200> aUri;
			aUri.Copy(redirectUrl);
			//CommonUtils::WriteLogL(_L("CSyncHttpConnection::StateChange redirectUrl = "), aUri);
			iConnection->ResetVarible();
			iConnection->Stop();
			iConnection->GetRequestL(aUri, 0);
			iConnection->sendRequest();
		}
		else
		{
			//CommonUtils::WriteLogL(_L("CSyncHttpConnection::StateChange ERedirect error"), _L(""));
			iEngineStatus = EHttpError;
			if (iWait->IsStarted())
			{
				iWait->AsyncStop();
			}
		}

	}
		break;
	default:
		if (iWait->IsStarted())
		{
			iWait->AsyncStop();
		}
		break;
	}
}
TInt CFloggerTest028_Sync_Static_Multiple2::DoTestCheckWriteL()
	{
	RFile logFile;
	HBufC8* hBuffer;
	TInt listfilesize,returnCode;
	RFs fileSystem; //For file operation create a file system
	TInt numSuccessful = 0;

	User::LeaveIfError(fileSystem.Connect());
	
	//Open the file in the read mode
	User::LeaveIfError(logFile.Open(fileSystem,KFloggerOutputFile,EFileRead));

	CleanupClosePushL(logFile);

	User::LeaveIfError(logFile.Size(listfilesize)); //Size of the file
	
	hBuffer = HBufC8::New(listfilesize); //Allocate the buffer
	CleanupStack::PushL(hBuffer);

	TPtr8 ptrString = hBuffer->Des();  //To access the buffer

	// Read from position 0: start of file
	User::LeaveIfError(returnCode = logFile.Read(ptrString));
	
	
	// the test case writes 5 elements 100 times, but we only check these things:
	// 1. that the long test message with one parameter is written 100 times
	// 2. that the test message with one param is written 100 times
	// 3. that the end of test message has been written
	
	TPtrC8 ptrStringOffsetForSearching;
	returnCode = ptrString.Find(KTestMessageOneParamExpected);

	if (returnCode > 0)
		{
		numSuccessful++;
		}
		
	TInt newLength;   // allow length to be watched during debugging
	TInt loop;
	
	ptrStringOffsetForSearching.Set(ptrString.Right((ptrString.Length()-returnCode)-KTestMessageOneParamExpected().Length()));
	for (loop=0; loop < KMultipleWriteStressTimes; loop++)
		{
		returnCode = ptrStringOffsetForSearching.Find(KTestMessageOneParamExpected); //find the next occurance
		if (returnCode > 0)
			{
			numSuccessful++;
			}
			
		newLength = ptrStringOffsetForSearching.Length() - returnCode - KTestMessageOneParamExpected().Length();
	 	if (newLength < 0)
	 		{
	 		User::Leave(KErrUnknown);
	 		}

		ptrStringOffsetForSearching.Set(ptrStringOffsetForSearching.Right(newLength));
		
		}


	returnCode = ptrString.Find(KTestTooLongMessageOneParamExpected);

	if (returnCode > 0)
		{
		numSuccessful++;
		}
		
	newLength = ptrString.Length()-returnCode-KTestTooLongMessageOneParamExpected().Length();
	ptrStringOffsetForSearching.Set(ptrString.Right(newLength));
	for (loop=0; loop < KMultipleWriteStressTimes; loop++)
		{
		returnCode = ptrStringOffsetForSearching.Find(KTestTooLongMessageOneParamExpected); //find the next occurance
		if (returnCode > 0)
			{
			numSuccessful++;
			}
			
		if (loop < (KMultipleWriteStressTimes - 1))
			{
			newLength = ptrStringOffsetForSearching.Length() - returnCode - KTestTooLongMessageOneParamExpected().Length();
	 		if (newLength < 0)
	 			{
	 			User::Leave(KErrUnknown);
	 			}
			ptrStringOffsetForSearching.Set(ptrStringOffsetForSearching.Right(newLength));
			}
		
		}

	returnCode = ptrString.Find(KTestEndMessage8); 
	if (returnCode > 0)
		{
		numSuccessful++;
		}

	
	CleanupStack::PopAndDestroy(hBuffer);
	CleanupStack::PopAndDestroy();	//logFile
	if ( numSuccessful == 201 )
		return KErrNone;
	else
		return KErrUnknown;
	}
TInt CFloggerTest028_Sync_ConMultiple2::DoTestCheckWriteL()
	{
	RFile logFile;
	HBufC8* hBuffer;
	TInt listfilesize,returnCode;
	RFs fileSystem; //For file operation create a file system
	TInt numSuccessful = 0;
	TInt loop = 0;

	User::LeaveIfError(fileSystem.Connect());
	
	//Open the file in the read mode
	User::LeaveIfError(logFile.Open(fileSystem,KFloggerOutputFile,EFileRead));

	CleanupClosePushL(logFile);

	User::LeaveIfError(logFile.Size(listfilesize)); //Size of the file
	
	hBuffer = HBufC8::New(listfilesize); //Allocate the buffer. This is about 176K in size
	CleanupStack::PushL(hBuffer);

	TPtr8 ptrString = hBuffer->Des();  //To access the buffer

	// Read from position 0: start of file
	User::LeaveIfError(returnCode = logFile.Read(ptrString));
	
	// the test case writes 6 elements 100 times, but we only check these things:
	// 1. that the test message with one parameter is written 100 times
	// 2. that the long message is written 100 times
	// 3. that the end of test message has been written
	// 4. that the file is suitably big enough to be expected to contain the
	//    1K data segment 100 times in it.
	
	TPtrC8 ptrStringOffsetForSearching;
	returnCode = ptrString.Find(KTestMessageOneParamExpected);

	if (returnCode > 0)
		{
		numSuccessful++;
		}
		
	TInt newLength;
	ptrStringOffsetForSearching.Set(ptrString.Right((ptrString.Length()-returnCode)-KTestMessageOneParamExpected().Length()));
	for (loop=0; loop < KMultipleWriteStressTimes; loop++)
		{
		returnCode = ptrStringOffsetForSearching.Find(KTestMessageOneParamExpected); //find the next occurance
		if (returnCode > 0)
			{
			numSuccessful++;
			}
			
		newLength = ptrStringOffsetForSearching.Length() - returnCode - KTestMessageOneParamExpected().Length();
		if (newLength < 0)
			{
			User::Leave(KErrUnknown);
			}
		ptrStringOffsetForSearching.Set(ptrStringOffsetForSearching.Right(newLength));
		
		}

	returnCode = ptrString.Find(KTestTooLongExpectedMessage); 
	
	if (returnCode > 0)
		{
		numSuccessful++;
		}
		
	ptrStringOffsetForSearching.Set(ptrString.Right((ptrString.Length()-returnCode)-KTestTooLongExpectedMessage().Length()));

	for (loop=0; loop < KMultipleWriteStressTimes; loop++)
		{

		returnCode = ptrStringOffsetForSearching.Find(KTestTooLongExpectedMessage); //find the next occurance
		if (returnCode > 0)
			{
			numSuccessful++;
			}
		newLength = ptrStringOffsetForSearching.Length() - returnCode - KTestTooLongExpectedMessage().Length();
		if (newLength <0)
			{
			User::Leave(KErrUnknown);
			}
		ptrStringOffsetForSearching.Set(ptrStringOffsetForSearching.Right(newLength));
			
		}


	returnCode = ptrString.Find(KTestEndMessage8); 
	if (returnCode > 0)
		{
		numSuccessful++;
		}
		

	// we don't check that all the binary data is there - just that the file is nice and long		
	if ( listfilesize > (K1KilobyteOfDataSize * KMultipleWriteStressTimes))
		{
		numSuccessful++;
		}
	


	CleanupStack::PopAndDestroy(hBuffer);
	CleanupStack::PopAndDestroy();	//logFile
	if ( numSuccessful == 202 )
		return KErrNone;
	else
		return KErrUnknown;
	}
// ---------------------------------------------------------------------------
// CAtSmsReceive::CMTResponseSecondLineL
// other items were commented in a header
// ---------------------------------------------------------------------------
void  CAtSmsReceive::CMTResponseSecondLineL() 
	{
	LOGTEXT(_L8("CAtSmsReceive::CMTResponseSecondLineL Enter funciton"));
	iError = KErrNone;
	iAttr.iFlags=0;
	TPtrC8 secondLineBuf;
	secondLineBuf.Set(CurrentLine());
	
#ifdef _DEBUG
	TInt totalLen = secondLineBuf.Length();
	if(totalLen <= KLogMaxCharNumPerLine)
		{
		LOGTEXT2(_L8("CAtSmsReceiveMessage::CMTResponseSecondLineL\tSecondLine=%S"),&secondLineBuf);
		}
	else
		{
		TInt lines = (totalLen/KLogMaxCharNumPerLine);
		TInt remainingStrNum = (totalLen%KLogMaxCharNumPerLine);
		for(TInt i = 0; i < lines; i++)
			{
			TPtrC8 line(secondLineBuf.Mid(i*KLogMaxCharNumPerLine,KLogMaxCharNumPerLine));
			LOGTEXT2(_L8("CAtSmsReceiveMessage::CMTResponseSecondLineL \tSecondLine line=%S"),&line);
			}
		
		TPtrC8 remaining(secondLineBuf.Right(remainingStrNum));
		
		LOGTEXT2(_L8("CAtSmsReceiveMessage::CMTResponseSecondLineL \tSecondLine line=%S"),&remaining);
		}
#endif  
	// Buffer size calculated as follows;
	//   (max pdu size + max prefixed SCA size) * number of ASCII chars used to code an octet
	TBuf8<(RMobileSmsMessaging::KGsmTpduSize+12)*2> localPdu;	
	localPdu.Copy(secondLineBuf);
	//  The CMT frame sometimes contains odd number of nibbles which
	// causes panic in ConvertAsciiToBinary() method. This type of
	// frames will simply be discarded.
	if(localPdu.Length() < (iPduLen*2))
		{
		iError = KErrUnderflow;
		User::Leave(KErrUnderflow);
		}
		
	//
	// Check if we have a prefixed SCA on our pdu.
	// If we do then remove it.
	
	if(localPdu.Length() > (iPduLen*2))
		{
		TInt ret = SmsAtUtil::ReadAndRemoveAddressFromAscii(localPdu,iAttr.iGsmServiceCentre);
		if(ret !=KErrNone)
			{
			LOGTEXT(_L8("CAtSmsReceiveMessage::CMTResponseSecondLineL Failed to read and remove SCA from PDU"));
			iError = ret;
			return;
			}
		else
			{
			iMsgReceive.iServiceCentre = iAttr.iGsmServiceCentre.iTelNumber;    //for iServiceCentre
			iMsgReceive.iMobileScNPI = iAttr.iGsmServiceCentre.iNumberPlan;
			iMsgReceive.iMobileScTON = iAttr.iGsmServiceCentre.iTypeOfNumber;
			iAttr.iFlags|= RMobileSmsMessaging::KGsmServiceCentre;
			}
		}
	//
	// Convert received pdu from ASCII into binary
	TInt ret = SmsAtUtil::ConvertAsciiToBinary(localPdu,iPdu);
	if (ret!=KErrNone)
		{
		LOGTEXT(_L8("CAtSmsReceiveMessage::CMTResponseSecondLineL Failed to code PDU into binary"));
		iError = ret;
		return;
		}
	else
		{
		iAttr.iDataFormat=RMobileSmsMessaging::EFormatGsmTpdu;
		iAttr.iFlags|=RMobileSmsMessaging::KSmsDataFormat;
		iAttr.iStatus = RMobileSmsMessaging::EMtMessageUnstoredClientAck;
		iAttr.iFlags|=RMobileSmsMessaging::KIncomingStatus;
		}

	LOGTEXT2(_L8("Received PDU String is %S"),&iPdu);
	iMsgReceive.iSmsMsg = iPdu;
	}
// -----------------------------------------------------------------------------
// CSTSCredentialManager::AddCredentialL
// Adds a certificate or certificate URI to certificate store
// -----------------------------------------------------------------------------
//
TBool CSTSCredentialManager::AddCredentialL(
    TInt/*const TDesC&*/ aCertDisplayName,
    TInt/*const TDesC&*/ aPkiPath)
{

    if (iState != EReady)
    {
        User::Leave(KErrNotReady);
    }

    iWritableCertStoreIndex = CheckWriteCertStoreSEIDL(NULL, NULL);

    const TDesC8* path = reinterpret_cast< const TDesC8* >(aPkiPath);

    TASN1DecGeneric genericDecoder(*path);

    genericDecoder.InitL();

    TPtrC8 certificates = genericDecoder.GetContentDER();

    TInt certificatesLength = certificates.Length();
    TInt pos = 0;

    iSubject.Set(certificates.Right(certificatesLength));

    TPtrC8 issuer(iSubject);

    // go through the certificate chain, leaving the last certificate as subject
    // and second last as issuer
    while (pos < certificatesLength)
    {
        issuer.Set(iSubject);
        TASN1DecGeneric
        certDecoder(certificates.Right(certificatesLength - pos));
        certDecoder.InitL();
        TInt certLength = certDecoder.LengthDER();

        TPtrC8 singleCert(certificates.Mid(pos, certLength));
        iSubject.Set(singleCert);
        pos+=certLength;
    }

    CX509Certificate* cert =
        CX509Certificate::NewLC(iSubject);

    CX509Certificate* issuerCert =
        CX509Certificate::NewLC(issuer);

    iSubjectKeyId = cert->KeyIdentifierL();
    iIssuerKeyId = issuerCert->KeyIdentifierL();

    iCertDisplayName = reinterpret_cast<TDesC*>(aCertDisplayName);

    // now we have to check that this certificate does not exist in the
    // database yet
    CCertAttributeFilter* filter = CCertAttributeFilter::NewLC();
    filter->SetFormat(EX509Certificate);
    filter->SetSubjectKeyId(iSubjectKeyId);
    filter->SetIssuerKeyId(iIssuerKeyId);

    RMPointerArray< CCTCertInfo >* certInfoArray =
        new(ELeave) RMPointerArray< CCTCertInfo >();
    if (iCertInfoArray)
    {
        iCertInfoArray->Close();
        delete iCertInfoArray;
    }
    iCertInfoArray = certInfoArray;

    iState = EAddListing;
    iStore->WritableCertStore(iWritableCertStoreIndex)
    .List(*iCertInfoArray, *filter,
          iStatus);
    WaitForCompletionL();

    CleanupStack::PopAndDestroy(3); // filter, cert, issuerCert

    iCertInfoArray->Close();
    delete iCertInfoArray;
    iCertInfoArray = NULL;


    return ETrue;
}
// -----------------------------------------------------------------------------
//  CUpnpHttpSession::ParseRangeHeader
//  Parse range values
// -----------------------------------------------------------------------------
//    
TBool CUpnpRangeHeaderParser::ParseRangeHeader( TDesC8& aRangeHeader, TInt& aStartPos,
                                                TInt& aEndPos )
    {
    // Check header's syntax: "bytes=x-y" where y i optional
    TInt pos( KErrNotFound );

    // 1 string has to contain "="
    pos = aRangeHeader.FindC( UpnpString::KEqual() );
    if( pos == KErrNotFound ) 
        return EFalse;

    // 2 "bytes" has to be at the beginnig
    pos = aRangeHeader.FindC( UpnpHTTP::KBytes() );
    if( pos == KErrNotFound || pos != 0 ) 
        return EFalse;

    // 3 Sets position to after bytes
    pos = UpnpHTTP::KBytes().Length();

    // 4 If there any space or tab after "bytes" - move pos after it
    CUpnpRangeHeaderParser::MovePosition( aRangeHeader, pos );

    // 5 "=" - has to be at this position (after "bytes" + spaces or tabs)
    if( aRangeHeader[ pos ] != UpnpString::KEqual()[0] )
        return EFalse;

    // 6 Sets position to after "="
    pos++;

    // 7 If there any space or tab after "=" - move pos after it
    CUpnpRangeHeaderParser::MovePosition( aRangeHeader, pos );
    
    // 8 extract x-y. -1 stands for '=' length
    TPtrC8 byteRange = aRangeHeader.Right( aRangeHeader.Length() - pos );

    // 9 There can't be any comas because multi-range is not allowed
    if( byteRange.Find( UpnpString::KComa() ) != KErrNotFound ) 
        return EFalse;

    // 10 "-" delimiter must occure and it cant't be first char, because notation as follows: "-y"  is not allowed
    pos = byteRange.Find( UpnpString::KMinus() );
    if( pos == KErrNotFound ) 
        return EFalse;
    
    // 11 Checks if it is a final bytes request
    // e.g. Range: bytes= -20
    if( pos == 0 )
        {
        // If there any space or tab after "-" - move pos after it
        CUpnpRangeHeaderParser::MovePosition( byteRange.Right( byteRange.Length()-1 ), pos );
        // if pos equal 0 should be 1 to avoid "-" in getting number from string operation
        pos = pos == 0 ? 1 : pos;
        TLex8 endMinus( byteRange.Right( byteRange.Length() - pos  ) );
        endMinus.SkipSpace();
        TInt error = endMinus.Val( aEndPos );
        if ( !CUpnpRangeHeaderParser::HandleConversionException( endMinus, aEndPos, error ) )
            {
            return EFalse;
            }
            
        // We have to check if something else than space or tab leaves after conversion - unless for example 11a will be correct but it is not
        if ( CUpnpRangeHeaderParser::HasImproperChars( endMinus ) )
            return EFalse;
         
        aStartPos = KErrNotFound;
        return ETrue;
        }

    // 12 All looks fine, so now parse it and get x and y
    TLex8 start( byteRange.Left( pos ) );
    start.SkipSpace();

    // 13 If conversion fails - return error
    TInt error = start.Val( aStartPos );
    if ( !CUpnpRangeHeaderParser::HandleConversionException( start, aStartPos, error ) )
        {
        return EFalse;
        }
    // 14 We have to check if something else than space or tab leaves after conversion - unless for example 11a will be correct but it is not
    if ( CUpnpRangeHeaderParser::HasImproperChars( start ) )
            return EFalse;

    // y is optional
    if( ( byteRange.Length() - pos - 1 ) > 0 )
        {
        TLex8 end( byteRange.Right( byteRange.Length() - pos - 1 ) );
        end.SkipSpace();
        
        error = end.Val( aEndPos );
        if ( !CUpnpRangeHeaderParser::HandleConversionException( end, aEndPos, error ) )
            {
            return EFalse;
            }
            
        // We have to check if something else than space or tab leaves after conversion - unless for example 11a will be correct but it is not
        if ( CUpnpRangeHeaderParser::HasImproperChars( end ) )
            return EFalse;
        
        } 
    else
        {
        aEndPos = KErrNotFound; 
        } 

    return ETrue;
    }