void CUPnPHeaderReader::DecodeGenericNumberL(RHeaderField& aHeader) const
	{
	TPtrC8 buffer;
	aHeader.RawDataL(buffer);
	TInt number = KErrNotFound;
	
	TInt decimalPos = buffer.Locate('.');
	if(decimalPos == 0)
		{
		// first character is decimal. So, set the value as zero.
		SetNewIntegerPartL(aHeader, 0, 0);
		}
	else
	   	{
		// Search for '\n' separator. In the case when a duplicate header has been received,
		// only use the fist instance of the valid data.
		TInt newLinePos = buffer.Locate('\n');
		if (newLinePos != KErrNotFound)
			{
			buffer.Set(buffer.Left(newLinePos));
			}
		
		TInt value = KErrNotFound;
		TInt ret = InetProtTextUtils::ConvertDescriptorToInt(buffer, value);
		if ( ret > KErrNone ) 
			{
			// Extract an integer.  Do not permit terminators other than WS or EOL.
			InetProtTextUtils::ExtractIntegerValueL(buffer, number, EFalse);	
			}
		SetNewIntegerPartL(aHeader, 0, number); // part 0, i.e. the first (and only) part
	   	}
	}
void CUPnPHeaderReader::DecodeTimeoutHeaderL(RHeaderField& aHeader) const
	{
	TPtrC8 buffer;
	aHeader.RawDataL(buffer);
	
	// Search for '\n' separator. In the case when a duplicate header has been received,
	// only use the fist instance of the valid data.
	TInt newLinePos = buffer.Locate('\n');
	if (newLinePos != KErrNotFound)
		{
		buffer.Set(buffer.Left(newLinePos));
		}
		
	RStringF infinite = iStringPool.StringF(UPnP::EInfinite, TUPnPTable::Table());
	if(buffer.Compare(infinite.DesC()) == 0)
		{
		SetNewIntegerPartL(aHeader, 0, -(KMaxTInt));	
		}
	
	else
		{
		TPtrC8 token;
		InetProtTextUtils::ExtractNextTokenFromList(buffer, token, KSemiSpaceSep);
		TInt consumed = token.Locate('-');
		token.Set(token.Mid(consumed+1));
		TInt intVal;
		InetProtTextUtils::ConvertDescriptorToInt(token, intVal);
		SetNewIntegerPartL(aHeader, 0, intVal); // part 0, i.e. the first (and only) part
		}
	}
Beispiel #3
0
void CApaDRMRecognizer::DoRecognizeL( const TDesC& aName, const TDesC8& aBuffer )
{
    if ( aBuffer.Size() < 3)
        {
        return;
        }

#ifdef RECOGNIZE_KEY_CHAIN
    // Recognize device key chain
    if ( aName.Length() > 3 && aName.Right(4).CompareF(_L(".dkc")) == 0)
        {
        iConfidence = ECertain;
        iDataType = TDataType( _L8("application/x-device-key-chain") );
        return;
        }
#endif

#ifdef DRM_OMA2_ENABLED
    // Recognize ROAP Trigger
    if ( RecognizeRoapTrigger( aBuffer ) )
        {
        return;
        }

    // Recognize DCFv2
    if ( RecognizeODF( aBuffer ) )
        {
        return;
        }
#endif
    // Recognize DCFv1
    TUint8 version = aBuffer[0];
    TUint8 contentTypeLen = aBuffer[1];
    TUint8 contentURILen = aBuffer[2];

    if ( contentTypeLen < KMinContentTypeLen || contentURILen == 0 )
    {
        return;
    }
    if ( version != KDCFVersionSupported )
    {
        return;
    }

    // Too little data received
    if ( aBuffer.Size() < ( contentTypeLen + KDCFHeaderLength ) )
    {
        return;
    }

    TPtrC8 mimeType = aBuffer.Mid( KDCFHeaderLength, contentTypeLen );
    if ( mimeType.Locate( '/' ) != KErrNotFound )
    {
        iConfidence = ECertain;
        iDataType=TDataType( mimeType );
    }


    return;
}
void CUPnPHeaderReader::DecodeCallbackL(RHeaderField& aHeader) const
	{
	//Callback: <token1><token2><token3>...<tokenN>
	
	TPtrC8 rawData;
	aHeader.RawDataL(rawData);
	TInt remaining = rawData.Length();
	TPtrC8 token;
	TInt tokensFound = 0;
	TInt consumed;
	while (remaining)
		{
		// Locate and remove the '<' character from the token
		consumed = rawData.Locate(KOpenAngleBracket);
		if(consumed == KErrNotFound)
			{
			// No more tokens.
			break;	
			}
		// '<' character has now been removed.
		rawData.Set(rawData.Mid(consumed+1));
		// Now extract the value before '>' character. 
		// This will be the actual value of the token.
		remaining -= InetProtTextUtils::ExtractNextTokenFromList(rawData, token, KCloseAngleBracket);

		// No parameters. Just store the field value
		InetProtTextUtils::RemoveWhiteSpace(token, InetProtTextUtils::ERemoveBoth);
		SetNewFStringPartL(aHeader, tokensFound, token);
		++tokensFound;
		}
	}
/**
	Checks that a Query/Header is in a valid form as specified in RFC 3261.

	@return		A boolean value of ETrue if uri contains valid Query/Header,
				EFalse if it does not.
*/
TBool TValidatorSip::IsValidQuery() const
	{
	const TDesC8& headers = iUri.Extract(EUriQuery);
	if (IsEmpty(headers))
		{
		return EFalse;
		}

	TDelimitedQueryParser8 parser;
	parser.Parse(headers);

	TPtrC8 name;
	TPtrC8 value;
	TPtrC8 segment;
	while( parser.GetNext(segment) == KErrNone )
		{
		// must be in the form name=value even if the value part is empty
		if (segment.Locate(KEqualsSeparator) == KErrNotFound)
			{
			return EFalse;
			}
		
		GetNameValuePair(segment, name, value);
		if (IsDuplicated(name, parser) || !IsValidHeaderSegment(name, value))
			{
			return EFalse;
		}
		}
	return ETrue;
	}
