示例#1
0
BOOL HTTPMessageWriter::URLStartWithHTTP(const uni_char *url)
{
	OP_ASSERT(url);

	if(!url)
		return FALSE;

	return !uni_strncmp(url, UNI_L("http://"), 7) || !uni_strncmp(url, UNI_L("HTTP://"), 7) || !uni_strncmp(url, UNI_L("https://"), 8) || !uni_strncmp(url, UNI_L("HTTPS://"), 8);
}
示例#2
0
/**
 * Returns OpStatus:ERR if there is no legal mapping.
 */
static OP_STATUS MapAttributeToPropertyName(const uni_char* attr, TempBuffer& prop)
{
	if (uni_strncmp(attr, "data-", 5) != 0)
		return OpStatus::ERR;

	attr += 5;
	const uni_char* p = attr;
	while (*p)
	{
		if (*p >= 'A' && *p <= 'Z')
			return OpStatus::ERR;
		p++;
	}

	while (*attr)
	{
		if (*attr == '-' && attr[1] >= 'a' && attr[1] <= 'z')
		{
			RETURN_IF_ERROR(prop.Append(attr[1] - 'a' + 'A'));
			attr++;
		}
		else
			RETURN_IF_ERROR(prop.Append(*attr));
		attr++;
	}

	return OpStatus::OK;
}
示例#3
0
INT32 GetSmiley(const uni_char* content, OpString8& smiley_tag, INT32& smiley_tag_len, const uni_char* start_of_text, unsigned int content_length, BOOL use_xml)
{
    if (!uni_strchr(start_of_smileys, *content)) //Is the start of the text one of the possible start of a smiley?
        return 0;

    if (content==start_of_text || uni_strchr(UNI_L(" \r\n\t"), *(content-1)) ) //Do we have whitespace in front of it?
    {
        struct Smileys *smiley;
        for (smiley = smileys_list; smiley->smiley_length>0; smiley++)
        {
            if (uni_strncmp(smiley->smiley, content, smiley->smiley_length) == 0) //We have found a smiley!
            {
                if (smiley->smiley_length == content_length || uni_strchr(UNI_L(" \r\n\t"), content[smiley->smiley_length])) //Do we have whitespace after it?
                {
                    smiley_tag.AppendFormat(
                        use_xml ?	"<html:span class=\"smiley-%s\" title=\"%s\">%s</html:span>" :
                        "<span class=\"smiley-%s\" title=\"%s\">%s</span>",
                        smiley->smiley_class,
                        smiley->smiley_xmlified ? smiley->smiley_xmlified : smiley->smiley,
                        smiley->smiley_xmlified ? smiley->smiley_xmlified : smiley->smiley);

                    smiley_tag_len = smiley_tag.Length();

                    return smiley->smiley_length;
                }
                break;
            }
        }
    }

    return 0;
}
/*!
 * Save plug-in subtitle with the same name of current playing file
 */
static void _ui_video_m_save_subt_lang(u16 *p_path)
{
    u8   i          = 0;
    u8   j          = 0;
    u8   cnt        = 0;
    u16 *p_temp     = NULL;
    u16 *p_name     = NULL;
    u16 *p_subt_tmp = NULL;   

    if(NULL == p_path)
    {
        UI_VIDEO_PRINF("[%s]: ##ERR## file name null\n", __FUNCTION__);
        return;
    }

    cnt = (u8)MIN(g_video_m.subt_list.file_count, V_SUB_CNT_MAX);

    p_name = _ui_video_m_get_name_without_path(p_path);

    p_temp = mtos_malloc(sizeof(u16) * (uni_strlen(p_name) + 1));

    uni_strcpy(p_temp, p_name);

    _ui_video_m_get_name_without_ext(p_temp);

    p_subt_tmp = mtos_malloc(sizeof(u16) * MAX_FILE_PATH);

    for(i = 0; i < cnt; i++)
    {
        uni_strncpy(p_subt_tmp, g_video_m.subt_list.p_file[i].p_name, MAX_FILE_PATH - 1);

        if(0 == uni_strncmp(p_subt_tmp, p_temp, uni_strlen(p_temp)))
        {
            /*!
             * Ignore ext, Eg "test.chg.ssa->test.chg" or "test123.ssa" -> "test123"
             */
            _ui_video_m_get_name_without_ext(p_subt_tmp);

            /*!
             * If string is "test.chg", only save "chg"
             */
            _ui_video_m_get_ext_without_name(p_subt_tmp);

            uni_strncpy(g_video_m.subt[j].subt_lang, p_subt_tmp, V_SUB_LANG_LEN - 1);

            /*!
             * Save the index for finding name
             */
            g_video_m.subt[j++].idx = i;
        }
    }

    mtos_free(p_temp);
    mtos_free(p_subt_tmp);

    g_video_m.subt_cnt = j;

    UI_VIDEO_PRINF("[%s]: total cnt:%d name:%s sub cnt:%d\n", __FUNCTION__, cnt, p_name, j);
}
示例#5
0
Counter* Counters::GetCounter(const uni_char* name, unsigned int name_length)
{
	for (Counter* counter = (Counter*) counter_list.First(); counter; counter = (Counter*) counter->Suc())
		if (name_length == counter->GetNameLength() && uni_strncmp(counter->GetName(), name, name_length) == 0)
			return counter;

	return NULL;
}
示例#6
0
/*static*/
BOOL OpDbUtils::StringsEqual(const uni_char* lhs_value, unsigned lhs_length,
		const uni_char* rhs_value, unsigned rhs_length)
{
	return lhs_length == rhs_length &&
			(lhs_value == rhs_value ||
				(lhs_value != NULL && rhs_value != NULL && uni_strncmp(lhs_value, rhs_value, lhs_length) == 0)
			);
}
示例#7
0
OP_STATUS
SVGPaintParser::ParsePaint(const uni_char *input_string, unsigned input_string_length,
						   SVGPaint& paint)
{
    if (input_string_length == 4 && uni_strncmp(input_string, "none", 4) == 0)
    {
		paint.SetPaintType(SVGPaint::NONE);
		return OpStatus::OK;
    }
    else if (input_string_length == 12 && uni_strncmp(input_string, "currentColor", 12) == 0)
    {
		paint.SetPaintType(SVGPaint::CURRENT_COLOR);
		return OpStatus::OK;
    }
    else
    {
		SVGColor color;
		const uni_char *url_string;
		unsigned url_string_length;
		status = OpStatus::OK;

		tokenizer.Reset(input_string, input_string_length);
		if (tokenizer.ScanURL(url_string, url_string_length))
		{
			paint.SetPaintType(SVGPaint::URI);
			paint.SetURI(url_string, url_string_length);

			tokenizer.EatWsp();
			if (!tokenizer.IsEnd())
				ScanBackupPaint(paint);
		}
		else if (ScanColor(color))
		{
			paint.SetPaintType(SVGPaint::RGBCOLOR);
			paint.SetColorRef(color.GetColorRef());
		}
		else
		{
			status = OpStatus::ERR;
		}

		return tokenizer.ReturnStatus(status);
    }
}
示例#8
0
int OpStringC16::Compare(const uni_char* aCStr, int aLength) const
{
	if (aCStr == NULL || *aCStr == '\0')
		return (iBuffer == NULL || *iBuffer == '\0') ? 0 : 1;
	if (iBuffer == NULL)
		return -1;
	if (aLength == KAll)
		return uni_strcmp(iBuffer, aCStr);
	return uni_strncmp(iBuffer, aCStr, aLength);
}
示例#9
0
/***********************************************************************************
 ** ParseIndexThemeFile
 **
 **
 **
 **
 ***********************************************************************************/
