Example #1
0
static bool makeAllDirectories(IFileMgr* fileManager, const String& path)
{
    if (path == canonicalPath(AEEFS_HOME_DIR))
        return true;

    int lastDivPos = path.reverseFind('/');
    int endPos = path.length();
    if (lastDivPos == path.length() - 1) {
        endPos -= 1;
        lastDivPos = path.reverseFind('/', lastDivPos);
    }

    if (lastDivPos > 0) {
        if (!makeAllDirectories(fileManager, path.substring(0, lastDivPos)))
            return false;
    }

    String folder(path.substring(0, endPos));

    // IFILEMGR_MkDir return SUCCESS when the file is successfully created or if file already exists.
    // So we need to check fileinfo.attrib.
    IFILEMGR_MkDir(fileManager, folder.utf8().data());

    FileInfo fileInfo;
    if (IFILEMGR_GetInfo(fileManager, folder.utf8().data(), &fileInfo) != SUCCESS)
        return false;

    return fileInfo.attrib & _FA_DIR;
}
Example #2
0
static CString pathSuitableForTestResult(const char* uriString)
{
    if (!uriString)
        return CString();

    KURL uri = KURL(ParsedURLString, uriString);

    if (!uri.isLocalFile())
        return uri.string().utf8();

    String pathString = uri.path();
    size_t indexBaseName = pathString.reverseFind('/');
    String baseName;
    if (indexBaseName == notFound)
        baseName = pathString;
    else
        baseName = pathString.substring(indexBaseName + 1);

    String dirName;
    if (indexBaseName != notFound) {
        size_t indexDirName = pathString.reverseFind('/', indexBaseName - 1);
        if (indexDirName != notFound)
            dirName = pathString.substring(indexDirName + 1, indexBaseName - indexDirName - 1);
    }

    String ret = dirName + "/" + baseName;
    return ret.utf8();
}
Example #3
0
static size_t reverseFindPathSeparator(const String& path, unsigned start = UINT_MAX)
{
    size_t positionSlash = path.reverseFind('/', start);
    size_t positionBackslash = path.reverseFind('\\', start);

    if (positionSlash == notFound)
        return positionBackslash;

    if (positionBackslash == notFound)
        return positionSlash;

    return std::max(positionSlash, positionBackslash);
}
Example #4
0
void ResourceHandle::fileLoadTimer(Timer<ResourceHandle>*)
{
    RefPtr<ResourceHandle> protector(this);
    deref(); // balances ref in start

    if (firstRequest().url().protocolIsData()) {
        handleDataURL(this);
        return;
    }

    String fileName = firstRequest().url().fileSystemPath();
    HANDLE fileHandle = CreateFileW(fileName.charactersWithNullTermination(), GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

    if (fileHandle == INVALID_HANDLE_VALUE) {
        client()->didFail(this, ResourceError());
        return;
    }

    ResourceResponse response;

    int dotPos = fileName.reverseFind('.');
    int slashPos = fileName.reverseFind('/');

    if (slashPos < dotPos && dotPos != -1) {
        String ext = fileName.substring(dotPos + 1);
        response.setMimeType(MIMETypeRegistry::getMIMETypeForExtension(ext));
    }

    client()->didReceiveResponse(this, response);

    bool result = false;
    DWORD bytesRead = 0;

    do {
        const int bufferSize = 8192;
        char buffer[bufferSize];
        result = ReadFile(fileHandle, &buffer, bufferSize, &bytesRead, 0);
        // FIXME: https://bugs.webkit.org/show_bug.cgi?id=19793
        // -1 means we do not provide any data about transfer size to inspector so it would use
        // Content-Length headers or content size to show transfer size.
        if (result && bytesRead)
            client()->didReceiveData(this, buffer, bytesRead, -1);
        // Check for end of file.
    } while (result && bytesRead);

    CloseHandle(fileHandle);

    client()->didFinishLoading(this, 0);
}
Example #5
0
Value FunLang::evaluate() const
{
    String lang = arg(0)->evaluate().toString();

    Attribute* languageAttribute = 0;
    Node* node = evaluationContext().node.get();
    while (node) {
        NamedNodeMap* attrs = node->attributes();
        if (attrs)
            languageAttribute = attrs->getAttributeItem(XMLNames::langAttr);
        if (languageAttribute)
            break;
        node = node->parentNode();
    }

    if (!languageAttribute)
        return false;

    String langValue = languageAttribute->value();
    while (true) {
        if (equalIgnoringCase(langValue, lang))
            return true;

        // Remove suffixes one by one.
        int index = langValue.reverseFind('-');
        if (index == -1)
            break;
        langValue = langValue.left(index);
    }

    return false;
}
Example #6
0
bool MediaPlayer::load(const KURL& url, const ContentType& contentType)
{
    String type = contentType.type().lower();
    String typeCodecs = contentType.parameter(codecs());
    String urlString = url.string();

    // If the MIME type is missing or is not meaningful, try to figure it out from the URL.
    if (type.isEmpty() || type == applicationOctetStream() || type == textPlain()) {
        if (protocolIs(urlString, "data"))
            type = mimeTypeFromDataURL(urlString);
        else {
            String lastPathComponent = url.lastPathComponent();
            size_t pos = lastPathComponent.reverseFind('.');
            if (pos != notFound) {
                String extension = lastPathComponent.substring(pos + 1);
                String mediaType = MIMETypeRegistry::getMediaMIMETypeForExtension(extension);
                if (!mediaType.isEmpty())
                    type = mediaType;
            }
        }
    }

    m_url = urlString;
    m_contentMIMEType = type;
    m_contentTypeCodecs = typeCodecs;
    loadWithNextMediaEngine(0);
    return m_currentMediaEngine;
}
PassRefPtr<SecurityOrigin> SecurityOrigin::maybeCreateFromDatabaseIdentifier(const String& databaseIdentifier)
{ 
    // Make sure there's a first separator
    size_t separator1 = databaseIdentifier.find(separatorCharacter);
    if (separator1 == notFound)
        return nullptr;
        
    // Make sure there's a second separator
    size_t separator2 = databaseIdentifier.reverseFind(separatorCharacter);
    if (separator2 == notFound)
        return nullptr;

    // Ensure there were at least 2 separator characters. Some hostnames on intranets have
    // underscores in them, so we'll assume that any additional underscores are part of the host.
    if (separator1 == separator2)
        return nullptr;

    // Make sure the port section is a valid port number or doesn't exist
    bool portOkay;
    int port = databaseIdentifier.right(databaseIdentifier.length() - separator2 - 1).toInt(&portOkay);
    bool portAbsent = (separator2 == databaseIdentifier.length() - 1);
    if (!(portOkay || portAbsent))
        return nullptr;

    if (port < 0 || port > MaxAllowedPort)
        return nullptr;

    // Split out the 3 sections of data
    String protocol = databaseIdentifier.substring(0, separator1);
    String host = databaseIdentifier.substring(separator1 + 1, separator2 - separator1 - 1);
    
    host = decodeURLEscapeSequences(host);
    return create(URL(URL(), protocol + "://" + host + ":" + String::number(port) + "/"));
}
Example #8
0
PassRefPtr<SecurityOrigin> SecurityOrigin::createFromDatabaseIdentifier(const String& databaseIdentifier)
{ 
    // Make sure there's a first separator
    int separator1 = databaseIdentifier.find(SeparatorCharacter);
    if (separator1 == -1)
        return create(KURL());
        
    // Make sure there's a second separator
    int separator2 = databaseIdentifier.find(SeparatorCharacter, separator1 + 1);
    if (separator2 == -1)
        return create(KURL());
        
    // Make sure there's not a third separator
    if (databaseIdentifier.reverseFind(SeparatorCharacter) != separator2)
        return create(KURL());
        
    // Make sure the port section is a valid port number or doesn't exist
    bool portOkay;
    int port = databaseIdentifier.right(databaseIdentifier.length() - separator2 - 1).toInt(&portOkay);
    if (!portOkay && separator2 + 1 == static_cast<int>(databaseIdentifier.length()))
        return create(KURL());
    
    if (port < 0 || port > 65535)
        return create(KURL());
        
    // Split out the 3 sections of data
    String protocol = databaseIdentifier.substring(0, separator1);
    String host = databaseIdentifier.substring(separator1 + 1, separator2 - separator1 - 1);
    return create(KURL(KURL(), protocol + "://" + host + ":" + String::number(port)));
}
Example #9
0
static String notAFunctionSourceAppender(const String& originalMessage, const String& sourceText, RuntimeType type, ErrorInstance::SourceTextWhereErrorOccurred occurrence)
{
    ASSERT(type != TypeFunction);

    if (occurrence == ErrorInstance::FoundApproximateSource)
        return defaultApproximateSourceError(originalMessage, sourceText);

    ASSERT(occurrence == ErrorInstance::FoundExactSource);
    auto notAFunctionIndex = originalMessage.reverseFind("is not a function");
    RELEASE_ASSERT(notAFunctionIndex != notFound);
    StringView displayValue;
    if (originalMessage.is8Bit()) 
        displayValue = StringView(originalMessage.characters8(), notAFunctionIndex - 1);
    else
        displayValue = StringView(originalMessage.characters16(), notAFunctionIndex - 1);

    String base = functionCallBase(sourceText);
    StringBuilder builder;
    builder.append(base);
    builder.appendLiteral(" is not a function. (In '");
    builder.append(sourceText);
    builder.appendLiteral("', '");
    builder.append(base);
    builder.appendLiteral("' is ");
    if (type == TypeObject)
        builder.appendLiteral("an instance of ");
    builder.append(displayValue);
    builder.appendLiteral(")");

    return builder.toString();
}
Example #10
0
bool MediaPlayer::load(const URL& url, const ContentType& contentType, const String& keySystem)
{
    m_contentMIMEType = contentType.type().lower();
    m_contentTypeCodecs = contentType.parameter(codecs());
    m_url = url;
    m_keySystem = keySystem.lower();
    m_contentMIMETypeWasInferredFromExtension = false;

#if ENABLE(MEDIA_SOURCE)
    m_mediaSource = 0;
#endif

    // If the MIME type is missing or is not meaningful, try to figure it out from the URL.
    if (m_contentMIMEType.isEmpty() || m_contentMIMEType == applicationOctetStream() || m_contentMIMEType == textPlain()) {
        if (m_url.protocolIsData())
            m_contentMIMEType = mimeTypeFromDataURL(m_url.string());
        else {
            String lastPathComponent = url.lastPathComponent();
            size_t pos = lastPathComponent.reverseFind('.');
            if (pos != notFound) {
                String extension = lastPathComponent.substring(pos + 1);
                String mediaType = MIMETypeRegistry::getMediaMIMETypeForExtension(extension);
                if (!mediaType.isEmpty()) {
                    m_contentMIMEType = mediaType;
                    m_contentMIMETypeWasInferredFromExtension = true;
                }
            }
        }
    }

    loadWithNextMediaEngine(0);
    return m_currentMediaEngine;
}
Example #11
0
static String findPluginMIMETypeFromURL(Page* page, const String& url)
{
    if (!url)
        return String();

    size_t dotIndex = url.reverseFind('.');
    if (dotIndex == notFound)
        return String();

    String extension = url.substring(dotIndex + 1);

    const PluginData& pluginData = page->pluginData();

    Vector<MimeClassInfo> mimes;
    Vector<size_t> mimePluginIndices;
    pluginData.getWebVisibleMimesAndPluginIndices(mimes, mimePluginIndices);
    for (auto& mime : mimes) {
        for (auto& mimeExtension : mime.extensions) {
            if (equalIgnoringASCIICase(extension, mimeExtension))
                return mime.type;
        }
    }

    return String();
}
String mimeTypeFromURL(const KURL& url)
{
    String decodedPath = decodeURLEscapeSequences(url.path());
    String extension = decodedPath.substring(decodedPath.reverseFind('.') + 1);

    // We don't use MIMETypeRegistry::getMIMETypeForPath() because it returns "application/octet-stream" upon failure
    return MIMETypeRegistry::getMIMETypeForExtension(extension);
}
Example #13
0
bool makeAllDirectories(const String& path)
{
    int lastDivPos = max(path.reverseFind('/'), path.reverseFind('\\'));
    int endPos = path.length();
    if (lastDivPos == path.length() - 1) {
        endPos -= 1;
        lastDivPos = max(path.reverseFind('/', lastDivPos), path.reverseFind('\\', lastDivPos));
    }

    if (lastDivPos > 0) {
        if (!makeAllDirectories(path.substring(0, lastDivPos)))
            return false;
    }

    String folder(path.substring(0, endPos));
    CreateDirectory(folder.charactersWithNullTermination(), 0);

    DWORD fileAttr = GetFileAttributes(folder.charactersWithNullTermination());
    return fileAttr != 0xFFFFFFFF && (fileAttr & FILE_ATTRIBUTE_DIRECTORY);
}
Example #14
0
void NetworkJob::handleNotifyDataReceived(const char* buf, size_t len)
{
    // Check for messages out of order or after cancel.
    if ((!m_isFile && !m_statusReceived) || m_cancelled)
        return;

    if (!buf || !len) {
        sendResponseIfNeeded();
        if (isClientAvailable())
            m_handle->client()->didReceiveData(m_handle.get(), 0, 0, 0);
        return;
    }
    // The loadFile API sets the override content type,
    // this will always be used as the content type and should not be overridden.
    if (!m_dataReceived && !m_isOverrideContentType) {
        bool shouldSniff = true;

        // Don't bother sniffing the content type of a file that
        // is on a file system if it has a MIME mappable file extension.
        // The file extension is likely to be correct.
        if (m_isFile) {
            String urlFilename = m_response.url().lastPathComponent();
            size_t pos = urlFilename.reverseFind('.');
            if (pos != notFound) {
                String extension = urlFilename.substring(pos + 1);
                String mimeType = MIMETypeRegistry::getMIMETypeForExtension(extension);
                if (!mimeType.isEmpty())
                    shouldSniff = false;
            }
        }

        if (shouldSniff) {
            MIMESniffer sniffer = MIMESniffer(m_contentType.latin1().data(), MIMETypeRegistry::isSupportedImageResourceMIMEType(m_contentType));
            if (const char* type = sniffer.sniff(buf, std::min(len, sniffer.dataSize())))
                m_sniffedMimeType = String(type);
        }
    }

    m_dataReceived = true;

    // Protect against reentrancy.
    updateDeferLoadingCount(1);

    if (shouldSendClientData()) {
        sendResponseIfNeeded();
        sendMultipartResponseIfNeeded();
        if (isClientAvailable()) {
            RecursionGuard guard(m_callingClient);
            m_handle->client()->didReceiveData(m_handle.get(), buf, len, len);
        }
    }

    updateDeferLoadingCount(-1);
}
Example #15
0
String MIMETypeRegistry::getMIMETypeForPath(const String& path)
{
    int pos = path.reverseFind('.');
    if (pos >= 0) {
        String extension = path.substring(pos + 1);
        String result = getMIMETypeForExtension(extension);
        if (result.length())
            return result;
    }
    return "application/octet-stream";
}
Example #16
0
String SVGURIReference::getTarget(const String& url)
{
    if (url.startsWith("url(")) { // URI References, ie. fill:url(#target)
        size_t start = url.find('#') + 1;
        size_t end = url.reverseFind(')');
        return url.substring(start, end - start);
    } else if (url.find('#') != notFound) { // format is #target
        size_t start = url.find('#') + 1;
        return url.substring(start, url.length() - start);
    } else // The url doesn't have any target.
        return String();
}
Example #17
0
static inline String pathExtension(const KURL& url)
{
    String extension;
    String filename = url.lastPathComponent();
    if (!filename.endsWith("/")) {
        int extensionPos = filename.reverseFind('.');
        if (extensionPos != -1)
            extension = filename.substring(extensionPos + 1);
    }
    
    return extension;
}
Example #18
0
String SVGURIReference::getTarget(const String& url)
{
    if (url.startsWith("url(")) { // URI References, ie. fill:url(#target)
        unsigned int start = url.find('#') + 1;
        unsigned int end = url.reverseFind(')');

        return url.substring(start, end - start);
    } else if (url.find('#') > -1) { // format is #target
        unsigned int start = url.find('#') + 1;
        return url.substring(start, url.length() - start);
    } else // Normal Reference, ie. style="color-profile:changeColor"
        return url;
}
Example #19
0
static String invalidParameterInstanceofSourceAppender(const String& originalMessage, const String& sourceText, RuntimeType, ErrorInstance::SourceTextWhereErrorOccurred occurrence)
{
    if (occurrence == ErrorInstance::FoundApproximateSource)
        return defaultApproximateSourceError(originalMessage, sourceText);

    ASSERT(occurrence == ErrorInstance::FoundExactSource);
    auto instanceofIndex = sourceText.reverseFind("instanceof");
    RELEASE_ASSERT(instanceofIndex != notFound);
    if (sourceText.find("instanceof") != instanceofIndex)
        return makeString(originalMessage, " (evaluating '", sourceText, "')");

    static const unsigned instanceofLength = 10;
    String rightHandSide = sourceText.substring(instanceofIndex + instanceofLength).simplifyWhiteSpace();
    return makeString(rightHandSide, " is not a function. (evaluating '", sourceText, "')");
}
Example #20
0
String LocaleWin::shortTimeFormat()
{
    if (!m_timeFormatWithoutSeconds.isNull())
        return m_timeFormatWithoutSeconds;
    String format = getLocaleInfoString(LOCALE_SSHORTTIME);
    // Vista or older Windows doesn't support LOCALE_SSHORTTIME.
    if (format.isEmpty()) {
        format = getLocaleInfoString(LOCALE_STIMEFORMAT);
        StringBuilder builder;
        builder.append(getLocaleInfoString(LOCALE_STIME));
        builder.append("ss");
        size_t pos = format.reverseFind(builder.toString());
        if (pos != notFound)
            format.remove(pos, builder.length());
    }
    m_timeFormatWithoutSeconds = convertWindowsDateTimeFormat(format);
    return m_timeFormatWithoutSeconds;
}
PassRefPtr<SecurityOrigin> createSecurityOriginFromDatabaseIdentifier(const String& databaseIdentifier)
{
    if (!databaseIdentifier.containsOnlyASCII())
        return SecurityOrigin::createUnique();

    // Make sure there's a first separator
    size_t separator1 = databaseIdentifier.find(separatorCharacter);
    if (separator1 == notFound)
        return SecurityOrigin::createUnique();

    // Make sure there's a second separator
    size_t separator2 = databaseIdentifier.reverseFind(separatorCharacter);
    if (separator2 == notFound)
        return SecurityOrigin::createUnique();

    // Ensure there were at least 2 separator characters. Some hostnames on intranets have
    // underscores in them, so we'll assume that any additional underscores are part of the host.
    if (separator1 == separator2)
        return SecurityOrigin::createUnique();

    // Make sure the port section is a valid port number or doesn't exist
    bool portOkay;
    int port = databaseIdentifier.right(databaseIdentifier.length() - separator2 - 1).toInt(&portOkay);
    bool portAbsent = (separator2 == databaseIdentifier.length() - 1);
    if (!(portOkay || portAbsent))
        return SecurityOrigin::createUnique();

    if (port < 0 || port > maxAllowedPort)
        return SecurityOrigin::createUnique();

    // Split out the 3 sections of data
    String protocol = databaseIdentifier.substring(0, separator1);
    String host = databaseIdentifier.substring(separator1 + 1, separator2 - separator1 - 1);

    // Make sure the components match their canonical representation so we are sure we're round tripping correctly.
    KURL url(KURL(), protocol + "://" + host + ":" + String::number(port) + "/");
    if (!url.isValid() || url.protocol() != protocol || url.host() != host)
        return SecurityOrigin::createUnique();

    return SecurityOrigin::create(url);
}
static String pathSuitableForTestResult(const char* uriString)
{
    URL uri = URL(ParsedURLString, uriString);
    if (uri.isEmpty())
        return "(null)";

    if (!uri.isLocalFile())
        return uri.string();

    URL mainFrameURL = URL(ParsedURLString, ewk_frame_uri_get(browser->mainFrame()));
    if (mainFrameURL.isEmpty())
        mainFrameURL = DumpRenderTreeSupportEfl::provisionalURL(browser->mainFrame());

    String mainFrameUrlPathString = mainFrameURL.path();
    String pathString = uri.path();
    String basePath = mainFrameUrlPathString.substring(0, mainFrameUrlPathString.reverseFind('/') + 1);

    if (!basePath.isEmpty() && pathString.startsWith(basePath))
        return pathString.substring(basePath.length());

    return uri.lastPathComponent();
}
PluginPackage* PluginDatabase::findPlugin(const KURL& url, String& mimeType)
{
    PluginPackage* plugin = pluginForMIMEType(mimeType);
    String filename = url.string();

    if (!plugin) {
        String filename = url.lastPathComponent();
        if (!filename.endsWith("/")) {
            int extensionPos = filename.reverseFind('.');
            if (extensionPos != -1) {
                String extension = filename.substring(extensionPos + 1);

                mimeType = MIMETypeForExtension(extension);
                plugin = pluginForMIMEType(mimeType);
            }
        }
    }

    // FIXME: if no plugin could be found, query Windows for the mime type
    // corresponding to the extension.

    return plugin;
}
Example #24
0
PluginPackage* PluginDatabase::findPlugin(const KURL& url, String& mimeType)
{
    if (!mimeType.isEmpty())
        return pluginForMIMEType(mimeType);
    
    String filename = url.lastPathComponent();
    if (filename.endsWith('/'))
        return 0;
    
    int extensionPos = filename.reverseFind('.');
    if (extensionPos == -1)
        return 0;
    
    String mimeTypeForExtension = MIMETypeForExtension(filename.substring(extensionPos + 1));
    PluginPackage* plugin = pluginForMIMEType(mimeTypeForExtension);
    if (!plugin) {
        // FIXME: if no plugin could be found, query Windows for the mime type
        // corresponding to the extension.
        return 0;
    }
    
    mimeType = mimeTypeForExtension;
    return plugin;
}
Example #25
0
String pathGetFileName(const String& path)
{
    return path.substring(path.reverseFind('/') + 1);
}
Example #26
0
void StructParser::amendHeaderFile(const File& file) {
	MetricsTimer timer(fmt("Code generation for {}", file.fileName()));

    String raw = file.readAllText();

    ParsingContext context;
    Sequence<StructInfo> infos = parseStructData(context,raw);

    Arx::String fileName = file.fileName();
    Arx::File generatedHeaderFile = file.parent().relativeFile(fileName + "_generated.h");
    Arx::File generatedCppFile = file.parent().relativeFile(fileName + "_generated.cpp");


    String genHead;
    genHead.append("// START_GENERATED_CODE\n");
    genHead.append("#ifndef AXM_PARSER_H\n"
                                 "\t#ifndef AXM_FWD_DECL\n"
                                 "\t\tclass AxmNode;\n"
                                 "\t\t#define AXM_FWD_DECL\n"
                                 "\t#endif\n"
                                 "#endif\n"
						   "#ifndef INTROSPECTION_H\n"
						   "\t#ifndef INTROSPECTION_FWD_DECL\n"
						   "\t\tclass StructInfo;\n"
						   "\t\t#define INTROSPECTION_FWD_DECL\n"
						   "\t#endif\n"
						   "#endif\n");

    String genCpp;
    genCpp.append("// START_GENERATED_CODE\n"
                          "#include <conf/AxmParser.h>\n"
                          "#include <core/Introspection.h>\n");
    genCpp.append(Format::format("#include \"{}\"\n", fileName));

    for (const StructInfo& info : infos) {
        Noto::info("\tProcessing struct info: {}", info.name);
        genHead.append(generateReadFunctionDecl(info).raw());
        genHead.append(";\n");
		genHead.append(Format::format("{};\n",generateIntrospectionFunctionDecl(info).raw()));

        genCpp.append(generateReadFunction(info).raw());
        genCpp.append("\n");
		genCpp.append(Format::format("{};\n",generateIntrospectionFunction(info).raw()));
    }

	String existingGenHead = generatedHeaderFile.exists() ? generatedHeaderFile.readAllText() : "";
	String existingGenCpp = generatedCppFile.exists() ? generatedCppFile.readAllText() : "";
	if (genHead.size() != existingGenHead.size() || genHead != existingGenHead) {
		Noto::info("\tRewriting generated header for {}", file.fileName());
    	generatedHeaderFile.write(genHead);
	}
	if (genCpp.size() != existingGenCpp.size() || genCpp != existingGenCpp) {
		Noto::info("\tRewriting generated cpp for {}", file.fileName());
    	generatedCppFile.write(genCpp);
	}

    Arx::String includeGeneratedIdent = "// Include Generated";
    int existingIncludeEnd = raw.reverseFind(includeGeneratedIdent);
    if (existingIncludeEnd == -1) {
        Noto::info("\tRewriting file to include generated header {}", generatedHeaderFile.path);
        int lindex = raw.reverseFind("#endif");
        raw.insert(Format::format("#include \"{}\" {}\n", generatedHeaderFile.fileName(), includeGeneratedIdent), lindex);

        file.write(raw);

        Arx::File mainCpp = file.withExtension(".cpp");
        Arx::String cppRaw;
        if (mainCpp.exists()) {
            cppRaw = mainCpp.readAllText();
        }

        if (!cppRaw.contains(includeGeneratedIdent)) {
            Noto::info("Rewriting cpp file to include generated cpp {}", generatedCppFile.path);
            cppRaw.append(Format::format("#include \"{}\" {}\n", generatedCppFile.fileName(), includeGeneratedIdent));

            mainCpp.write(cppRaw);
        }
    }

	timer.printElapsed();
}
Boolean ClientAuthenticator::checkResponseHeaderForChallenge(
    Array<HTTPHeader> headers)
{
    //
    // Search for "WWW-Authenticate" header:
    //
    const char* authHeader;
    String authType;
    String authChallenge;
    String authRealm;

    if (!HTTPMessage::lookupHeader(
            headers, WWW_AUTHENTICATE, authHeader, false))
    {
        return false;
    }

   //
   // Parse the authentication challenge header
   //
   if (!_parseAuthHeader(authHeader, authType, authChallenge))
   {
       throw InvalidAuthHeader();
   }

   if (String::equal(authType, "Local"))
   {
       _authType = ClientAuthenticator::LOCAL;
       authRealm = _parseBasicRealm(authChallenge);
       if (authRealm.size() == 0)
           return false;
   }
   else if ( String::equal(authType, "Basic"))
   {
       _authType = ClientAuthenticator::BASIC;
       authRealm = _parseBasicRealm(authChallenge);
       if (authRealm.size() == 0)
           return false;
   }
   else if ( String::equal(authType, "Digest"))
   {
       _authType = ClientAuthenticator::DIGEST;
   }
   else if ( String::equal(authType, "Negotiate"))
   {
       _authType = ClientAuthenticator::NEGOTIATE;
#ifdef PEGASUS_NEGOTIATE_AUTHENTICATION
       _session->parseChallenge(authChallenge);
#endif
   }
   else
   {
       throw InvalidAuthHeader();
   }

   if (_challengeReceived)
   {
       // Do not respond to a challenge more than once.
       // Only Negotiate authentication can take multiple roundtrips,
       // but stop it when the server returns empty challenge.
       if (_authType != ClientAuthenticator::NEGOTIATE
               || authChallenge.size() == 0)
       {
           return false;
       }
   }

   _challengeReceived = true;

   if (_authType == ClientAuthenticator::LOCAL)
   {
       String filePath = authRealm;
       FileSystem::translateSlashes(filePath);

       // Check whether the directory is a valid pre-defined directory.
       //
       Uint32 index = filePath.reverseFind('/');

       if (index != PEG_NOT_FOUND)
       {
           String dirName = filePath.subString(0,index);

           if (!String::equal(dirName, String(PEGASUS_LOCAL_AUTH_DIR)))
           {
               // Refuse to respond to the challenge when the file is
               // not in the expected directory
               return false;
           }
       }

       _localAuthFile = authRealm;
   }

   return true;
}
Example #28
0
void TextTrackCue::parseSettings(const String& input)
{
    unsigned position = 0;

    while (position < input.length()) {

        // The WebVTT cue settings part of a WebVTT cue consists of zero or more of the following components, in any order, 
        // separated from each other by one or more U+0020 SPACE characters or U+0009 CHARACTER TABULATION (tab) characters. 
        while (position < input.length() && WebVTTParser::isValidSettingDelimiter(input[position]))
            position++;
        if (position >= input.length())
            break;

        // When the user agent is to parse the WebVTT settings given by a string input for a text track cue cue, 
        // the user agent must run the following steps:
        // 1. Let settings be the result of splitting input on spaces.
        // 2. For each token setting in the list settings, run the following substeps:
        //    1. If setting does not contain a U+003A COLON character (:), or if the first U+003A COLON character (:) 
        //       in setting is either the first or last character of setting, then jump to the step labeled next setting.
        unsigned endOfSetting = position;
        String setting = WebVTTParser::collectWord(input, &endOfSetting);
        CueSetting name;
        size_t colonOffset = setting.find(':', 1);
        if (colonOffset == notFound || colonOffset == 0 || colonOffset == setting.length() - 1)
            goto NextSetting;

        // 2. Let name be the leading substring of setting up to and excluding the first U+003A COLON character (:) in that string.
        name = settingName(setting.substring(0, colonOffset));

        // 3. Let value be the trailing substring of setting starting from the character immediately after the first U+003A COLON character (:) in that string.
        position += colonOffset + 1;
        if (position >= input.length())
            break;

        // 4. Run the appropriate substeps that apply for the value of name, as follows:
        switch (name) {
        case Vertical:
            {
            // If name is a case-sensitive match for "vertical"
            // 1. If value is a case-sensitive match for the string "rl", then let cue's text track cue writing direction 
            //    be vertical growing left.
            String writingDirection = WebVTTParser::collectWord(input, &position);
            if (writingDirection == verticalGrowingLeftKeyword())
                m_writingDirection = VerticalGrowingLeft;
            
            // 2. Otherwise, if value is a case-sensitive match for the string "lr", then let cue's text track cue writing 
            //    direction be vertical growing right.
            else if (writingDirection == verticalGrowingRightKeyword())
                m_writingDirection = VerticalGrowingRight;
            }
            break;
        case Line:
            {
            // 1-2 - Collect chars that are either '-', '%', or a digit.
            // 1. If value contains any characters other than U+002D HYPHEN-MINUS characters (-), U+0025 PERCENT SIGN 
            //    characters (%), and characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), then jump
            //    to the step labeled next setting.
            StringBuilder linePositionBuilder;
            while (position < input.length() && (input[position] == '-' || input[position] == '%' || isASCIIDigit(input[position])))
                linePositionBuilder.append(input[position++]);
            if (position < input.length() && !WebVTTParser::isValidSettingDelimiter(input[position]))
                break;

            // 2. If value does not contain at least one character in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT 
            //    NINE (9), then jump to the step labeled next setting.
            // 3. If any character in value other than the first character is a U+002D HYPHEN-MINUS character (-), then 
            //    jump to the step labeled next setting.
            // 4. If any character in value other than the last character is a U+0025 PERCENT SIGN character (%), then
            //    jump to the step labeled next setting.
            String linePosition = linePositionBuilder.toString();
            if (linePosition.find('-', 1) != notFound || linePosition.reverseFind("%", linePosition.length() - 2) != notFound)
                break;

            // 5. If the first character in value is a U+002D HYPHEN-MINUS character (-) and the last character in value is a 
            //    U+0025 PERCENT SIGN character (%), then jump to the step labeled next setting.
            if (linePosition[0] == '-' && linePosition[linePosition.length() - 1] == '%')
                break;

            // 6. Ignoring the trailing percent sign, if any, interpret value as a (potentially signed) integer, and 
            //    let number be that number. 
            // NOTE: toInt ignores trailing non-digit characters, such as '%'.
            bool validNumber;
            int number = linePosition.toInt(&validNumber);
            if (!validNumber)
                break;

            // 7. If the last character in value is a U+0025 PERCENT SIGN character (%), but number is not in the range 
            //    0 ≤ number ≤ 100, then jump to the step labeled next setting.
            // 8. Let cue's text track cue line position be number.
            // 9. If the last character in value is a U+0025 PERCENT SIGN character (%), then let cue's text track cue 
            //    snap-to-lines flag be false. Otherwise, let it be true.
            if (linePosition[linePosition.length() - 1] == '%') {
                if (number < 0 || number > 100)
                    break;

                // 10 - If '%' then set snap-to-lines flag to false.
                m_snapToLines = false;
            }

            m_linePosition = number;
            }
            break;
        case Position:
            {
            // 1. If value contains any characters other than U+0025 PERCENT SIGN characters (%) and characters in the range 
            //    U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), then jump to the step labeled next setting.
            // 2. If value does not contain at least one character in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9),
            //    then jump to the step labeled next setting.
            String textPosition = WebVTTParser::collectDigits(input, &position);
            if (textPosition.isEmpty())
                break;
            if (position >= input.length())
                break;

            // 3. If any character in value other than the last character is a U+0025 PERCENT SIGN character (%), then jump
            //    to the step labeled next setting.
            // 4. If the last character in value is not a U+0025 PERCENT SIGN character (%), then jump to the step labeled
            //    next setting.
            if (input[position++] != '%')
                break;
            if (position < input.length() && !WebVTTParser::isValidSettingDelimiter(input[position]))
                break;

            // 5. Ignoring the trailing percent sign, interpret value as an integer, and let number be that number.
            // 6. If number is not in the range 0 ≤ number ≤ 100, then jump to the step labeled next setting.
            // NOTE: toInt ignores trailing non-digit characters, such as '%'.
            bool validNumber;
            int number = textPosition.toInt(&validNumber);
            if (!validNumber)
                break;
            if (number < 0 || number > 100)
              break;

            // 7. Let cue's text track cue text position be number.
            m_textPosition = number;
            }
            break;
        case Size:
            {
            // 1. If value contains any characters other than U+0025 PERCENT SIGN characters (%) and characters in the
            //    range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), then jump to the step labeled next setting.
            // 2. If value does not contain at least one character in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT 
            //    NINE (9), then jump to the step labeled next setting.
            String cueSize = WebVTTParser::collectDigits(input, &position);
            if (cueSize.isEmpty())
                break;
            if (position >= input.length())
                break;

            // 3. If any character in value other than the last character is a U+0025 PERCENT SIGN character (%),
            //    then jump to the step labeled next setting.
            // 4. If the last character in value is not a U+0025 PERCENT SIGN character (%), then jump to the step
            //    labeled next setting.
            if (input[position++] != '%')
                break;
            if (position < input.length() && !WebVTTParser::isValidSettingDelimiter(input[position]))
                break;

            // 5. Ignoring the trailing percent sign, interpret value as an integer, and let number be that number.
            // 6. If number is not in the range 0 ≤ number ≤ 100, then jump to the step labeled next setting.
            bool validNumber;
            int number = cueSize.toInt(&validNumber);
            if (!validNumber)
                break;
            if (number < 0 || number > 100)
                break;

            // 7. Let cue's text track cue size be number.
            m_cueSize = number;
            }
            break;
        case Align:
            {
            String cueAlignment = WebVTTParser::collectWord(input, &position);

            // 1. If value is a case-sensitive match for the string "start", then let cue's text track cue alignment be start alignment.
            if (cueAlignment == startKeyword())
                m_cueAlignment = Start;

            // 2. If value is a case-sensitive match for the string "middle", then let cue's text track cue alignment be middle alignment.
            else if (cueAlignment == middleKeyword())
                m_cueAlignment = Middle;

            // 3. If value is a case-sensitive match for the string "end", then let cue's text track cue alignment be end alignment.
            else if (cueAlignment == endKeyword())
                m_cueAlignment = End;
            }
            break;
        case None:
            break;
        }

NextSetting:
        position = endOfSetting;
    }
}
Example #29
0
String pathGetFileName(const String& path)
{
    return path.substring(std::max(path.reverseFind('/'), path.reverseFind('\\')) + 1);
}
Example #30
0
ObjectContentType WebFrameLoaderClient::objectContentType(const URL& url, const String& mimeTypeIn)
{
    String mimeType = mimeTypeIn;

    if (mimeType.isEmpty())
        mimeType = mimeTypeFromURL(url);

    if (mimeType.isEmpty()) {
        String decodedPath = decodeURLEscapeSequences(url.path());
        mimeType = PluginDatabase::installedPlugins()->MIMETypeForExtension(decodedPath.substring(decodedPath.reverseFind('.') + 1));
    }

    if (mimeType.isEmpty())
        return ObjectContentType::Frame; // Go ahead and hope that we can display the content.

    bool plugInSupportsMIMEType = PluginDatabase::installedPlugins()->isMIMETypeRegistered(mimeType);

    if (MIMETypeRegistry::isSupportedImageMIMEType(mimeType))
        return WebCore::ObjectContentType::Image;

    if (plugInSupportsMIMEType)
        return WebCore::ObjectContentType::PlugIn;

    if (MIMETypeRegistry::isSupportedNonImageMIMEType(mimeType))
        return WebCore::ObjectContentType::Frame;

    return WebCore::ObjectContentType::None;
}