/**
	Parses the descriptor aUri into uri components.
	
	@param			aUri A reference to a descriptor pointer of an Uri.
	@param			aScheme A reference to a descriptor pointer for retieved 
					scheme component.
 */
void TUriParser8::RetrieveScheme(const TPtrC8& aUri, TPtrC8& aScheme)
	{
	TInt schemePos = aUri.Locate(KSchemeDelimiter);
	if(schemePos != KErrNotFound)
		{
		// Got a scheme - store information
		aScheme.Set(aUri.Left(schemePos));
		}
	}
TInt CExampleCookieManager::CountSeparators(const TDesC8& aDes)
	{
	const TChar pathSeparator('/');
	TInt numSeps = 0;

	// Get all the descriptor to start with
	TPtrC8 desPtr = aDes.Mid(0);
	TInt sepPos = desPtr.Locate(pathSeparator);
	while(sepPos != KErrNotFound)
		{
		++numSeps;

		// Get the rest of the descriptor without the separator that we have found
		desPtr.Set(desPtr.Mid(sepPos + 1));
		sepPos = desPtr.Locate(pathSeparator);
		}

	return numSeps;
	}
Beispiel #8
0
void RElementIdArray::SetListL( const TDesC8& aChilds)
{
	TInt index = 0;
	TPtrC8 ptr = aChilds;	
	
	while ( 0 <= ( index = ptr.Locate( KMessageDelimiterChar)))
	{
		AppendL( ptr.Left( index).AllocL());
		ptr.Set( ptr.Mid(index + 1));
	}	
}
Beispiel #9
0
// -----------------------------------------------------------------------------
// SdpUtil::IsTokenTextPair
// Checks if aValue is valid pair ("valid token":"valid byte-string")
// -----------------------------------------------------------------------------
//
TBool SdpUtil::IsTokenTextPair(
    const TDesC8& aValue, 
    TInt aStart,
    TInt aEnd )
	{
	// token ":" text
	TBool result = EFalse;
	if ( aStart >= 0 && aEnd <= aValue.Length() && aStart < aEnd )
		{
		TPtrC8 subVal = aValue.Mid( aStart, aEnd - aStart );
		TInt colonPos = subVal.Locate( KColonChar );
		result = colonPos != KErrNone &&
                 IsToken( subVal, 0, colonPos ) &&
                 IsByteString( subVal, colonPos + 1, subVal.Length() );
		}
	return result;
	}
void CUPnPHeaderReader::DecodeGenericUpnpHeadersL(RHeaderField& aHeader) const
	{
	TPtrC8 buffer;
	aHeader.RawDataL(buffer);
	
	// Search for '\n' separator. In the case when a duplicate header has been received,
	// only use the fist instance of the valid data.
	TInt newLinePos = buffer.Locate('\n');
	if (newLinePos != KErrNotFound)
		{
		buffer.Set(buffer.Left(newLinePos));
		}

	TPtrC8 token;
	InetProtTextUtils::ExtractNextTokenFromList(buffer, token, KSemiSpaceSep);
	SetNewFStringPartL(aHeader, 0, token); // part 0, i.e. the first (and only) part
	}
Beispiel #11
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 );
			}
		}
    }
Beispiel #12
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 );
}
TBool CExampleCookieManager::ValidateCookieL(CCookie& aCookie, const TUriC8& aUri)
	{
	THTTPHdrVal attributeVal;

	if(aCookie.Attribute(CCookie::EPath, attributeVal) == KErrNone)
		{
		// if the path attribute exists check it is a prefix of the path
		// of the uri that issued it (if not reject)
		RStringF cookiePath = attributeVal.StrF();
		const TDesC8& uriPath = aUri.Extract(EUriPath);
		if(uriPath.FindF(RemoveQuotes(cookiePath.DesC())) != 0)
			return EFalse;
		}
	else
		{
		// if the path attribute doesn't exist add it
		THTTPHdrVal val(iStringPool.OpenFStringL(aUri.Extract(EUriPath)));
		aCookie.SetAttributeL(CCookie::EPath, val);
		}

	if(aCookie.Attribute(CCookie::EDomain, attributeVal) == KErrNone)
		{
		const TChar dot('.');
		const TDesC8& cookieDomain = attributeVal.StrF().DesC();
		const TDesC8& uriDomain = aUri.Extract(EUriHost);

		// if the domain does not exactly match the uri and does not begin
		// with a dot then add one
		if((cookieDomain.Compare(uriDomain) != 0) &&
		   (cookieDomain.Locate(dot) != 0))
			{
			_LIT8(KAddDotString, ".%S");
			HBufC8* newDomain = HBufC8::NewLC(cookieDomain.Length() + 1);
			newDomain->Des().AppendFormat(KAddDotString(), &cookieDomain);

			RStringF domain = iStringPool.OpenFStringL(*newDomain);
			CleanupStack::PopAndDestroy(newDomain);

			THTTPHdrVal val(domain);
			aCookie.SetAttributeL(CCookie::EDomain, val);
			domain.Close();
			}

		// if the domain does not contain an embedded dot then reject it
		// ie reject .com or .com.
		// Start by removing one character from each end. ie start at pos 1 and take a length
		// which is 2 shorter than the original descriptor
		TPtrC8 domainMiddle = cookieDomain.Mid(1, cookieDomain.Length() - 2);
		if(domainMiddle.Locate(dot) == KErrNotFound)
			return EFalse;

		// Reject the cookie if the domain differs by two or more levels from the uri
		// ie if uri=www.x.y.com then accept a cookie with .x.y.com but reject .y.com
		TInt pos = uriDomain.FindF(cookieDomain);
		if(pos > 2)
			{
			const TDesC8& domainDiff = uriDomain.Left(pos);

			// Remove one character from each end. ie start at pos 1 and take a length
			// which is 2 shorter than the original descriptor
			const TDesC8& diffMiddle = domainDiff.Mid(1, domainDiff.Length() - 2);
			if(diffMiddle.Locate(dot) != KErrNotFound)
				return EFalse;
			}
		}
	else
		{
		// if the domain attribute is not found add it
		THTTPHdrVal val(iStringPool.OpenFStringL(aUri.Extract(EUriHost)));
		aCookie.SetAttributeL(CCookie::EDomain, val);
		val.StrF().Close();
		}

	if(!CheckPortMatch(aCookie, aUri))
		return EFalse;

	return ETrue;
	}