OP_STATUS IndexThemeFile::ParseInternal(OpFile & file)
{
    //-----------------------------------------------------
    // Parameter checking:
    //-----------------------------------------------------
    //File pointer cannot be null
    OP_ASSERT(file.IsOpen());
    if(!file.IsOpen())
	return OpStatus::ERR;

    //Node pointer cannot be null
    OP_ASSERT(m_node);
    if(!m_node)
	return OpStatus::ERR;
    //-----------------------------------------------------

    OpString theme_path;
    theme_path.Set(file.GetFullPath());
    FileHandlerManagerUtilities::RemoveSuffix(theme_path, UNI_L("index.theme"));

    m_node->SetThemePath(theme_path.CStr());

    //Split file into lines - only if smaller than 100k
    // - All desktop files should be less than 100k
    UINT32 max_size = 100000;
    OpAutoVector<OpString> list;
    FileHandlerManagerUtilities::FileToLineVector(&file, list, max_size);
	
    for(UINT32 i = 1; i < list.GetCount(); i++)
    {
		OpString* line = list.Get(i);
		OpAutoVector<OpString> items;
		FileHandlerManagerUtilities::SplitString(items, *line, '=');
		
		if(items.GetCount() == 2)
		{
			OpString * item_0 = items.Get(0);
			OpString * item_1 = items.Get(1);
			
			if(uni_strncmp(item_0->CStr(), UNI_L("Inherits"), 7) == 0)
			{
				m_node->SetInherits(item_1->CStr());
			}
		}
    }

    return OpStatus::OK;
}
BOOL MacOpDesktopResources::IsSameVolume(const uni_char* path1, const uni_char* path2)
{
	const uni_char * voff1 = uni_strstr(path1, UNI_L("/Volumes/"));
	const uni_char * voff2 = uni_strstr(path2, UNI_L("/Volumes/"));
	if (voff1 != path1 && voff2 != path2) {
		// Both on boot volume
		return TRUE;
	}
	if (voff1 == path1 && voff2 == path2) {
		// Both on non-boot
		voff1 = uni_strchr(path1+9, UNI_L('/'));
		voff2 = uni_strchr(path2+9, UNI_L('/'));
		if (voff1 && voff2) {
			int vlen1=(voff1-path1);
			int vlen2=(voff2-path2);
			if (vlen1==vlen2 && uni_strncmp(path1,path2,vlen1)==0)
				return TRUE;
		}
	}
	return FALSE;
}
示例#11
0
OP_STATUS ExtensionUtils::GetAccessLevel(OpGadgetClass *gclass, BOOL& has_access_list, 
                                         OpString& access_list, BOOL& has_userjs_includes)
{

	has_access_list = FALSE;
	OpGadgetAccess* access = gclass->GetFirstAccess();
		
	if (access && access->Suc() == NULL)
	{
		has_access_list = TRUE;
		if (uni_strncmp(access->Name(), UNI_L("*"), 1) == 0)
		{
			access_list.Append(GetLocaleString(Str::D_INSTALL_EXTENSION_ACCESS_WEBPAGES).CStr());
		}
		else
		{
			access_list.AppendFormat(GetLocaleString(Str::D_INSTALL_EXTENSION_ACCESS_SINGLE_SITE).CStr(), access->Name());
		}
	}
	else 
	{
		if (!access)
		{
			access_list.Append(GetLocaleString(Str::D_INSTALL_EXTENSION_ACCESS_NONE).CStr());
		}
		else 
		{
			has_access_list = TRUE;
			access_list.Append(GetLocaleString(Str::D_INSTALL_EXTENSION_ACCESS_WEBPAGES).CStr());
		}		
	}
	
	has_userjs_includes = FALSE;
	RETURN_IF_ERROR(ExtensionUtils::HasExtensionUserJSIncludes(gclass, has_userjs_includes));

	return OpStatus::OK;    
}
/*!
 * When enter directory or change partition, it need check current playing file is in directory
 * or partition, if in, it should highlight it.
 */