Beispiel #14
0
SYSCALL(MAHandle, maConnect(const char* url)) {
	TPtrC8 urlP(CBP url, SYSCALL_THIS->ValidatedStrLen(url));
	LOGST("Connect %i %s", gConnNextHandle, url);
	if(gConnections.size() >= CONN_MAX)
		return CONNERR_MAX;

	_LIT8(KLocalhost, "localhost");
	CConnection* conn = NULL;
	TPtrC8 match;
	SocketType socketType = TCP;	// initialized to placate stupid compiler
	ConnectionType type;

	// determine type of connection
	if(SSTREQ(urlP, KSocket)) {
		match.Set(KSocket);
		type = eSocket;
		socketType = TCP;
	} else if(SSTREQ(urlP, KDatagram)) {
		match.Set(KDatagram);
		type = eSocket;
		socketType = UDP;
	} else if(SSTREQ(urlP, KSsl)) {
		match.Set(KSsl);
		type = eSocket;
		socketType = SSL;
	} else if(SSTREQ(urlP, KHttp)) {
		match.Set(KHttp);
		type = eHttp;
		socketType = TCP;
	} else if(SSTREQ(urlP, KHttps)) {
		match.Set(KHttps);
		type = eHttp;
		socketType = SSL;
	} else if(SSTREQ(urlP, KBtspp)) {
		match.Set(KBtspp);
		type = eBtspp;
	} else {	//error
		return CONNERR_URL;
	}
	TPtrC8 parturl = urlP.Mid(match.Length());

	if(type == eSocket) {
		TPtrC8 hostnamePtrC8;
		int port;
		if(!splitPurl(parturl, hostnamePtrC8, port, (1<<16))) {
			return CONNERR_URL;
		}
		Smartie<CSocket> sockp(createSocket(socketType));

		_LIT8(K127, "127.");
		TInetAddr addr;
		bool localhost = false;
		if(hostnamePtrC8 == KLocalhost) {
			localhost = true;
			addr.SetAddress(INET_ADDR(127,0,0,1));
		} else if(hostnamePtrC8.Length() > K127().Length()) {
			if(hostnamePtrC8.Left(K127().Length()) == K127) {
				localhost = true;
				Smartie<HBufC16> hostname(CreateHBufC16FromDesC8LC(hostnamePtrC8));
				addr.Input(*hostname());
			}
		}
		sockp->state |= CONNOP_CONNECT;
		if(localhost) {
			StartConnOpL(CO_AddrConnect::NewL(false, *this, gConnNextHandle, *sockp(),
				addr, port, *sockp()));
		} else {
			Smartie<HBufC16> hostname(CreateHBufC16FromDesC8LC(hostnamePtrC8));
			CleanupStack::Pop(hostname());
			StartConnOpL(CO_NameConnect::NewL(gNetworkingState != EStarted,
				*this, gConnNextHandle, *sockp(), hostname, port, *sockp()));
		}
		conn = sockp.extract();
	} else if(type == eHttp) {
		CHttpConnection* http;
		TLTZ_PASS(httpCreateConnectionLC(parturl, http, HTTP_GET, socketType));
		http->state |= CONNOP_CONNECT;
		StartConnOpL(CO_HttpFinish::NewL(gNetworkingState != EStarted,
			*this, gConnNextHandle, *http, *http, true));
		http->mState = CHttpConnection::WRITING;
		conn = http;
		CleanupStack::Pop(conn);
	} else if(type == eBtspp) {
		if(gBtState != eAvailable) {
			return CONNERR_UNAVAILABLE;
		}
		TPtrC8 hostnamePtrC8;
		int port_m1_index = parturl.Locate(':');
		if(port_m1_index == KErrNotFound) {
			return false;
		}
		hostnamePtrC8.Set(parturl.Left(port_m1_index));
		if(hostnamePtrC8 == KLocalhost) {	// server
			// extract and parse uuid
			static const int KUuidLength = 32;
			int uuidStartIndex = port_m1_index + 1;
			int paramStartIndex = uuidStartIndex + KUuidLength;
			if(parturl.Length() < paramStartIndex) {
				return CONNERR_URL;
			}
			TPtrC8 uuidPtrC8(parturl.Mid(uuidStartIndex, KUuidLength));
			TUint32 us[4];
			for(int i=0; i<4; i++) {
				TPtrC8 p(uuidPtrC8.Mid(i*8, 8));
				for(int j=0; j<8; j++) {
					if(!TChar(p[j]).IsHexDigit())
						return CONNERR_URL;
				}
				LHEL(TLex8(p).Val(us[i], EHex));
			}
			TUUID uuid(us[0], us[1], us[2], us[3]);
			//TUUID uuid(KSerialPortUUID);	//temp hack

			// create listener socket
			Smartie<CBtServerSocket> sockp(new (ELeave) CBtServerSocket(gBtSdpDB));

			// extract name, if it's there. initialize the socket.
			TPtrC8 paramPtrC8(parturl.Mid(paramStartIndex));
			_LIT8(KNameParam, ";name=");
			if(SSTREQ(paramPtrC8, KNameParam)) {
				TPtrC8 namePtrC8(paramPtrC8.Mid(KNameParam().Length()));
				sockp->init(gSocketServ, uuid, true, namePtrC8);
			} else if(paramPtrC8.Length() == 0) {
				sockp->init(gSocketServ, uuid, false);
			} else {
				return CONNERR_URL;
			}
			//skip the async/connect step
			gConnections.insert(gConnNextHandle, sockp.extract());
			return gConnNextHandle++;
		} else {	// client
			// extract port number
			int port;
			if(!splitPurl(parturl, hostnamePtrC8, port, 31)) {
				return CONNERR_URL;
			}
			TRfcommSockAddr rfcsa;

			// parse address
			TBTDevAddr btaddr;
			for(int i=0; i<BTADDR_LEN; i++) {
				TLex8 btaLex(parturl.Mid(i*2, 2));
				int result = btaLex.Val(btaddr[i], EHex);
				if(result != KErrNone)
					return CONNERR_URL;
			}
			rfcsa.SetBTAddr(btaddr);

			// create socket
			Smartie<CSocket> sockp(new (ELeave) CSocket(gSocketServ, CSocket::ERfcomm));
			sockp->state |= CONNOP_CONNECT;
			StartConnOpL(CO_AddrConnect::NewL(false, *this, gConnNextHandle, *sockp(),
				rfcsa, port, *sockp()));
			conn = sockp.extract();
		}
	}
	CleanupStack::PushL(conn);
	gConnections.insert(gConnNextHandle, conn);
	CleanupStack::Pop(conn);
	return gConnNextHandle++;
}
// Convert the WWW-Authenticate header field from OTA to generic form.
void CHttpClientHeaderReader::DecodeWWWAuthenticateL( RHeaderField& aHeader ) const
	{
	// RFC2616, section 14.47 WWW-Authenticate
	// RFC2617, 'HTTP Authentication: Basic and Digest Access Authentication'
	//
	// WWW-Authenticate  = "WWW-Authenticate" ":" 1#challenge
	// challenge   = auth-scheme 1*SP 1#auth-param
	// auth-scheme    = token
	// auth-param     = token "=" ( token | quoted-string )

	// There may be one or more challenge, in a comma-separated list.
	TPtrC8 buffer;
	aHeader.RawDataL( buffer );

	TInt totalBytesConsumed = 0;
	TInt numChallenges = 0;
	CHeaderFieldPart* part = NULL;
	TBool done = EFalse;
	while ( !done )
		{
		_LIT8( commaSpaceNewline, ", \n" );
		TPtrC8 token;
		TInt bytesConsumed = InetProtTextUtils::ExtractNextTokenFromList( buffer, token, commaSpaceNewline );

		done = (bytesConsumed == 0);
		if ( done && ( numChallenges == 0 ) ) // if we didn't find _anything_ at all...
			{
			User::Leave( KErrHttpDecodeWWWAuthenticate );
			}

		if ( !done && ( token.Length() > 0 ) )
			{
			totalBytesConsumed += bytesConsumed;

			TBool equalsPresent = ( token.Locate( '=' ) != KErrNotFound );

			if ( ( totalBytesConsumed == bytesConsumed ) && equalsPresent )
				{
				// The first token has an equals sign in it. That
				// can't be as it has to be an authentication scheme
				User::Leave( KErrHttpDecodeWWWAuthenticate );
				}

			if ( !equalsPresent )
				{
				// Got a new part. Add it.
				++numChallenges;
				part = SetNewFStringPartL( aHeader, numChallenges - 1, token );
				
			if( token.Compare( iStrPool.StringF(HTTP::ENTLM, iStringTable).DesC() ) == 0 )
				{
 					TInt consumed = InetProtTextUtils::ExtractNextTokenFromList( buffer, token, commaSpaceNewline );
 					if( consumed > 0 )
 						{
 						++numChallenges;
 						part = SetNewFStringPartL( aHeader, numChallenges -1, token );
						}
					}
				}
			else
				{
				// Got a param & parameter value.
				TPtrC8 paramName;
				TInt paramBytesConsumed = InetProtTextUtils::ExtractNextTokenFromList( token, paramName, '=' );

				if ( paramBytesConsumed == 0 )
					{
					User::Leave( KErrHttpDecodeBasicAuth );
					}

				// Obtain the parameter value. It is a string which
				// may or may not be quoted. 
				TPtrC8 paramVal;
				if ( token.Length() > 0 && token[0] == '"' )
					{
					bytesConsumed += InetProtTextUtils::ExtractQuotedStringL( token, paramVal );
					}
				else
					{
					paramVal.Set( token );
					}

				SetNewStringParamL( *part, paramName, paramVal );
				}
			}
		}
	}
// ---------------------------------------------------------------------------
// 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;
	}
/**
ConstructL()
Parses a .txt file and creates Arrays of fields and there values

@param aFileName
Name of the file to be parsed.
*/
EXPORT_C void CT_MsgUtilsConfigFileParserUtility::ConstructL(const TDesC& aFileName)
	{
	RFs fileServerSession;

	fileServerSession.Connect();

	RFile file;
	User::LeaveIfError(file.Open(fileServerSession, aFileName, EFileRead));

	TInt eof = EFalse;
	TInt fileOffset = 0;
	TBuf8<KFileBufferSize> fileBuffer;

	while (!eof)
		{
		fileBuffer.SetLength(0);
		User::LeaveIfError(file.Read(fileOffset, fileBuffer, KFileBufferSize));
		TInt read = fileBuffer.Length();

		if (read < KFileBufferSize)
			{
			fileBuffer.Append('\n');
			eof = ETrue;
			}

		TInt lineOverflow = fileBuffer.Locate('\n');
		
		if ((lineOverflow == KErrNotFound) && (read == KFileBufferSize))
			{
			User::Leave(KErrOverflow);
			}

		TInt eol = EFalse;
		
		while (!eol)
			{
			TInt lineFeedLocation = fileBuffer.Locate('\n');
			
			if (lineFeedLocation == KErrNotFound)
				{
				eol = ETrue;
				}
			
			else
				{
				fileOffset += lineFeedLocation + 1;
				TInt lineLength;
				if ((lineFeedLocation != 0) && (fileBuffer[lineFeedLocation - 1] == '\r'))
					{
					lineLength = lineFeedLocation - 1;
					}
					
				else
					{
					lineLength = lineFeedLocation;
					}
					
				TPtrC8 line  = fileBuffer.Left(lineLength);
				TInt commentLocation = line.Match(KComment);
				
				if (commentLocation != KErrNotFound)
					{
					TPtrC8 skipComment = line.Left(commentLocation);
					line.Set(skipComment);
					}
					
				TInt seperatorLocation = line.Locate('=');
				
				if (seperatorLocation != KErrNotFound)
					{
					if ((seperatorLocation == 0) || (seperatorLocation == line.Length() - 1))
						{
						seperatorLocation = KErrNotFound;
						}
					}
					
				if (seperatorLocation != KErrNotFound)
					{
					TPtrC8 namePtr = line.Left(seperatorLocation);
					HBufC8* nameBuf8 = HBufC8::NewL(namePtr.Length());
					CleanupStack::PushL(nameBuf8);
					
					TPtr8 name8 = nameBuf8->Des();
					name8.Copy(namePtr);
					name8.Trim();
					HBufC* nameBuf16 = HBufC::NewL(namePtr.Length());
					TPtr name16 = nameBuf16->Des();
					name16.Copy(name8);
					iName.Append(nameBuf16);
					CleanupStack::PopAndDestroy(nameBuf8);

					TPtrC8 contentPtr = line.Mid(seperatorLocation + 1);
					HBufC8* contentBuf8 = HBufC8::NewL(contentPtr.Length());
					CleanupStack::PushL(contentBuf8);
					TPtr8 content8 = contentBuf8->Des();
					content8.Copy(contentPtr);
					content8.Trim();
					
					HBufC* contentBuf16 = HBufC::NewL(contentPtr.Length());
					TPtr content16 = contentBuf16->Des();
					content16.Copy(content8);
					iContent.Append(contentBuf16);
					iContent8.Append(contentBuf8);
					CleanupStack::Pop(contentBuf8);
					}
				TPtrC8 theRest = fileBuffer.Mid(lineFeedLocation + 1);
				fileBuffer.Copy(theRest);
				}
			}
		}
	file.Close();
	fileServerSession.Close();
	}