RET_CODE ui_video_m_find_idx_by_cur_play_file(u32 *p_idx)
{
    u32 i          = 0;
    u32 cnt        = 0;
    u16 *p_path     = NULL;
    u16 *p_cur_file = NULL;

    p_cur_file = ui_video_m_get_cur_playing_file_path();

    if((NULL == p_cur_file) || (NULL == p_idx))
    {
        UI_VIDEO_PRINF("[%s]: ##ERR## current file null\n", __FUNCTION__);    
        return ERR_FAILURE;
    }

    UI_VIDEO_PRINF("[%s]: current playing file path = %s\n", __FUNCTION__, p_cur_file);
    
    cnt = ui_video_m_get_total();

    for(i = 0; i < cnt; i++)
    {
        p_path = ui_video_m_get_path_by_idx(i);

        if(NULL != p_path)
        {
            UI_VIDEO_PRINF("[%s]: path[%d] = %s\n", __FUNCTION__, i, p_path);
        }
        
        if((NULL != p_path) && (0 == uni_strncmp(p_cur_file,p_path, uni_strlen(p_cur_file))))
        {
            *p_idx = i;
            return SUCCESS;
        }
    }

    return ERR_FAILURE;
}
示例#13
0
OP_STATUS
OpSecurityManager_DOM::CheckWorkerScriptImport(const OpSecurityContext& source, const OpSecurityContext& target, BOOL& allowed)
{
	allowed = FALSE;

	URLType target_type = target.GetURL().Type();
	switch (source.GetURL().Type())
	{
	case URL_HTTP:
	case URL_HTTPS:
	case URL_DATA:
		allowed = target_type == URL_HTTP || target_type == URL_HTTPS || target_type == URL_DATA;
		break;

	case URL_FILE:
		if (target_type == URL_FILE)
		{
			/* The target must be at or below the source/worker's directory. */

			OpString worker_file, target_file;

			{
				OpString worker_string, target_string;

				RETURN_IF_ERROR(source.GetURL().GetAttribute(URL::KUniName_Username_Password_Escaped_NOT_FOR_UI, worker_string));
				RETURN_IF_ERROR(target.GetURL().GetAttribute(URL::KUniName_Username_Password_Escaped_NOT_FOR_UI, target_string));

				RETURN_OOM_IF_NULL(worker_file.Reserve(worker_string.Length() + 1));
				UriUnescape::Unescape(worker_file.CStr(), worker_string.CStr(), UriUnescape::ExceptUnsafeCtrl);

				RETURN_OOM_IF_NULL(target_file.Reserve(target_string.Length() + 1));
				UriUnescape::Unescape(target_file.CStr(), target_string.CStr(), UriUnescape::ExceptUnsafeCtrl);
			}

			unsigned length = worker_file.Length();
			const uni_char *str = worker_file.CStr();
			while (length != 0)
				if (str[length - 1] == '/')
					break;
				else
					--length;

			allowed = length > 0 && length < static_cast<unsigned>(target_file.Length()) &&
			          uni_strncmp(worker_file.CStr(), target_file.CStr(), length) == 0;

			if (allowed)
			{
				const uni_char *dotdot = target_file.CStr() + length;
				while (dotdot && allowed)
				{
					dotdot = uni_strstr(dotdot, UNI_L(".."));
					if (dotdot && (IS_LIKELY_PATH_SEP_CHARACTER(dotdot[-1]) && IS_LIKELY_PATH_SEP_CHARACTER(dotdot[2])))
						allowed = FALSE;
					else
						dotdot = dotdot ? dotdot + 1 : NULL;
				}
			}
		}
		else
			allowed = target_type == URL_HTTP || target_type == URL_HTTPS || target_type == URL_DATA;
		break;
	default:
		break;
	}

	return OpStatus::OK;
}
示例#14
0
OP_STATUS
OpScopeTPReader::ParseStream()
{
    OP_ASSERT(enabled);

    while (true)
    {
        switch (state)
        {
        case Message:
        {
            if (version == 0)
            {
                state = STP0_Message;
                continue;
            }
            else
                state = Prefix;
            message_version = 1;
        }

        case Prefix:
        {
            if (incoming->Length() < 4)
                return STPStatus::ERR_NOT_ENOUGH_DATA;
            char buffer[4]; // "STP" + ver // ARRAY OK 2009-05-05 jhoff
            incoming->Extract(0, 4, buffer);
            if (buffer[0] != 'S' || buffer[1] != 'T' || buffer[2] != 'P')
            {
                return OpStatus::ERR_PARSING_FAILED;
            }
            message.Clear();
            incoming->Consume(4);
            unsigned int incoming_version = buffer[3];
            // Check if we support the message
            if (incoming_version == 0)
            {
                // Support for STP/0 message wrapped in a STP/1 message
                message_version = 0;
            }
            else if (incoming_version > 1)
            {
                // TODO: Report it somewhere/somehow?
                state = IgnoreMessageSize;
                continue;
            }
            message.SetVersion((OpScopeTPMessage::MessageVersion)incoming_version);
            state = MessageSize;
        }

        case MessageSize:
        {
            unsigned int field_size;
            // FIXME: Field size is 64 bit
            BOOL3 result = ParseVarInt32(field_size);
            if (result == NO)
                return OpStatus::ERR_PARSING_FAILED;
            if (result == MAYBE)
                return STPStatus::ERR_NOT_ENOUGH_DATA;
            OP_ASSERT(field_size < (1u << 31));
            protobuf_limit = field_size;
            has_service_field = has_command_field = has_type_field = has_payload_field = FALSE;
            if (message_version == 0)
            {
                // Support for STP/0 message wrapped in a STP/1 message
                // The exception is the size entry for STP/0 which is skipped
                body_size = field_size;
                OP_ASSERT((body_size % 2) == 0);
                stp0_size = body_size / 2;
                state = STP0_Init;
                continue;
            }
            state = STPType;
        }

        case STPType:
        {
            if (incoming->Length() < 1)
                return STPStatus::ERR_NOT_ENOUGH_DATA;
            unsigned int type = incoming->Extract1(0);
            protobuf_limit -= 1;
            incoming->Consume(1);
            if (type == OpScopeTPMessage::STP_Call)
                message.SetTransportType(OpScopeTPMessage::STP_Call);
            else if (type == OpScopeTPMessage::STP_Response)
                message.SetTransportType(OpScopeTPMessage::STP_Response);
            else if (type == OpScopeTPMessage::STP_Event)
                message.SetTransportType(OpScopeTPMessage::STP_Event);
            else if (type == OpScopeTPMessage::STP_Error)
                message.SetTransportType(OpScopeTPMessage::STP_Error);
            else
            {
                state = IgnoreFields;
                continue;
            }
            state = Field;
        }

        case Field:
        {
            if (protobuf_limit == 0) // Did we reach the end of the field data?
            {
                protobuf_limit = -1; // Remove limit
                state = MessageDone;
                continue;
            }

            unsigned int field;
            BOOL3 result = ParseVarInt32(field);
            if (result == NO)
                return OpStatus::ERR_PARSING_FAILED;
            if (result == MAYBE)
                return STPStatus::ERR_NOT_ENOUGH_DATA;
            int type = OpProtobufWireFormat::DecodeFieldType32(field);
            int number = OpProtobufWireFormat::DecodeFieldNumber32(field);
            if (number == OpScopeTPMessage::Field_ServiceName)
            {
                if (type == OpProtobufWireFormat::LengthDelimited)
                    state = Service;
            }
            else if (number == OpScopeTPMessage::Field_CommandID)
            {
                if (type == OpProtobufWireFormat::VarInt)
                    state = Command;
            }
            else if (number == OpScopeTPMessage::Field_Type)
            {
                if (type == OpProtobufWireFormat::VarInt)
                    state = Type;
            }
            else if (number == OpScopeTPMessage::Field_Status)
            {
                if (type == OpProtobufWireFormat::VarInt)
                    state = Status;
            }
            else if (number == OpScopeTPMessage::Field_Tag)
            {
                if (type == OpProtobufWireFormat::VarInt)
                    state = Tag;
            }
            else if (number == OpScopeTPMessage::Field_Payload)
            {
                if (type == OpProtobufWireFormat::LengthDelimited)
                    state = ChunkSize;
                payload.Clear();
            }

            if (state == Field)
            {
                if (type == OpProtobufWireFormat::VarInt)
                    state = IgnoreVarint;
                else if (type == OpProtobufWireFormat::Fixed32)
                    state = IgnoreFixed32;
                else if (type == OpProtobufWireFormat::Fixed64)
                    state = IgnoreFixed64;
                else if (type == OpProtobufWireFormat::LengthDelimited)
                    state = IgnoreLengthDelimited;
                else
                    return OpStatus::ERR_PARSING_FAILED;
            }
            continue;
        }

        case Service:
        {
            BOOL3 result = ParseVarInt32(string_length);
            if (result == NO)
                return OpStatus::ERR_PARSING_FAILED;
            if (result == MAYBE)
                return STPStatus::ERR_NOT_ENOUGH_DATA;
            message.ServiceName().Empty();
            state = ServiceString;
        }

        case ServiceString:
        {
            BOOL3 result = ParseString(message.ServiceName(), string_length);
            if (result == NO)
                return OpStatus::ERR_PARSING_FAILED;
            if (result == MAYBE)
                return STPStatus::ERR_NOT_ENOUGH_DATA;
            has_service_field = TRUE;
            state = Field;
            continue;
        }

        case Command:
        {
            unsigned command_id;
            BOOL3 result = ParseVarInt32(command_id);
            if (result == NO)
                return OpStatus::ERR_PARSING_FAILED;
            if (result == MAYBE)
                return STPStatus::ERR_NOT_ENOUGH_DATA;
            message.SetCommandID(command_id);
            has_command_field = TRUE;
            state = Field;
            continue;
        }

        case Type:
        {
            unsigned int type;
            BOOL3 result = ParseVarInt32(type);
            if (result == NO)
                return OpStatus::ERR_PARSING_FAILED;
            if (result == MAYBE)
                return STPStatus::ERR_NOT_ENOUGH_DATA;
            if (type > OpScopeTPHeader::MessageTypeMax)
                return OpStatus::ERR;
            payload_format = static_cast<OpScopeTPMessage::MessageType>(type);
            has_type_field = TRUE;
            state = Field;
            continue;
        }

        case Status:
        {
            unsigned int status;
            BOOL3 result = ParseVarInt32(status);
            if (result == NO)
                return OpStatus::ERR_PARSING_FAILED;
            if (result == MAYBE)
                return STPStatus::ERR_NOT_ENOUGH_DATA;
            message.SetStatus(static_cast<OpScopeTPMessage::MessageStatus>(status));
            state = Field;
            continue;
        }

        case Tag:
        {
            unsigned int tag;
            BOOL3 result = ParseVarInt32(tag);
            if (result == NO)
                return OpStatus::ERR_PARSING_FAILED;
            if (result == MAYBE)
                return STPStatus::ERR_NOT_ENOUGH_DATA;
            message.SetTag(tag);
            state = Field;
            continue;
        }

        case ChunkSize:
        {
            BOOL3 result = ParseVarInt32(chunk_size);
            if (result == NO)
                return OpStatus::ERR_PARSING_FAILED;
            if (result == MAYBE)
                return STPStatus::ERR_NOT_ENOUGH_DATA;
            if (chunk_size == 0)
            {
                chunk_size = 0;
                state = Field;
                has_payload_field = TRUE;
                continue;
            }
            body_size = chunk_size;
            state = ChunkData;
        }

        case ChunkData:
        {
            if (incoming->Length() < chunk_size)
                return STPStatus::ERR_NOT_ENOUGH_DATA;
            RETURN_IF_ERROR(OpScopeCopy(*incoming, payload, chunk_size));
            incoming->Consume(chunk_size);
            protobuf_limit -= chunk_size;
            chunk_size = 0;
            has_payload_field = TRUE;
            state = Field;
            continue;
        }

        case MessageDone:
        {
            // TODO: Check for missing required fields
            if (!has_service_field || !has_command_field || !has_type_field || !has_payload_field)
            {
                // Missing fields, ignore this message
                // TODO: Should report about bad message to a callback.
                state = Message;
                continue;
            }
            RETURN_IF_ERROR(message.SetData(payload, payload_format));
            OP_ASSERT(message.Type() != OpScopeTPHeader::None);
            OP_ASSERT(message.Data() != NULL);
            PrepareMessage(message);
            OnMessageParsed(message);
            RETURN_IF_ERROR(message.Free());
            state = Message;
            return OpStatus::OK;
        }

        case STP0_Message:
        {
            if (version > 0)
            {
                state = Message;
                continue;
            }
            message.Clear();
            state = STP0_Size;
            message_version = 0;
        }

        case STP0_Size:
        {
            BOOL3 result = ParseSTP0Size(stp0_size);
            if (result == MAYBE)
                return STPStatus::ERR_NOT_ENOUGH_DATA;
            else if (result == NO)
                return STPStatus::ERR_PARSING_FAILED;
            body_size = stp0_size*2;
            state = STP0_Init;
        }

        case STP0_Init:
        {
            OP_DELETEA(stp0_incoming);
            stp0_incoming = OP_NEWA(uni_char, stp0_size);
            RETURN_OOM_IF_NULL(stp0_incoming);
            message.SetVersion(OpScopeTPMessage::Version_0);
            message.SetTransportType(OpScopeTPMessage::STP_Call);
            message.SetServiceName(UNI_L(""));
            message.SetCommandID(0);
            message.SetStatus(OpScopeTPMessage::OK);
            RETURN_IF_ERROR(message.Free());
            message.SetTag(0);
            payload.Clear();
            state = STP0_Data;
        }

        case STP0_Data:
        {
            OP_ASSERT(stp0_incoming != NULL);
            if (incoming->Length() < body_size)
                return STPStatus::ERR_NOT_ENOUGH_DATA;
            incoming->Extract(0, body_size, reinterpret_cast<char *>(stp0_incoming));
            incoming->Consume(body_size);
#ifndef OPERA_BIG_ENDIAN
            OpProtobufUtils::ByteSwap(stp0_incoming, stp0_size);
#endif // OPERA_BIG_ENDIAN

            // Now find the service name and separate it from the data that follows
            const uni_char *stp0_data = NULL;
            for (unsigned int i = 0; i < stp0_size; ++i)
            {
                if (stp0_incoming[i] == ' ')
                {
                    stp0_incoming[i] = '\0';
                    stp0_data = stp0_incoming + i + 1;
                    break;
                }
            }
            OP_STATUS status = OpStatus::OK;
            if (stp0_data != NULL)
            {
                unsigned int data_size = stp0_size - (stp0_data - stp0_incoming);
                RETURN_IF_ERROR(message.SetServiceName(stp0_incoming));

                // Check if it contains an STP/x header, if so decode extra headers.
                if (stp0_incoming[0] != '*' && data_size >= 4 && uni_strncmp(stp0_data, UNI_L("STP/"), 4) == 0)
                {
                    status = ParseExtendedStp0(message, stp0_data, data_size);
                }
                else
                {
                    RETURN_IF_ERROR(payload.AppendBytes(reinterpret_cast<const char *>(stp0_data), data_size*2));

                    // Sniff information
                    if (stp0_incoming[0] == '*')
                        payload_format = OpScopeTPMessage::JSON; // FIXME: The JSON type is just a temporary solution as the Scope type is removed
                    else if (data_size > 0)
                    {
                        if (uni_strncmp(stp0_data, "<?xml", 5) == 0)
                            payload_format = OpScopeTPMessage::XML;
                        else if (stp0_data[0] == '[')
                            payload_format = OpScopeTPMessage::JSON;
                    }
                }
            }
            OP_DELETEA(stp0_incoming);
            stp0_incoming = NULL;

            chunk_size = stp0_size = 0;
            state = version == 0 ? STP0_Message : Message;

            if (stp0_data != NULL && OpStatus::IsSuccess(status))
            {
                RETURN_IF_ERROR(message.SetData(payload, payload_format));
                payload.Clear();
                PrepareMessage(message);
                OnMessageParsed(message);
                RETURN_IF_ERROR(message.Free());
            }

            if (stp0_data == NULL)
                return OpStatus::ERR_PARSING_FAILED;
            return OpStatus::OK;
        }

        case IgnoreVarint:
        {
            unsigned int tmp;
            BOOL3 result = ParseVarInt32(tmp);
            if (result == NO)
                return OpStatus::ERR_PARSING_FAILED;
            if (result == MAYBE)
                return STPStatus::ERR_NOT_ENOUGH_DATA;
            state = Field;
            continue;
        }

        case IgnoreFixed32:
        {
            unsigned int tmp;
            BOOL3 result = ParseFixed32(tmp);
            if (result == NO)
                return OpStatus::ERR_PARSING_FAILED;
            if (result == MAYBE)
                return STPStatus::ERR_NOT_ENOUGH_DATA;
            state = Field;
            continue;
        }

        case IgnoreFixed64:
        {
            UINT64 tmp;
            BOOL3 result = ParseFixed64(tmp);
            if (result == NO)
                return OpStatus::ERR_PARSING_FAILED;
            if (result == MAYBE)
                return STPStatus::ERR_NOT_ENOUGH_DATA;
            state = Field;
            continue;
        }

        case IgnoreLengthDelimited:
        {
            BOOL3 result = ParseVarInt32(ignore_size);
            if (result == NO)
                return OpStatus::ERR_PARSING_FAILED;
            if (result == MAYBE)
                return STPStatus::ERR_NOT_ENOUGH_DATA;
            state = IgnoreLengthDelimitedData;
        }

        case IgnoreLengthDelimitedData:
        {
            if (protobuf_limit >= 0)
            {
                OP_ASSERT(protobuf_limit >= (int)ignore_size);
                if (protobuf_limit < (int)ignore_size) // Cannot skip length-delimited data as it is crosses the limit
                    return OpStatus::ERR_PARSING_FAILED;
            }
            if (incoming->Length() < ignore_size)
                return STPStatus::ERR_NOT_ENOUGH_DATA;
            incoming->Consume(ignore_size);
            if (protobuf_limit > 0)
                protobuf_limit -= ignore_size;
            state = Field;
            continue;
        }

        case IgnoreMessageSize:
        {
            // TODO: Should consume data as they arrive, better for iterative parsing
            unsigned int field_size;
            // FIXME: Field size is 64 bit
            BOOL3 result = ParseVarInt32(field_size);
            if (result == NO)
                return OpStatus::ERR_PARSING_FAILED;
            if (result == MAYBE)
                return STPStatus::ERR_NOT_ENOUGH_DATA;
            OP_ASSERT(field_size < (1u << 31));
            protobuf_limit = field_size;
            state = IgnoreFields;
        }

        case IgnoreFields:
        {
            // TODO: Should consume data as they arrive, better for iterative parsing
            if ((int)incoming->Length() < protobuf_limit)
                return STPStatus::ERR_NOT_ENOUGH_DATA;
            incoming->Consume(protobuf_limit);
            protobuf_limit = -1;
            state = Message;
            continue;
        }

        default:
            OP_ASSERT(!"Invalid parser state");
        }
        break;
    }
    return OpStatus::OK;
}
示例#15
0
/***********************************************************************************
 ** ParseDefaultFile
 **
 **
 **
 ** FOR KDE : ${HOME}/.kde/share/config/profilerc
 ***********************************************************************************/