// ---------------------------------------------------------------------------------
// CUpnpTmFilteredAppList::ParseAppFilterStringL
// Method parses the descriptor containing the filter string
// It parses the comma-separated list of A_ARG_TYPE_AppList schema 
// elements, attributes and their values
// eg: "name="*Audio*",description="*",icon@mimetype="*svg+xml*", remotingInfo@protocolID="*",
//     appInfo@appCategory="*",audioInfo@audioType="*",resourceStatus="free",signature="*""
// @param aAppFilter Buffer containing application filter string
// @param aErr[out]  Terminal Mode error code
// ---------------------------------------------------------------------------------
//
void CUpnpTmFilteredAppList::ParseAppFilterStringL( const TDesC8& aAppFilter, 
                                                     TTerminalModeErrorCode& aErr )
    {
    OstTraceFunctionEntry0( CUPNPTMFILTEREDAPPLIST_PARSEAPPFILTERSTRINGL_ENTRY );
    // Validate the filter string
    aErr = ETerminalModeSuccess;
    TInt quotePos = aAppFilter.Locate( KQuote );
    if ( ( quotePos != 0 ) || ( aAppFilter.Find(KDoubleQuote) == KErrNotFound ))    
        {
        // corrupt filter string
        aErr = ETerminalModeInvalidArgument;
        OstTrace1( TRACE_ERROR, DUP2_CUPNPTMFILTEREDAPPLIST_PARSEAPPFILTERSTRINGL, "CUpnpTmFilteredAppList::ParseAppFilterStringL;quotePos=%d", quotePos );
        return;
        }
    RBuf8 filterBuffer;
    CleanupClosePushL(filterBuffer);
    /* Create a buffer having the content of AppFilter buffer but without 
       the leading quote(")  */ 
    filterBuffer.CreateL(aAppFilter.Mid(quotePos+1));
    TInt equalToQuoteToken;
    while( ( equalToQuoteToken = filterBuffer.Find(Keq)) != KErrNotFound )
        {
        // Fetch the full key string
        TPtrC8 key = filterBuffer.Left(equalToQuoteToken);
        // Check for the presence of sub element by checking the @ in the key string
        TInt atTokenPos = key.Find(KAtToken);
        TBool displayInfo(EFalse);
        if ( atTokenPos != KErrNotFound )
            {
            // @ is found in the key string
            // Now extract the parent element
            TPtrC8 parentKey = key.Left(atTokenPos);
            //Remove any leading and trailing whitespaces in the parent element
            const TDesC8& parentKeyWithoutSpace = RemoveWhiteSpace(parentKey);
            // Check if the parent elemet is one of desired element or not.
            // It should be one of the following :
            // <1> icon <2> remotingInfo <3> appInfo <4> displayInfo <5> audioInfo
            if ( ( parentKeyWithoutSpace.Compare(KIconElement) != KErrNone ) &&
                ( parentKeyWithoutSpace.Compare(KRemotingInfo) != KErrNone ) &&
                ( parentKeyWithoutSpace.Compare(KAppInfo) != KErrNone ) &&
                ( parentKeyWithoutSpace.Compare(KDisplayInfo) != KErrNone ) &&
                ( parentKeyWithoutSpace.Compare(KAudioInfo) != KErrNone ) )
                {
                // parent element is not proper
                aErr = ETerminalModeInvalidArgument;   
                break;
                }
            if ( parentKeyWithoutSpace.Compare(KDisplayInfo) == KErrNone )
                {
                // The parent key element is displayInfo
                displayInfo = ETrue;   
                }
            // Fetch the actual key name ( child element )
            key.Set(key.Mid(atTokenPos+1));
            }
        
        //Remove any leading and trailing whitespaces in the key 
        const TDesC8& keyWithoutSpace = RemoveWhiteSpace(key);
        if ( (filterBuffer.Mid(equalToQuoteToken) ).Locate(KQuote) != 1 )
            {
            // Missing quote(") ahead of the value
            aErr = ETerminalModeInvalidArgument;
            break;    
            }
        TPtrC8 bufPtr = filterBuffer.Mid(equalToQuoteToken+2);
        quotePos = bufPtr.Locate( KQuote );
        if ( quotePos == KErrNotFound )
            {
            // missing quote (") at the end of the value
            aErr = ETerminalModeInvalidArgument;
            break;
            }
        
        /* Add the filter info as key-value pairs.
        // Also check if the parent key is display info.
           If display info flag is true then use the method with non default parameter */
        if ( displayInfo )
            {
            iFilterInfo->SetFilterInfoL( keyWithoutSpace, bufPtr.Left(quotePos), aErr, ETrue );
            }
        else
            {
            // Use the method with default parameter
            iFilterInfo->SetFilterInfoL( keyWithoutSpace, bufPtr.Left(quotePos), aErr );   
            }
        if ( aErr != ETerminalModeSuccess )
            {
            // Return the error code in case the key element is not as per the schema
            aErr = ETerminalModeInvalidArgument;
            break;
            }
        // Skip the quote position and set the buffer
        bufPtr.Set(bufPtr.Mid(quotePos+1));
        if ( ( bufPtr.Locate(KCommaSeparator) != 0 ) && ( bufPtr.Locate(KQuote) != 0 ) )
            {
            //  missing quote (") or comma (,) following the quote.
            //  Expected to be something of this kind ( ", or "" )
            aErr = ETerminalModeInvalidArgument;
            break;      
            }
        //Copy the residual content skipping two characters(", or "" ) in the actual buffer
        filterBuffer.Copy(bufPtr.Mid(UpnpString::KLinefeedLength));
        }
    CleanupStack::PopAndDestroy(&filterBuffer);
    OstTrace1( TRACE_FLOW, CUPNPTMFILTEREDAPPLIST_PARSEAPPFILTERSTRINGL, "CUpnpTmFilteredAppList::ParseAppFilterStringL;aErr=%d", aErr );
    OstTraceFunctionExit0( CUPNPTMFILTEREDAPPLIST_PARSEAPPFILTERSTRINGL_EXIT );
    }