OP_STATUS ProfilercFile::ParseInternal(OpFile & file)
{
    //-----------------------------------------------------
    // Parameter checking:
    //-----------------------------------------------------
    //File pointer cannot be null
    OP_ASSERT(file.IsOpen());
    if(!file.IsOpen())
		return OpStatus::ERR;
    //-----------------------------------------------------
	
    //Split file into lines - only if smaller than 10MB
    UINT32 max_size = 10000000;
    OpAutoVector<OpString> list;
    FileHandlerManagerUtilities::FileToLineVector(&file, list, max_size);
	
    OpString mime_type;
    OpString desktop_file;
	
    unsigned int priority = 0;
    OP_STATUS status = OpStatus::OK;
	
    for(UINT32 i = 0; i < list.GetCount(); i++)
    {
		OpString* line = list.Get(i);
		line->Strip();
		
		// Seperator line :
		if(line->IsEmpty())
		{
			continue;
		}
		
		if(ParsedMime(*line, mime_type, priority, status))
			continue;
		
		RETURN_IF_ERROR(status);
		
		OpAutoVector<OpString> items;
		FileHandlerManagerUtilities::SplitString(items, *line, '=');
		
		if(items.GetCount() == 2)
		{
			items.Get(0)->Strip();
			items.Get(1)->Strip();
			
			OpString * key   = items.Get(0);
			OpString * value = items.Get(1);
			
			MimeTypeNode* node = FileHandlerManager::GetManager()->MakeMimeTypeNode(mime_type.CStr());
			
			if(uni_strncmp(key->CStr(), UNI_L("Application"), 11) == 0)
			{
				desktop_file.Set(value->CStr());
			}
			else if(uni_strncmp(key->CStr(), UNI_L("GenericServiceType"), 18) == 0)
			{
				if(uni_strncmp(value->CStr(), UNI_L("Application"), 11) == 0)
				{
					FileHandlerManager::GetManager()->InsertIntoApplicationList(node,
																				desktop_file.CStr(),
																				0,
																				0,
																				(priority == 1));
				}
				else
				{
					desktop_file.Empty();
				}
			}
		}
		else
		{
			//Error in reading line - should have two elements
			OP_ASSERT(FALSE);
		}
    }
	
    return OpStatus::OK;
}
示例#16
0
/***********************************************************************************
 ** Parse
 **
 **
 **
 **
 ***********************************************************************************/
OP_STATUS DesktopFile::ParseInternal(OpFile & file)
{
    //-----------------------------------------------------
    // Parameter checking:
    //-----------------------------------------------------
    //File pointer cannot be null
    OP_ASSERT(file.IsOpen());
    if(!file.IsOpen())
	return OpStatus::ERR;

    //Node pointer cannot be null
    OP_ASSERT(m_node);
    if(!m_node)
	return OpStatus::ERR;
    //-----------------------------------------------------

    //Split file into lines - only if smaller than 100k
    // - All desktop files should be less than 100k
    UINT32 max_size = 100000;
    OpAutoVector<OpString> list;
    FileHandlerManagerUtilities::FileToLineVector(&file, list, max_size);

    for(UINT32 i = 1; i < list.GetCount(); i++)
    {
		OpString* line = list.Get(i);
		OpAutoVector<OpString> items;
		FileHandlerManagerUtilities::SplitString(items, *line, '=');
		
		if(items.GetCount() == 2)
		{
			OpString * item_0 = items.Get(0);
			OpString * item_1 = items.Get(1);
			
			if(uni_strncmp(item_0->CStr(), UNI_L("TryExec"), 7) == 0)
			{
				if(m_node->GetType() == APPLICATION_NODE_TYPE)
				{
					ApplicationNode * app_node = (ApplicationNode *) m_node;
					app_node->SetTryExec(item_1->CStr());
				}
			}
			else if(uni_strncmp(item_0->CStr(), UNI_L("Exec"), 4) == 0)
			{
				if(m_node->GetType() == APPLICATION_NODE_TYPE)
				{
					ApplicationNode * app_node = (ApplicationNode *) m_node;
					app_node->SetCommand(item_1->CStr());
				}
			}
			else if(uni_strncmp(item_0->CStr(), UNI_L("Icon"), 4) == 0)
			{
				m_node->SetIcon(item_1->CStr());
			}
			else if(uni_strlen(item_0->CStr()) == 7 && uni_strncmp(item_0->CStr(), UNI_L("Comment"), 7) == 0)
			{
				m_node->SetComment(item_1->CStr());
			}
			else if(uni_strlen(item_0->CStr()) == 4 && uni_strncmp(item_0->CStr(), UNI_L("Name"), 4) == 0)
			{
				m_node->SetName(item_1->CStr());
			}
			else if(uni_strlen(item_0->CStr()) == 8 && uni_strncmp(item_0->CStr(), UNI_L("Terminal"), 8) == 0)
			{
				if(m_node->GetType() == APPLICATION_NODE_TYPE)
				{
					ApplicationNode * app_node = (ApplicationNode *) m_node;
					BOOL in_terminal =
						(uni_strncmp(item_1->CStr(), UNI_L("true"), 4) == 0) ||
						(uni_strncmp(item_1->CStr(), UNI_L("1"), 1) == 0);
					app_node->SetInTerminal(in_terminal);
				}
			}
			else if(uni_strlen(item_0->CStr()) == 17 && uni_strncmp(item_0->CStr(), UNI_L("InitialPreference"), 17) == 0)
			{
				//TODO KDE way to say the preference weight
			}
		}
    }
	
    return OpStatus::OK;
}
示例#17
0
BOOL
XPath_Node::HasStringValueL (const uni_char *value)
{
  unsigned value_length;

  if (!value)
    value = UNI_L (""), value_length = 0;
  else
    value_length = uni_strlen (value);

  XMLTreeAccessor::Node *iter = treenode, *first = 0;
  TempBuffer buffer; ANCHOR (TempBuffer, buffer);
  const uni_char *data = 0;
  BOOL id, specified;

  switch (type)
    {
    case XP_NODE_ROOT:
    case XP_NODE_ELEMENT:
      LEAVE_IF_ERROR (tree->GetCharacterDataContent (data, treenode, &buffer));
      return uni_strcmp (value, data) == 0;

    case XP_NODE_TEXT:
      while (XPath_Utils::GetNodeType (tree, iter) == XP_NODE_TEXT)
        {
          first = iter;

          if (XMLTreeAccessor::Node *previous = tree->GetPreviousSibling (iter))
            iter = previous;
          else
            break;
        }
      while (first && XPath_Utils::GetNodeType (tree, first) == XP_NODE_TEXT)
        {
          LEAVE_IF_ERROR (tree->GetData (data, first, &buffer));
          unsigned data_length = uni_strlen (data);

          if (value_length < data_length || uni_strncmp (value, data, data_length) != 0)
            return FALSE;

          value += data_length;
          value_length -= data_length;

          buffer.Clear ();
          first = tree->GetNextSibling (first);
        }
      return TRUE;

    case XP_NODE_ATTRIBUTE:
      LEAVE_IF_ERROR (tree->GetAttribute (tree->GetAttributes (treenode, FALSE, TRUE), name, data, id, specified, &buffer));
      return uni_strcmp (value, data) == 0;

    case XP_NODE_NAMESPACE:
      {
        const uni_char *uri = name.GetUri ();
        if (uri)
          return uni_strcmp (value, uri) == 0;
        else
          return value_length == 0;
      }

    case XP_NODE_PI:
    case XP_NODE_COMMENT:
      LEAVE_IF_ERROR (tree->GetData (data, iter, &buffer));
      return uni_strcmp (value, data) == 0;
    }

  return FALSE;
}
示例#18
0
/***********************************************************************************
 ** ParseInternal
 **
 **
 **
 ** FOR GNOME : /usr/share/application-registry/gnome-vfs.applications
 ***********************************************************************************/