void CUPnPHeaderReader::DecodeManL(RHeaderField& aHeader) const
	{
	TPtrC8 rawData;
	aHeader.RawDataL(rawData);
	TInt remaining = rawData.Length();
	TPtrC8 token;
	TInt tokensFound = 0;
	while (remaining > 0)
		{
		remaining -= InetProtTextUtils::ExtractNextTokenFromList(rawData, token, KCommaChar);

		TInt pos = token.Locate(KSemiColonChar);
		if (pos < 0)
			{
			// No parameters. Just store the field value
			InetProtTextUtils::RemoveWhiteSpace(token, InetProtTextUtils::ERemoveBoth);
			SetNewFStringPartL(aHeader, tokensFound, token);
			}
		else if (pos==0)
			{
			// No valid ns-value. Just store the parameter.
			User::Leave(KErrUPnPDecodeMAN);
			}
		else
			{
			// parameter value(s) exist.

			if (pos==token.Length())
				// if no field value exists. i.e. an invalid header
				User::Leave(KErrUPnPDecodeMAN);

			// store the field
			TPtrC8 fieldValue(token.Left(pos));
			TPtrC8 parameters(token.Mid(pos+1));
			InetProtTextUtils::RemoveWhiteSpace(fieldValue, InetProtTextUtils::ERemoveBoth);

			CHeaderFieldPart* part = SetNewFStringPartL(aHeader, tokensFound, fieldValue);

			TPtrC8 thisParam;
			do {
				// check if there is another parameter
				pos = parameters.Locate(KSemiColonChar);
				if (pos > 0)
					{
					if (pos==token.Length())
						// if no field value exists. i.e. an invalid header
						User::Leave(KErrUPnPDecodeMAN);

					thisParam.Set(parameters.Left(pos));
					parameters.Set(parameters.Mid(pos+1));
					}
				else
					thisParam.Set(parameters);

				
				TInt pPos = thisParam.Locate(KEqualsChar);
				if (pPos <= 0 || pPos==thisParam.Length())
					// Invalid parameter, missing '=' char, or missing field value.
					User::Leave(KErrUPnPDecodeMAN);

				TPtrC8 paramField(thisParam.Left(pPos));
 				TPtrC8 paramData(thisParam.Mid(pPos + 1));

				SetNewFStringParamL(*part, paramField, paramData);

				} while (pos > 0);
			}
		++tokensFound;
		}
	}
Beispiel #20
0
TInt CISO2022KRImplementation::ConvertToUnicode(
    CCnvCharacterSetConverter::TEndianness aDefaultEndiannessOfForeignCharacters, 
    TDes16& aUnicode, 
    const TDesC8& aForeign, 
    TInt& aState, 
    TInt& aNumberOfUnconvertibleCharacters, 
    TInt& aIndexOfFirstByteOfFirstUnconvertibleCharacter)
	{
    TInt err;
    TInt ret = 0;
    TInt currPos = 0;
    TInt convPos = 0;
    TInt shiftInPos = KErrNotFound;
    TInt shiftOutPos = KErrNotFound;
    TInt shiftPos = KErrNotFound;
    TInt escPos = KErrNotFound;
    TPtrC8 currSegment;
    TPtrC8 convSegment;
    TBool changeState = EFalse;

    TUint outputConversionFlags = 0;
    TUint inputConversionFlags = CCnvCharacterSetConverter::EInputConversionFlagAppend;
    TInt numberOfUnconvertibleCharacters = 0;
    TInt indexOfFirstByteOfFirstUnconvertibleCharacter = 0;
    aNumberOfUnconvertibleCharacters = 0;

    while( currPos < aForeign.Length() )
        {

        currSegment.Set( aForeign.Mid( currPos ) );

        /* First change state if needed */
        if( changeState )
            {
            changeState = EFalse;
            if( (aState & KBitsForNonStandardStates) == KShiftedToKSCState )
                { /* Switch back to default ASCII */
                aState &= ~(KShiftedToKSCState);
                }
            else
                { /* Switch to KSC */
                aState |= KShiftedToKSCState; 
                }
            }

        /* Search for escape which should be skipped */
        escPos = currSegment.Find( KLit8EscapeSequence );
        
        /* Search for shift in byte */
        shiftInPos = currSegment.Locate( SHIFT_IN_BYTE );

        /* Search for shift out byte */
        shiftOutPos = currSegment.Locate( SHIFT_OUT_BYTE );

        /* Set shift pos according to found shift bytes */
        if( shiftInPos == KErrNotFound &&
            shiftOutPos == KErrNotFound )
            { /* Neither found */
            shiftPos = KErrNotFound;
            }
        else
            {
            if( (shiftInPos != KErrNotFound) &&
                ((shiftInPos < shiftOutPos) || (shiftOutPos == KErrNotFound)) )
                { /* shift in is nearer or shift out not found */
                shiftPos = shiftInPos;
                /* Set state change if needed */
                if( (aState & KBitsForNonStandardStates) == KShiftedToKSCState )
                    {
                    changeState = ETrue;
                    }
                }
            else
                { /* shift out must be nearer or shift in not fouind */
                shiftPos = shiftOutPos;
                /* Set state change if needed */
                if( (aState & KBitsForNonStandardStates) != KShiftedToKSCState )
                    {
                    changeState = ETrue;
                    }
                }
            }

        if( shiftPos == KErrNotFound )
            { /* Shift byte not found, same coding for the rest of the data */
            if( escPos == KErrNotFound )
                { /* No escape sequence either, just convert the rest */
                convSegment.Set( currSegment );
                }
            }
        else if( ((escPos != KErrNotFound) && (shiftPos < escPos)) ||
                 (escPos == KErrNotFound) )
            { /* Shift byte found and it comes before escape sequence or no escape
                 sequence was found, convert data preceeding the shift byte if shift
                 byte isn't the first character */
                if( shiftPos == 0 )
                { /* No data to convert preceeds the shift byte, just skip it and continue */
                    currPos += 1;
                    continue;
                }
                convSegment.Set( currSegment.Left( shiftPos ) );
                /* Clear to prevent convert to escape sequence */
                escPos = KErrNotFound;
            }

        if( escPos != KErrNotFound )
            { /* Escape sequence found before any shift bytes,
                 clear possible state change and convert data
                 preceeding the escape sequence if
                 escape sequence is not at the beginning */
            changeState = EFalse;
            if( escPos == 0 )
                { /* No data to convert preceeds the escape sequence, just skip it continue */
                currPos += KLit8EscapeSequence().Length();
                continue;
                }
            convSegment.Set( currSegment.Left( escPos ) );
            }

        if( (aState & KBitsForNonStandardStates) == KShiftedToKSCState )
            { /* Convert KSC encoded */
            HBufC8 *tmpForeign = NULL;

            if( (convSegment.Length() & 0x1) )
                { /* KSC should have even amount of bytes */
                ret = CCnvCharacterSetConverter::EErrorIllFormedInput;
                }
            else
                {
                convPos = 0;
                while( convPos < convSegment.Length() )
                    {
                    TRAP( err, tmpForeign = HBufC8::NewL( KMaxSizeOfTmpBuffer ) );
                    if( err != KErrNone )
                        {
                        User::Panic( _L("ISO-2022-KR"), err );
                        }

                    if( convSegment.Length() < KMaxSizeOfTmpBuffer )
                        { /* Convert whole segment */
                        tmpForeign->Des().Copy( convSegment );
                        }
                    else
                        { /* Convert in chunks */
                        if( (convPos + KMaxSizeOfTmpBuffer) >= convSegment.Length() )
                            { /* Last chunk */
                            tmpForeign->Des().Copy( convSegment.Mid( convPos ) );
                            }
                        else
                            {
                            tmpForeign->Des().Copy( convSegment.Mid( convPos, KMaxSizeOfTmpBuffer ) );
                            }
                        }

                    TUint8 *chars = (TUint8 *)tmpForeign->Des().Ptr();
                    for( TInt i = 0 ; i < tmpForeign->Length() ; i++ )
                        { /* Set highest bit in characters */
                        chars[i] |= 0x80;
                        }

                    numberOfUnconvertibleCharacters = 0;
                    ret = CCnvCharacterSetConverter::DoConvertToUnicode( CnvCp949Table::ConversionData(),
                                                                         aDefaultEndiannessOfForeignCharacters,
                                                                         aUnicode, *tmpForeign,
                                                                         numberOfUnconvertibleCharacters,
                                                                         indexOfFirstByteOfFirstUnconvertibleCharacter,
                                                                         outputConversionFlags,
                                                                         inputConversionFlags );
                    if( numberOfUnconvertibleCharacters != 0 &&
                        aNumberOfUnconvertibleCharacters == 0 )
                        { /* First uncovertible found, set index relative to actual input buffer*/
                        aIndexOfFirstByteOfFirstUnconvertibleCharacter = (currPos + convPos + indexOfFirstByteOfFirstUnconvertibleCharacter);
                        }

                    aNumberOfUnconvertibleCharacters += numberOfUnconvertibleCharacters;

                    if( ret < 0 )
                        { /* Some error, break the loop,
                             errors are handled later */
                        delete tmpForeign;
                        break;
                        }

                    if( ret > 0 )
                        { /* Not all were converted, fix return value
                             to be relative to convSegment and break the loop */
                        ret = (convSegment.Length() - convPos - tmpForeign->Length() + ret);
                        delete tmpForeign;
                        break;
                        }

                    convPos += tmpForeign->Length();
                    delete tmpForeign;
                    }
                }
            }
        else
            { /* Convert ASCII encoded by default, KSC can be used without setting highest bit */
                numberOfUnconvertibleCharacters = 0;
                ret = CCnvCharacterSetConverter::DoConvertToUnicode( CnvCp949Table::ConversionData(),
                                                                     aDefaultEndiannessOfForeignCharacters,
                                                                     aUnicode, convSegment,
                                                                     numberOfUnconvertibleCharacters,
                                                                     indexOfFirstByteOfFirstUnconvertibleCharacter,
                                                                     outputConversionFlags,
                                                                     inputConversionFlags );
                if( numberOfUnconvertibleCharacters != 0 &&
                    aNumberOfUnconvertibleCharacters == 0 )
                    { /* First uncovertible found, set index relative to actual input buffer*/
                    aIndexOfFirstByteOfFirstUnconvertibleCharacter = currPos + indexOfFirstByteOfFirstUnconvertibleCharacter;
                    }
                aNumberOfUnconvertibleCharacters += numberOfUnconvertibleCharacters;
            }

        if( ret < 0 )
            { /* Error during conversion */
            return ret;
            }
        else if( ret > 0 )
            { /* Not all characters where converted, return
                 value indicating how many bytes in total are left unconverted */
            return (aForeign.Length() - currPos - convSegment.Length() + ret);
            }

        /* Increase to skip converted data */
        currPos += convSegment.Length();
        if( escPos != KErrNotFound )
            { /* Increase to skip escape sequence */
            currPos += KLit8EscapeSequence().Length();
            }
        else if( shiftPos != KErrNotFound )
            { /* Increase to skip shift byte */
            currPos += 1;
            }

        }

    return 0;
	}