OP_STATUS GnomeVFSFile::ParseInternal(OpFile & file)
{
    //-----------------------------------------------------
    // Parameter checking:
    //-----------------------------------------------------
    //File pointer cannot be null
    OP_ASSERT(file.IsOpen());
    if(!file.IsOpen())
	return OpStatus::ERR;
    //-----------------------------------------------------

    //Split file into lines - only if smaller than 10MB
    UINT32 max_size = 10000000;
    OpAutoVector<OpString> list;
    FileHandlerManagerUtilities::FileToLineVector(&file, list, max_size);
	
    OpString application;
	
    ApplicationNode * app_node = 0;
	
    for(UINT32 i = 0; i < list.GetCount(); i++)
    {
		OpString* line = list.Get(i);
		
		line->Strip();
		
		// Seperator line :
		if(line->IsEmpty())
		{
			application.Empty();
			app_node = 0;
			continue;
		}
		
		OpAutoVector<OpString> items;
		FileHandlerManagerUtilities::SplitString(items, *line, '=');
		
		if(items.GetCount() == 1)
		{
			items.Get(0)->Strip();
			application.Set(items.Get(0)->CStr());
		}
		else if(items.GetCount() == 2)
		{
			items.Get(0)->Strip();
			items.Get(1)->Strip();
			
			OpString * key   = items.Get(0);
			OpString * value = items.Get(1);

			if(uni_strncmp(key->CStr(), UNI_L("command"), 7) == 0)
			{
				if(value->HasContent())
					app_node = FileHandlerManager::GetManager()->MakeApplicationNode(0, 0, value->CStr(), 0);
			}
			else if(app_node && uni_strncmp(key->CStr(), UNI_L("name"), 4) == 0)
			{
				app_node->SetName(value->CStr());
			}
			else if(app_node && uni_strncmp(key->CStr(), UNI_L("requires_terminal"), 17) == 0)
			{
				if(uni_strncmp(value->CStr(), UNI_L("true"), 4) == 0)
				{
					app_node->SetInTerminal(TRUE);
				}
				else if(uni_strncmp(value->CStr(), UNI_L("false"), 5) == 0)
				{
					app_node->SetInTerminal(FALSE);
				}
			}
			else if(app_node && uni_strncmp(key->CStr(), UNI_L("mime_types"), 10) == 0)
			{
				OpAutoVector<OpString> mime_types;
				FileHandlerManagerUtilities::SplitString(mime_types, *value, ',');
				
				MimeTypeNode * node     = 0;
				
				for(UINT32 j = 0; j < mime_types.GetCount(); j++)
				{
					node = 0;
					
					mime_types.Get(j)->Strip();
					OpString * mime_type = mime_types.Get(j);
					
					if(!mime_type || mime_type->IsEmpty())
						continue;
					
					node = FileHandlerManager::GetManager()->MakeMimeTypeNode(mime_type->CStr());
					
					if(!node)
						continue;
					
					FileHandlerManager::GetManager()->InsertIntoApplicationList(node, app_node, FALSE);
				}
			}
		}
    }

    return OpStatus::OK;
}
示例#19
0
/* virtual */ void
XSLT_Output::AddAttributeL (XSLT_StylesheetParserImpl *parser, XSLT_AttributeType type, const XMLCompleteNameN &name, const uni_char *value, unsigned value_length)
{
  XSLT_OutputMethod method;
  XSLT_OutputSpecificationInternal &output_specification = parser->GetStylesheet ()->GetOutputSpecificationInternal ();

  switch (type)
    {
    case XSLTA_METHOD:
      method = XSLT_OUTPUT_DEFAULT;

      if (value_length == 3 && uni_strncmp (value, "xml", 3) == 0)
        method = XSLT_OUTPUT_XML;
      else if (value_length == 4)
        if (uni_strncmp (value, "html", 4) == 0)
          method = XSLT_OUTPUT_HTML;
        else if (uni_strncmp (value, "text", 4) == 0)
          method = XSLT_OUTPUT_TEXT;

      if (method != XSLT_OUTPUT_DEFAULT)
        parser->GetStylesheet ()->SetOutputMethod (method);
      break;

    case XSLTA_VERSION:
      XSLT_ReplaceSpecificationValueL (output_specification.version, output_specification.owns_version, value, value_length);
      break;

    case XSLTA_ENCODING:
      XSLT_ReplaceSpecificationValueL (output_specification.encoding, output_specification.owns_encoding, value, value_length);
      break;

    case XSLTA_OMIT_XML_DECLARATION:
      if (value_length == 3 && uni_strncmp (value, "yes", 3) == 0)
        output_specification.omit_xml_declaration = TRUE;
      break;

    case XSLTA_STANDALONE:
      if (value_length == 3 && uni_strncmp (value, "yes", 3) == 0)
        output_specification.standalone = XMLSTANDALONE_YES;
      else if (value_length == 2 && uni_strncmp (value, "no", 2) == 0)
        output_specification.standalone = XMLSTANDALONE_NO;
      break;

    case XSLTA_DOCTYPE_PUBLIC:
      XSLT_ReplaceSpecificationValueL (output_specification.doctype_public_id, output_specification.owns_doctype_public_id, value, value_length);
      break;

    case XSLTA_DOCTYPE_SYSTEM:
      XSLT_ReplaceSpecificationValueL (output_specification.doctype_system_id, output_specification.owns_doctype_system_id, value, value_length);
      break;

    case XSLTA_CDATA_SECTION_ELEMENTS:
      parser->AddCDATASectionElementsL (value, value_length);
      break;

    case XSLTA_INDENT:
      if (value_length == 3 && uni_strncmp (value, "yes", 3) == 0)
        output_specification.indent = TRUE;
      break;

    case XSLTA_MEDIA_TYPE:
      XSLT_ReplaceSpecificationValueL (output_specification.media_type, output_specification.owns_media_type, value, value_length);
      break;

#ifdef XSLT_COPY_TO_FILE_SUPPORT
    case XSLTA_COPY_TO_FILE:
      parser->GetStylesheet ()->SetCopyToFileL (value, value_length);
      break;
#endif // XSLT_COPY_TO_FILE_SUPPORT

    case XSLTA_OTHER:
    case XSLTA_NO_MORE_ATTRIBUTES:
      break;

    default:
      XSLT_Element::AddAttributeL (parser, type, name, value, value_length);
    }
}
示例#20
0
/* virtual */ XMLTokenHandler::Result
XMLToLanguageParserTokenHandler::HandleToken(XMLToken &token)
{
	OP_STATUS status = OpStatus::OK;
	OpStatus::Ignore(status);

	if (finished)
		return RESULT_OK;

	if (ignore_element_depth != 0)
	{
		if (token.GetType() == XMLToken::TYPE_STag)
			++ignore_element_depth;
		else if (token.GetType() == XMLToken::TYPE_ETag)
			--ignore_element_depth;
	}

	XMLParserImpl *xmlparser = (XMLParserImpl *) token.GetParser();
	BOOL block = FALSE;

	if (ignore_element_depth == 0)
	{
#ifdef XML_ERRORS
		XMLRange location;
#endif // XML_ERRORS

		switch (token.GetType())
		{
		case XMLToken::TYPE_PI:
#ifdef XML_ERRORS
			token.GetTokenRange(location);
			parser->SetLocation(location);
#endif // XML_ERRORS

			status = parser->AddProcessingInstruction(token.GetName().GetLocalPart(), token.GetName().GetLocalPartLength(), token.GetData(), token.GetDataLength());
			break;

		case XMLToken::TYPE_CDATA:
		case XMLToken::TYPE_Text:
		case XMLToken::TYPE_Comment:
		{
			XMLLanguageParser::CharacterDataType cdatatype = XMLLanguageParser::CHARACTERDATA_TEXT;
			if (token.GetType() != XMLToken::TYPE_Comment)
				if (token.GetType() == XMLToken::TYPE_CDATA)
					cdatatype = XMLLanguageParser::CHARACTERDATA_CDATA_SECTION;
				else if (token.GetLiteralIsWhitespace())
				{
					if (!entity_signalled)
						/* Don't generate calls to the language parser before the
						   first call to StartEntity. */
						break;
					cdatatype = XMLLanguageParser::CHARACTERDATA_TEXT_WHITESPACE;
				}

			const uni_char *simplevalue;
			uni_char *allocatedvalue;

			if ((simplevalue = token.GetLiteralSimpleValue()) == 0)
			{
				simplevalue = allocatedvalue = token.GetLiteralAllocatedValue();
				if (!allocatedvalue)
					status = OpStatus::ERR_NO_MEMORY;
			}
			else
				allocatedvalue = 0;

			if (simplevalue)
			{
#ifdef XML_ERRORS
				token.GetTokenRange(location);
				parser->SetLocation(location);
#endif // XML_ERRORS

				if (token.GetType() == XMLToken::TYPE_Comment)
					status = parser->AddComment(simplevalue, token.GetLiteralLength());
				else
					status = parser->AddCharacterData(cdatatype, simplevalue, token.GetLiteralLength());

				OP_DELETEA(allocatedvalue);
			}
			break;
		}
		case XMLToken::TYPE_STag:
		case XMLToken::TYPE_ETag:
		case XMLToken::TYPE_EmptyElemTag:
			if (!(xmlparser->GetCurrentEntityUrl() == current_entity_url) && xmlparser->GetCurrentEntityDepth() <= current_entity_depth)
				status = parser->EndEntity();

			if (OpStatus::IsSuccess(status) && (!(xmlparser->GetCurrentEntityUrl() == current_entity_url) || current_entity_url.IsEmpty() && !entity_signalled) && xmlparser->GetCurrentEntityDepth() > current_entity_depth)
			{
				status = parser->StartEntity(xmlparser->GetCurrentEntityUrl(), xmlparser->GetDocumentInformation(), xmlparser->GetCurrentEntityDepth() > 1);
				entity_signalled = TRUE;
			}

			current_entity_url = xmlparser->GetCurrentEntityUrl();
			current_entity_depth = xmlparser->GetCurrentEntityDepth();

			if (token.GetType() != XMLToken::TYPE_ETag)
			{
				if (OpStatus::IsSuccess(status))
				{
					BOOL fragment_start = FALSE;

					if (!fragment_found)
					{
						if (!fragment_id)
							fragment_start = TRUE;
						else
						{
							XMLToken::Attribute *attributes = token.GetAttributes();
							unsigned attributes_count = token.GetAttributesCount();
							unsigned fragment_id_length = uni_strlen(fragment_id);

							for (unsigned index = 0; index < attributes_count; ++index)
								if (attributes[index].GetId())
									if (attributes[index].GetValueLength() == fragment_id_length && uni_strncmp(attributes[index].GetValue(), fragment_id, fragment_id_length) == 0)
									{
										fragment_start = TRUE;
										break;
									}
						}

						if (fragment_start)
							fragment_found = TRUE;
					}

#ifdef XML_ERRORS
					token.GetTokenRange(location);
					parser->SetLocation(location);
#endif // XML_ERRORS

					BOOL ignore_element = FALSE;
					status = parser->StartElement(token.GetName(), fragment_start, ignore_element);

					if (ignore_element)
					{
						if (token.GetType() == XMLToken::TYPE_STag)
							ignore_element_depth = 1;
					}
					else
					{
						XMLToken::Attribute *attributes = token.GetAttributes();
						unsigned attributes_count = token.GetAttributesCount();

						for (unsigned index = 0; OpStatus::IsSuccess(status) && index < attributes_count; ++index)
						{
#ifdef XML_ERRORS
							token.GetAttributeRange(location, index);
							parser->SetLocation(location);
#endif // XML_ERRORS

							XMLToken::Attribute &attribute = attributes[index];
							status = parser->AddAttribute(attribute.GetName(), attribute.GetValue(), attribute.GetValueLength(), attribute.GetSpecified(), attribute.GetId());
						}

						if (OpStatus::IsSuccess(status))
							status = parser->StartContent();
					}
				}
			}

			if (OpStatus::IsSuccess(status) && token.GetType() != XMLToken::TYPE_STag)
			{
#ifdef XML_ERRORS
				token.GetTokenRange(location);
				parser->SetLocation(location);
#endif // XML_ERRORS

				status = parser->EndElement(block, finished);

				if (OpStatus::IsSuccess(status) && block)
					parser->SetSourceCallback(&sourcecallbackimpl);
			}
			break;

		case XMLToken::TYPE_Finished:
			status = parser->EndEntity();
		}
	}

	if (OpStatus::IsSuccess(status))
		if (block)
			return RESULT_BLOCK;
		else
			return RESULT_OK;
	else if (OpStatus::IsMemoryError(status))
		return RESULT_OOM;
	else
		return RESULT_ERROR;
}
示例#21
0
OP_STATUS OpFolderListing::GenerateData()
{
#ifdef _LOCALHOST_SUPPORT_
	// Prefix for local files
# ifdef HAS_COMPLEX_GLOBALS
	static const uni_char * const localhost_prefix =
		UNI_L("file://localhost/");
# else
#  define localhost_prefix UNI_L("file://localhost/")
# endif
	static const size_t localhost_prefix_len = 17;
	OP_ASSERT(uni_strlen(localhost_prefix) == localhost_prefix_len);
#endif

	const uni_char * OP_MEMORY_VAR dirend_char = UNI_L("");
#if PATHSEPCHAR != '/'
	const uni_char * OP_MEMORY_VAR displayable_dirend_char = dirend_char;
#else
# define displayable_dirend_char dirend_char
#endif

	// FIXME: OOM - not reported, not checked

	// Set attributes.
	m_url.SetAttribute(URL::KIsDirectoryListing, TRUE);

	// Get the URL and take copies of it for processing.
	OpString base;
	RETURN_IF_ERROR(m_url.GetAttribute(URL::KUniName_Username_Escaped, base));
	m_temp_base = SetNewStr(base.CStr());
	m_displayable_base_url = SetNewStr(base.CStr());
	if (!m_temp_base || !m_displayable_base_url)
	{
		return OpStatus::ERR_NO_MEMORY;
	}

	// Check if this is a local file or not.
#ifdef _LOCALHOST_SUPPORT_
	OP_MEMORY_VAR bool is_local_file = false;
#else
	static const bool is_local_file = false;
#endif
#ifdef _LOCALHOST_SUPPORT_
	if (uni_strncmp(m_displayable_base_url, localhost_prefix, localhost_prefix_len) == 0)
	{
		is_local_file = true;
	}
#endif

	static const uni_char pathsepchar = '/';

	//  If wildchars, remove upto last PATHSEPCHAR/
	unsigned int PathLen = uni_strcspn(m_temp_base, UNI_L(WILDCHARS));
	if (PathLen != uni_strlen(m_temp_base))
	{
		int i;
		for (i = PathLen; i > 0 && m_temp_base[i] != PATHSEPCHAR && m_temp_base[i] != '/' && m_temp_base[i] != '\\' ; i--) {}
		m_temp_base[i] = '\0';
	}

	PathLen = uni_strcspn(m_temp_base,UNI_L("?"));
	m_temp_base[PathLen] = '\0';
	{
		// Ignore parameter portion, but only for the last element to ensure
		// proper path names for FTP and file (anyone using parameters in the
		// parent directories will just have to take their chances).
		uni_char *temp_path = uni_strrchr(m_temp_base, '/'); // don't bother looking for backslash
		if(temp_path)
		{
			uni_char *temp_param = uni_strchr(temp_path, ';');
			if(temp_param)
			{
				PathLen = temp_param - m_temp_base;
				m_temp_base[PathLen] = '\0';
			}
		}
	}

	// If the path does not end in a path separator, add one.
	if (m_temp_base[PathLen-1] != '/'
#if PATHSEPCHAR != '/'
		&& m_temp_base[PathLen-1] != PATHSEPCHAR
#endif
	   )
	{
		dirend_char = UNI_L("/");
#if PATHSEPCHAR != '/'
		if (is_local_file)
		{
			displayable_dirend_char = UNI_L(PATHSEP);
		}
		else
		{
			displayable_dirend_char = dirend_char;
		}
#endif
	}

	// Create a HTML version of the URL string.
	m_htmlified_url = HTMLify_string(m_temp_base);
	if (!m_htmlified_url)
	{
		return OpStatus::ERR_NO_MEMORY;
	}

	// Transmogrify the URL to make it displayable.
	UriUnescape::ReplaceChars(m_displayable_base_url,
		(static_cast<URLType>(m_url.GetAttribute(URL::KType)) == URL_FILE ?
		 UriUnescape::LocalfileUrlUtf8 : UriUnescape::SafeUtf8));

	// Remove localhost prefix
	if (is_local_file)
		op_memmove(m_displayable_base_url, m_displayable_base_url + localhost_prefix_len, UNICODE_SIZE(uni_strlen(m_displayable_base_url + localhost_prefix_len) + 1));

#ifdef SYS_CAP_FILESYSTEM_HAS_DRIVES
	// Clean up the generated path string
	if (is_local_file)
	{
		// Replace Netscape-compatible "|" as drive letter postfix with
		// a drive separator, which we assume to be ":"
		if (m_displayable_base_url[0] &&
		    '|' == m_displayable_base_url[1])
		{
			m_displayable_base_url[1] = ':';
		}

		// Make sure drive letter is upper-cased
		if (Unicode::IsLower(m_displayable_base_url[0]))
		{
			m_displayable_base_url[0] = Unicode::ToUpper(m_displayable_base_url[0]);
		}
	}
#endif

	// Remove formatting characters
	RemoveFormattingCharacters(m_displayable_base_url);

	// Create a HTML version of the displayable URL string.
	m_htmlified_displayable_base_url = HTMLify_string(m_displayable_base_url);
	if (!m_htmlified_displayable_base_url)
	{
		return OpStatus::ERR_NO_MEMORY;
	}

	// Set up the document title from the displayable URL string.
	OpString document_title;
#ifndef SYS_CAP_FILESYSTEM_HAS_DRIVES
	if (is_local_file)
	{
		// Include an initial slash for local files on file systems that do
		// not have drive letters, to avoid blank titles or titles like
		// "usr/bin".
		if (uni_strcmp(m_htmlified_displayable_base_url, localhost_prefix) == 0)
		{
			RETURN_IF_ERROR(document_title.Set("/"));
		}
		else
		{
			RETURN_IF_ERROR(document_title.SetConcat(UNI_L("/"), m_htmlified_displayable_base_url));
		}
	}
	else
#endif
	{
		RETURN_IF_ERROR(document_title.Set(m_htmlified_displayable_base_url));
	}


	// Write the document.
#ifdef _LOCALHOST_SUPPORT_
	OpString dirstyle;
	TRAP_AND_RETURN(rc, g_pcfiles->GetFileURLL(PrefsCollectionFiles::StyleDirFile, &dirstyle));
	RETURN_IF_ERROR(OpenDocument(document_title.CStr(), dirstyle.CStr()));
#else
	RETURN_IF_ERROR(OpenDocument(document_title.CStr(), NULL));
#endif

	m_url.WriteDocumentDataUniSprintf(UNI_L(" <base href=\"%s%s\">\n"), m_htmlified_url, dirend_char);

	RETURN_IF_ERROR(OpenBody(Str::S_FOLDER_LISTING_TEXT));

	RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, UNI_L("<h2>")));

	// Provide links to each parent directory in the hierarchy.
	size_t len_htmlified = uni_strlen(m_htmlified_url);
	size_t len_displayable = uni_strlen(m_htmlified_displayable_base_url);
	size_t idx_htmlified = 0, idx_displayable = 0;
	uni_char *protocolsuffix = NULL;
	if (NULL != (protocolsuffix = uni_strstr(m_htmlified_url, UNI_L("://"))))
	{
		uni_char *thirdslash = uni_strchr(protocolsuffix + 3, '/');
		if (thirdslash)
		{
			idx_htmlified = thirdslash - m_htmlified_url + 1;
			if(!is_local_file)
			{
				m_url.WriteDocumentDataUniSprintf(UNI_L("<a href=\"%.*s\">%.*s</a>"), idx_htmlified, m_htmlified_url, idx_htmlified, m_htmlified_url);
			}
		}
		else
		{
			idx_htmlified = static_cast<size_t>(-1);
		}
	}
	else
	{
		idx_htmlified = static_cast<size_t>(-1);
	}
	if (NULL != (protocolsuffix = uni_strstr(m_htmlified_displayable_base_url, UNI_L("://"))))
	{
		uni_char *thirdslash = uni_strchr(protocolsuffix + 3, '/');
		if (thirdslash)
		{
			idx_displayable = thirdslash - m_htmlified_displayable_base_url + 1;
		}
	}

	if (static_cast<size_t>(-1) == idx_htmlified)
	{
		m_url.WriteDocumentDataUniSprintf(UNI_L("%s%s</h2>\n\n"),
										  m_htmlified_url, displayable_dirend_char);
	}
	else
	{
#ifndef SYS_CAP_FILESYSTEM_HAS_DRIVES
		if (is_local_file)
		{
			// Add the initial slash manually, as it does not have a
			// left-hand-side component.
			m_url.WriteDocumentDataUniSprintf(UNI_L("<a href=\"%s\">/</a>"), localhost_prefix);
		}
#endif
		while (idx_htmlified < len_htmlified && idx_displayable < len_displayable)
		{
			uni_char *nextslash_htmlified = uni_strchr(m_htmlified_url + idx_htmlified, '/');
			if (!nextslash_htmlified)
			{
				nextslash_htmlified = m_htmlified_url + len_htmlified;
			}
			uni_char *nextslash_displayable =
				uni_strchr(m_htmlified_displayable_base_url + idx_displayable, pathsepchar);
			if (!nextslash_displayable)
			{
				nextslash_displayable = m_htmlified_displayable_base_url + len_displayable;
			}
			int temp_idx_htmlified = nextslash_htmlified - m_htmlified_url;
			int temp_idx_displayable = nextslash_displayable - m_htmlified_displayable_base_url;

			m_url.WriteDocumentDataUniSprintf(UNI_L("<a href=\"%.*s/\">%.*s</a>/"),
											 temp_idx_htmlified, m_htmlified_url,
											 temp_idx_displayable - idx_displayable, &m_htmlified_displayable_base_url[idx_displayable]);

			idx_htmlified = temp_idx_htmlified + 1;
			idx_displayable = temp_idx_displayable + 1;
		}
		m_url.WriteDocumentData(URL::KNormal, UNI_L("</h2>\n\n"));
	}

	// Clean up.
	delete[] m_temp_base; m_temp_base = NULL;
	delete[] m_htmlified_url; m_htmlified_url = NULL;
	delete[] m_displayable_base_url; m_displayable_base_url = NULL;
	delete[] m_htmlified_displayable_base_url; m_htmlified_displayable_base_url = NULL;

	return OpStatus::OK;
}