void COperationParser::ParseOperationsL( TDes8& aReturnTxt)
{
	//reset line counter and initialize XML-parser
	iActiveLine = 0;
	iReturnText = &aReturnTxt;
	iXMLStackPointer = 0;
	ResetOperations();


	//initliaze symbian xml parser
	iParser->ParseBeginL();
	
	//Max size of chunk (max text length, which go once to parser)
	const TInt KMaxChunkLength = 1000;
	
	TPtrC8 xml = iXMLContent;
	TPtrC8 chunk;
	TInt length = KMaxChunkLength < xml.Length() ? KMaxChunkLength : xml.Length();

	do
	{
		//Find line feed mark (asciicode 10)
		TInt indexLineFeed = xml.Locate(10);
		TInt elementEndIndex = xml.Locate( KXMLElementEndMark );

		if ( elementEndIndex != KErrNotFound && (elementEndIndex < indexLineFeed || indexLineFeed == KErrNotFound))
		{
			length = elementEndIndex + 1;
		}
		else
		if ( indexLineFeed != KErrNotFound)
		{ 
			//max text, which go to parser is one line or KMaxChunkLength. Counter tracks line, where parsing is going
			iActiveLine++;
		
			length = indexLineFeed + 1;
		}

		//set chunk pointer
		chunk.Set( xml.Left(length));
		

		if ( ParserUtility::ContainsCDataField( chunk))
		{
			//cdata mark indicated in chunk, remove cdata area from chunk, 
			TPtrC8 cdata;
			ParserUtility::ReadCDataAreaL( cdata, chunk, xml);
			
			//pointer to cdata content
			ParserUtility::RemoveCDataMarksL( cdata);
	
			if ( !iActiveOperation)
			{
				HandleErrorL( ParserErrors::UnexpectedElement, KCDataElement); 
			}
			
			iActiveOperation->SetXACMLContentL( cdata);
			iActiveOperation->SetLineOffset( iActiveLine - 1);
			
			iActiveLine += ParserUtility::LineCounter( cdata);
		}
		else
		{
			//set remaining XACML description to xacmlDescription
			xml.Set( xml.Mid(length));			
		}

		//'|' and '~' are not allowed in policy system...
		if ( chunk.Locate('|') != KErrNotFound || chunk.Locate('~') != KErrNotFound)
		{
			HandleErrorL( ParserErrors::InvalidMark, ParserErrors::InvalidMarks); 
		}
		
		//drive description to parser	
		iParser->ParseL( chunk);
	
		length = KMaxChunkLength < xml.Length() ? KMaxChunkLength : xml.Length();
	} while ( length);

	//close parser
	iParser->ParseEndL();	
}