Exemple #1
0
PassRefPtr<Intent> Intent::create(ScriptState* scriptState, const Dictionary& options, ExceptionCode& ec)
{
    String action;
    if (!options.get("action", action) || action.isEmpty()) {
        ec = SYNTAX_ERR;
        return 0;
    }

    String type;
    if (!options.get("type", type) || type.isEmpty()) {
        ec = SYNTAX_ERR;
        return 0;
    }

    String service;
    KURL serviceUrl;
    if (options.get("service", service) && !service.isEmpty()) {
      serviceUrl = KURL(KURL(), service);
      if (!serviceUrl.isValid()) {
          ec = SYNTAX_ERR;
          return 0;
      }
    }

    MessagePortArray ports;
    OwnPtr<MessagePortChannelArray> channels;
    if (options.get("transfer", ports))
        channels = MessagePort::disentanglePorts(&ports, ec);

    ScriptValue dataValue;
    RefPtr<SerializedScriptValue> serializedData;
    if (options.get("data", dataValue)) {
        bool didThrow = false;
        serializedData = dataValue.serialize(scriptState, &ports, 0, didThrow);
        if (didThrow) {
            ec = DATA_CLONE_ERR;
            return 0;
        }
    }

    HashMap<String, String> extras;
    Dictionary extrasDictionary;
    if (options.get("extras", extrasDictionary))
        extrasDictionary.getOwnPropertiesAsStringHashMap(extras);

    HashSet<AtomicString> suggestionsStrings;
    Vector<KURL> suggestions;
    if (options.get("suggestions", suggestionsStrings)) {
        for (HashSet<AtomicString>::iterator iter = suggestionsStrings.begin(); iter != suggestionsStrings.end(); ++iter) {
            KURL suggestedURL = KURL(KURL(), *iter);
            if (!suggestedURL.isValid()) {
                ec = SYNTAX_ERR;
                return 0;
            }
            suggestions.append(suggestedURL);
        }
    }

    return adoptRef(new Intent(action, type, serializedData.release(), channels.release(), extras, serviceUrl, suggestions));
}
bool LinkLoader::loadLink(const LinkRelAttribute& relAttribute, const AtomicString& crossOriginMode, const String& type, const KURL& href, Document& document)
{
    if (relAttribute.isDNSPrefetch()) {
        Settings* settings = document.settings();
        // FIXME: The href attribute of the link element can be in "//hostname" form, and we shouldn't attempt
        // to complete that as URL <https://bugs.webkit.org/show_bug.cgi?id=48857>.
        if (settings && settings->dnsPrefetchingEnabled() && href.isValid() && !href.isEmpty())
            prefetchDNS(href.host());
    }

    // FIXME(crbug.com/323096): Should take care of import.
    if ((relAttribute.isLinkPrefetch() || relAttribute.isLinkSubresource()) && href.isValid() && document.frame()) {
        if (!m_client->shouldLoadLink())
            return false;
        Resource::Type type = relAttribute.isLinkSubresource() ?  Resource::LinkSubresource : Resource::LinkPrefetch;
        FetchRequest linkRequest(ResourceRequest(document.completeURL(href)), FetchInitiatorTypeNames::link);
        if (!crossOriginMode.isNull())
            linkRequest.setCrossOriginAccessControl(document.securityOrigin(), crossOriginMode);
        setResource(document.fetcher()->fetchLinkResource(type, linkRequest));
    }

    if (const unsigned prerenderRelTypes = prerenderRelTypesFromRelAttribute(relAttribute)) {
        if (!m_prerender) {
            m_prerender = PrerenderHandle::create(document, this, href, prerenderRelTypes);
        } else if (m_prerender->url() != href) {
            m_prerender->cancel();
            m_prerender = PrerenderHandle::create(document, this, href, prerenderRelTypes);
        }
        // TODO(gavinp): Handle changes to rel types of existing prerenders.
    } else if (m_prerender) {
        m_prerender->cancel();
        m_prerender.clear();
    }
    return true;
}
bool protocolHostAndPortAreEqual(const KURL& a, const KURL& b)
{
    if (!a.isValid() || !b.isValid())
        return false;

    return a.protocol() == b.protocol()
           && a.host() == b.host()
           && a.port() == b.port();
}
Exemple #4
0
void FileSelectDlg::updateSizeLabels()
{
	//calculate free disk space

	KURL sdir = KURL(m_downloadLocation -> url());
	while( sdir.isValid() && sdir.isLocalFile() && (!sdir.isEmpty())  && (! QDir(sdir.path()).exists()) ) 
	{
		sdir = sdir.upURL();
	}
	
	Uint64 bytes_free = 0;
	if (!FreeDiskSpace(sdir.path(),bytes_free))
	{
		FreeDiskSpace(tc->getDataDir(),bytes_free);
	}
	
	Uint64 bytes_to_download = 0;
	if (root)
		bytes_to_download = root->bytesToDownload();
	else
		bytes_to_download = tc->getStats().total_bytes;

	lblFree->setText(kt::BytesToString(bytes_free));
	lblRequired->setText(kt::BytesToString(bytes_to_download));

	if (bytes_to_download > bytes_free)
		lblStatus->setText("<font color=\"#ff0000\">" + kt::BytesToString(-1*(long long)(bytes_free - bytes_to_download)) + i18n(" short!"));
	else
		lblStatus->setText(kt::BytesToString(bytes_free - bytes_to_download));
}
Exemple #5
0
PassRefPtr<EventSource> EventSource::create(ScriptExecutionContext* context, const String& url, const Dictionary& eventSourceInit, ExceptionCode& ec)
{
    if (url.isEmpty()) {
        ec = SYNTAX_ERR;
        return 0;
    }

    KURL fullURL = context->completeURL(url);
    if (!fullURL.isValid()) {
        ec = SYNTAX_ERR;
        return 0;
    }

    // FIXME: Convert this to check the isolated world's Content Security Policy once webkit.org/b/104520 is solved.
    bool shouldBypassMainWorldContentSecurityPolicy = false;
    if (context->isDocument()) {
        Document* document = toDocument(context);
        shouldBypassMainWorldContentSecurityPolicy = document->frame()->script()->shouldBypassMainWorldContentSecurityPolicy();
    }
    if (!shouldBypassMainWorldContentSecurityPolicy && !context->contentSecurityPolicy()->allowConnectToSource(fullURL)) {
        // FIXME: Should this be throwing an exception?
        ec = SECURITY_ERR;
        return 0;
    }

    RefPtr<EventSource> source = adoptRef(new EventSource(context, fullURL, eventSourceInit));

    source->setPendingActivity(source.get());
    source->connect();
    source->suspendIfNeeded();

    return source.release();
}
PassRefPtr<EntrySync> WorkerContext::webkitResolveLocalFileSystemSyncURL(const String& url, ExceptionCode& ec)
{
    ec = 0;
    KURL completedURL = completeURL(url);
    if (!AsyncFileSystem::isAvailable() || !securityOrigin()->canAccessFileSystem() || !securityOrigin()->canRequest(completedURL)) {
        ec = FileException::SECURITY_ERR;
        return 0;
    }

    AsyncFileSystem::Type type;
    String filePath;
    if (!completedURL.isValid() || !DOMFileSystemBase::crackFileSystemURL(completedURL, type, filePath)) {
        ec = FileException::ENCODING_ERR;
        return 0;
    }

    FileSystemSyncCallbackHelper readFileSystemHelper;
    LocalFileSystem::localFileSystem().readFileSystem(this, type, FileSystemCallbacks::create(readFileSystemHelper.successCallback(), readFileSystemHelper.errorCallback(), this), true);
    RefPtr<DOMFileSystemSync> fileSystem = readFileSystemHelper.getResult(ec);
    if (!fileSystem)
        return 0;

    RefPtr<EntrySync> entry = fileSystem->root()->getDirectory(filePath, 0, ec);
    if (ec == FileException::TYPE_MISMATCH_ERR)
        return fileSystem->root()->getFile(filePath, 0, ec);

    return entry.release();
}
CredentialTransformData::CredentialTransformData(HTMLFormElement* form)
    : m_userNameElement(0)
    , m_passwordElement(0)
    , m_isValid(false)
{
    ASSERT(form);

    // Get the document URL
    KURL fullOrigin(ParsedURLString, form->document()->documentURI());

    // Calculate the canonical action URL
    String action = form->action();
    if (action.isNull())
        action = ""; // missing 'action' attribute implies current URL
    KURL fullAction = form->document()->completeURL(action);
    if (!fullAction.isValid())
        return;

    if (!findPasswordFormFields(form))
        return;

    m_url = stripURL(fullOrigin);
    m_action = stripURL(fullAction);
    m_protectionSpace = ProtectionSpace(m_url.host(), m_url.port(), ProtectionSpaceServerHTTP, "Form", ProtectionSpaceAuthenticationSchemeHTMLForm);
    m_credential = Credential(m_userNameElement->value(), m_passwordElement->value(), CredentialPersistencePermanent);

    m_isValid = true;
}
Exemple #8
0
PassRefPtr<EventSource> EventSource::create(ScriptExecutionContext* context, const String& url, ExceptionCode& ec)
{
    if (url.isEmpty()) {
        ec = SYNTAX_ERR;
        return 0;
    }

    KURL fullURL = context->completeURL(url);
    if (!fullURL.isValid()) {
        ec = SYNTAX_ERR;
        return 0;
    }

    // FIXME: Should support at least some cross-origin requests.
    if (!context->securityOrigin()->canRequest(fullURL)) {
        ec = SECURITY_ERR;
        return 0;
    }

    if (!context->contentSecurityPolicy()->allowConnectToSource(fullURL)) {
        // FIXME: Should this be throwing an exception?
        ec = SECURITY_ERR;
        return 0;
    }

    RefPtr<EventSource> source = adoptRef(new EventSource(fullURL, context));

    source->setPendingActivity(source.get());
    source->connect();
    source->suspendIfNeeded();

    return source.release();
}
EventSource* EventSource::create(ExecutionContext* context, const String& url, const EventSourceInit& eventSourceInit, ExceptionState& exceptionState)
{
    if (url.isEmpty()) {
        exceptionState.throwDOMException(SyntaxError, "Cannot open an EventSource to an empty URL.");
        return nullptr;
    }

    KURL fullURL = context->completeURL(url);
    if (!fullURL.isValid()) {
        exceptionState.throwDOMException(SyntaxError, "Cannot open an EventSource to '" + url + "'. The URL is invalid.");
        return nullptr;
    }

    // FIXME: Convert this to check the isolated world's Content Security Policy once webkit.org/b/104520 is solved.
    if (!ContentSecurityPolicy::shouldBypassMainWorld(context) && !context->contentSecurityPolicy()->allowConnectToSource(fullURL)) {
        // We can safely expose the URL to JavaScript, as this exception is generate synchronously before any redirects take place.
        exceptionState.throwSecurityError("Refused to connect to '" + fullURL.elidedString() + "' because it violates the document's Content Security Policy.");
        return nullptr;
    }

    EventSource* source = new EventSource(context, fullURL, eventSourceInit);

    source->scheduleInitialConnect();
    source->suspendIfNeeded();
    return source;
}
void ArchiveResourceCollection::addAllResources(MHTMLArchive* archive)
{
    ASSERT(archive);
    if (!archive)
        return;

    const MHTMLArchive::SubArchiveResources& subresources = archive->subresources();
    for (const RefPtrWillBeMember<ArchiveResource>& subresource : subresources) {
        addResource(*subresource);
    }

    const MHTMLArchive::SubFrameArchives& subframes = archive->subframeArchives();
    for (const RefPtrWillBeMember<MHTMLArchive>& archive : subframes) {
        ASSERT(archive->mainResource());

        const String& frameName = archive->mainResource()->frameName();
        if (!frameName.isNull()) {
            m_subframes.set(frameName, archive.get());
        } else {
            // In the MHTML case, frames don't have a name so we use the URL instead.
            m_subframes.set(archive->mainResource()->url().string(), archive.get());
        }

        KURL cidURI = MHTMLParser::convertContentIDToURI(archive->mainResource()->contentID());
        if (cidURI.isValid())
            m_subframes.set(cidURI, archive.get());
    }
}
WebPasswordFormData::WebPasswordFormData(const WebFormElement& webForm)
{
    RefPtr<HTMLFormElement> form = webForm.operator PassRefPtr<HTMLFormElement>();

    Frame* frame = form->document()->frame();
    if (!frame)
        return;

    PasswordFormFields fields;
    findPasswordFormFields(form.get(), &fields);

    // Get the document URL
    KURL fullOrigin(ParsedURLString, form->document()->documentURI());

    // Calculate the canonical action URL
    String action = form->action();
    if (action.isNull())
        action = ""; // missing 'action' attribute implies current URL
    KURL fullAction = frame->loader()->completeURL(action);
    if (!fullAction.isValid())
        return;

    // Determine the types of the password fields
    HTMLInputElement* password = 0;
    HTMLInputElement* oldPassword = 0;
    if (!locateSpecificPasswords(&fields, &password, &oldPassword))
        return;

    assemblePasswordFormResult(fullOrigin, fullAction,
                               fields.submit, fields.userName,
                               oldPassword, password, this);
}
void SearchManager::startSearch(KURL const& root, SearchMode const& modo)
{
    canceled_ = false;

    //time_.restart();
    time_.start();

    Q_ASSERT(root.isValid());
    //Q_ASSERT(root.protocol() == "http" || root.protocol() == "https");

    if(root.hasHost() && (domain_.isNull() || domain_.isEmpty()))
    {
        setDomain(root.host() + root.directory());
        kdDebug(23100) << "Domain: " << domain_ << endl;
    }
    root_.setIsRoot(true);
    root_.setDepth(0);
    root_.setOriginalUrl(root.prettyURL());
    root_.setAbsoluteUrl(root);
    root_.setOnlyCheckHeader(false);
    root_.setRootUrl(root);

    search_mode_ = modo;
    if(modo == depth)
        Q_ASSERT(depth_ != -1);
    else if(modo == domain)
        Q_ASSERT(depth_ == -1);
    else
        Q_ASSERT(depth_ != -1);

    searching_ = true;

    //Q_ASSERT(domain_ != QString::null);
    checkRoot();
}
void History::stateObjectAdded(PassRefPtr<SerializedScriptValue> data, const String& title, const String& urlString, StateObjectType stateObjectType, ExceptionCode& ec)
{
    if (!m_frame || !m_frame->page())
        return;
    
    KURL fullURL = urlForState(urlString);
    RefPtr<SecurityOrigin> origin = SecurityOrigin::create(fullURL);
    if (!fullURL.isValid() || !m_frame->document()->securityOrigin()->isSameSchemeHostPort(origin.get())) {
        ec = SECURITY_ERR;
        return;
    }

    if (stateObjectType == StateObjectPush)
        m_frame->loader()->history()->pushState(data, title, fullURL.string());
    else if (stateObjectType == StateObjectReplace)
        m_frame->loader()->history()->replaceState(data, title, fullURL.string());
            
    if (!urlString.isEmpty())
        m_frame->document()->updateURLForPushOrReplaceState(fullURL);

    if (stateObjectType == StateObjectPush)
        m_frame->loader()->client()->dispatchDidPushStateWithinPage();
    else if (stateObjectType == StateObjectReplace)
        m_frame->loader()->client()->dispatchDidReplaceStateWithinPage();
}
Exemple #14
0
void PageSerializer::serializeCSSStyleSheet(CSSStyleSheet* styleSheet, const KURL& url)
{
    StringBuilder cssText;
    for (unsigned i = 0; i < styleSheet->length(); ++i) {
        StyleBase* item = styleSheet->item(i);
        String itemText = item->cssText();
        if (!itemText.isEmpty()) {
            cssText.append(itemText);
            if (i < styleSheet->length() - 1)
                cssText.append("\n\n");
        }
        // Some rules have resources associated with them that we need to retrieve.
        if (item->isImportRule()) {
            CSSImportRule* importRule = static_cast<CSSImportRule*>(item);
            KURL importURL = styleSheet->document()->completeURL(importRule->href());
            if (m_resourceURLs.contains(importURL))
                continue;
            serializeCSSStyleSheet(importRule->styleSheet(), importURL);
        } else if (item->isFontFaceRule()) {
            // FIXME: Add support for font face rule. It is not clear to me at this point if the actual otf/eot file can
            // be retrieved from the CSSFontFaceRule object.
        } else if (item->isStyleRule())
            retrieveResourcesForCSSRule(static_cast<CSSStyleRule*>(item));
    }

    if (url.isValid() && !m_resourceURLs.contains(url)) {
        // FIXME: We should check whether a charset has been specified and if none was found add one.
        TextEncoding textEncoding(styleSheet->charset());
        ASSERT(textEncoding.isValid());
        String textString = cssText.toString();
        CString text = textEncoding.encode(textString.characters(), textString.length(), EntitiesForUnencodables);
        m_resources->append(Resource(url, String("text/css"), SharedBuffer::create(text.data(), text.length())));
        m_resourceURLs.add(url);
    }
}
Exemple #15
0
CachedImage* CachedResourceLoader::requestImage(ResourceRequest& request)
{
    if (Frame* f = frame()) {
        Settings* settings = f->settings();
        if (!f->loader()->client()->allowImages(!settings || settings->areImagesEnabled()))
            return 0;

        if (f->loader()->pageDismissalEventBeingDispatched()) {
            KURL requestURL = request.url();
            if (requestURL.isValid() && canRequest(CachedResource::ImageResource, requestURL))
                PingLoader::loadImage(f, requestURL);
            return 0;
        }
    }
    CachedImage* resource = static_cast<CachedImage*>(requestResource(CachedResource::ImageResource, request, String()));
    if (resource) {
#ifdef ANDROID_BLOCK_NETWORK_IMAGE
        resource->setAutoLoadWasPreventedBySettings(!autoLoadImages() || shouldBlockNetworkImage(request.url()));
#else
        resource->setAutoLoadWasPreventedBySettings(!autoLoadImages());
#endif
        if (autoLoadImages() && resource->stillNeedsLoad()) {
#ifdef ANDROID_BLOCK_NETWORK_IMAGE
            if (shouldBlockNetworkImage(request.url())) {
                return resource;
            }
#endif
            resource->setLoading(true);
            load(resource, true);
        }
    }
    return resource;
}
Exemple #16
0
static void dnsPrefetchIfNeeded(
    const LinkRelAttribute& relAttribute,
    const KURL& href,
    Document& document,
    const NetworkHintsInterface& networkHintsInterface,
    LinkCaller caller) {
  if (relAttribute.isDNSPrefetch()) {
    UseCounter::count(document, UseCounter::LinkRelDnsPrefetch);
    if (caller == LinkCalledFromHeader)
      UseCounter::count(document, UseCounter::LinkHeaderDnsPrefetch);
    Settings* settings = document.settings();
    // FIXME: The href attribute of the link element can be in "//hostname"
    // form, and we shouldn't attempt to complete that as URL
    // <https://bugs.webkit.org/show_bug.cgi?id=48857>.
    if (settings && settings->dnsPrefetchingEnabled() && href.isValid() &&
        !href.isEmpty()) {
      if (settings->logDnsPrefetchAndPreconnect()) {
        document.addConsoleMessage(ConsoleMessage::create(
            OtherMessageSource, DebugMessageLevel,
            String("DNS prefetch triggered for " + href.host())));
      }
      networkHintsInterface.dnsPrefetchHost(href.host());
    }
  }
}
Exemple #17
0
static void preconnectIfNeeded(
    const LinkRelAttribute& relAttribute,
    const KURL& href,
    Document& document,
    const CrossOriginAttributeValue crossOrigin,
    const NetworkHintsInterface& networkHintsInterface,
    LinkCaller caller) {
  if (relAttribute.isPreconnect() && href.isValid() &&
      href.protocolIsInHTTPFamily()) {
    UseCounter::count(document, UseCounter::LinkRelPreconnect);
    if (caller == LinkCalledFromHeader)
      UseCounter::count(document, UseCounter::LinkHeaderPreconnect);
    Settings* settings = document.settings();
    if (settings && settings->logDnsPrefetchAndPreconnect()) {
      document.addConsoleMessage(ConsoleMessage::create(
          OtherMessageSource, DebugMessageLevel,
          String("Preconnect triggered for ") + href.getString()));
      if (crossOrigin != CrossOriginAttributeNotSet) {
        document.addConsoleMessage(ConsoleMessage::create(
            OtherMessageSource, DebugMessageLevel,
            String("Preconnect CORS setting is ") +
                String((crossOrigin == CrossOriginAttributeAnonymous)
                           ? "anonymous"
                           : "use-credentials")));
      }
    }
    networkHintsInterface.preconnectHost(href, crossOrigin);
  }
}
void DolphinView::startDirLister(const KURL& url, bool reload)
{
    if (!url.isValid()) {
        const QString location(url.prettyURL());
        if (location.isEmpty()) {
            m_statusBar->setMessage(i18n("The location is empty."), DolphinStatusBar::Error);
        }
        else {
            m_statusBar->setMessage(i18n("The location '%1' is invalid.").arg(location),
                                    DolphinStatusBar::Error);
        }
        return;
    }

    // Only show the directory loading progress if the status bar does
    // not contain another progress information. This means that
    // the directory loading progress information has the lowest priority.
    const QString progressText(m_statusBar->progressText());
    m_showProgress = progressText.isEmpty() ||
                     (progressText == i18n("Loading directory..."));
    if (m_showProgress) {
        m_statusBar->setProgressText(i18n("Loading directory..."));
        m_statusBar->setProgress(0);
    }

    m_refreshing = true;
    m_dirLister->stop();
    m_dirLister->openURL(url, false, reload);
}
Exemple #19
0
bool PlaylistSaver::save(const KURL &file, int opt)
{
//	kdDebug(66666) << k_funcinfo << "opt=" << opt << endl;

    if(file.isEmpty() || !file.isValid())
        return false;

    switch (opt)
    {
    default:
    case 0:
    case XMLPlaylist:
        return saveXML(file, opt);

    case M3U:
    case EXTM3U:
        return saveM3U(file, opt);

    case PLS:
        return savePLS(file, opt);

    case ASX:
        return false; // No, I won't code that! [mETz]
    }
}
static PathToDefaultProtectionSpaceMap::iterator findDefaultProtectionSpaceForURL(const KURL& url)
{
    ASSERT(url.protocolIsInHTTPFamily());
    ASSERT(url.isValid());

    PathToDefaultProtectionSpaceMap& map = pathToDefaultProtectionSpaceMap();

    // Don't spend time iterating the path for origins that don't have any credentials.
    if (!originsWithCredentials().contains(originStringFromURL(url)))
        return map.end();

    String directoryURL = protectionSpaceMapKeyFromURL(url);
    unsigned directoryURLPathStart = url.pathStart();
    while (true) {
        PathToDefaultProtectionSpaceMap::iterator iter = map.find(directoryURL);
        if (iter != map.end())
            return iter;

        if (directoryURL.length() == directoryURLPathStart + 1)  // path is "/" already, cannot shorten it any more
            return map.end();

        size_t index = directoryURL.reverseFind('/', directoryURL.length() - 2);
        ASSERT(index != notFound);
        directoryURL = directoryURL.substring(0, (index == directoryURLPathStart) ? index + 1 : index);
        ASSERT(directoryURL.length() > directoryURLPathStart);
        ASSERT(directoryURL.length() == directoryURLPathStart + 1 || directoryURL[directoryURL.length() - 1] != '/');
    }
}
KURL AbstractWorker::resolveURL(const String& url, ExceptionCode& ec)
{
    if (url.isEmpty()) {
        ec = SYNTAX_ERR;
        return KURL();
    }

    // FIXME: This should use the dynamic global scope (bug #27887)
    KURL scriptURL = scriptExecutionContext()->completeURL(url);
    if (!scriptURL.isValid()) {
        ec = SYNTAX_ERR;
        return KURL();
    }

    if (!scriptExecutionContext()->securityOrigin()->canRequest(scriptURL)) {
        ec = SECURITY_ERR;
        return KURL();
    }

    if (scriptExecutionContext()->contentSecurityPolicy() && !scriptExecutionContext()->contentSecurityPolicy()->allowScriptFromSource(scriptURL)) {
        ec = SECURITY_ERR;
        return KURL();
    }

    return scriptURL;
}
void KSubtitleRipperView::createSRT() {
	// TODO check if srttool is executable
	
	if ( !askIfModified() ) return;

	KURL url = KFileDialog::getSaveURL( srtName, "*.srt|" + i18n("SRT Subtitles"), this, i18n( "Save Subtitles" ) );
	if ( url.isEmpty() || !url.isValid() ) return;
	
	/*QString extension = QFileInfo( url.path() ).extension( false ).lower();
	if ( extension != "srt" && ( !url.isLocalFile() || !QFile::exists( url.path() ) ) )
		url = url.url() + ".srt";
	*/
	QString text = "A file named \"%1\" already exists.\nAre you sure you want to overwrite it?";
	if ( url.isLocalFile() && QFile::exists( url.path() ) &&
		KMessageBox::warningContinueCancel( this, i18n( text ).arg( url.filename() ),
		i18n( "Overwrite File?" ), i18n( "Overwrite" ) ) == KMessageBox::Cancel ) return;
	
	newSrt = new KURL( url );
	
	if ( url.isLocalFile() ) {
		tmpSrt = QString::null;
		
		CreateSRT *createSrt = new CreateSRT( project, url.path() );
		
		connect(createSrt, SIGNAL(success( CreateSRT* )),
			this, SLOT(createSrtSuccess( CreateSRT* ) ) );
		connect(createSrt, SIGNAL(failed( CreateSRT*, const QString& )),
			this, SLOT(createSrtFailed( CreateSRT*, const QString& ) ) );
		
		createSrt->saveSRT();
	} else {
PassRefPtr<EntrySync> WorkerGlobalScopeFileSystem::webkitResolveLocalFileSystemSyncURL(WorkerGlobalScope* worker, const String& url, ExceptionState& exceptionState)
{
    KURL completedURL = worker->completeURL(url);
    ExecutionContext* secureContext = worker->executionContext();
    if (!secureContext->securityOrigin()->canAccessFileSystem() || !secureContext->securityOrigin()->canRequest(completedURL)) {
        exceptionState.throwSecurityError(FileError::securityErrorMessage);
        return 0;
    }

    if (!completedURL.isValid()) {
        exceptionState.throwDOMException(EncodingError, "the URL '" + url + "' is invalid.");
        return 0;
    }

    EntrySyncCallbackHelper resolveURLHelper;
    OwnPtr<AsyncFileSystemCallbacks> callbacks = ResolveURICallbacks::create(resolveURLHelper.successCallback(), resolveURLHelper.errorCallback(), worker);
    callbacks->setShouldBlockUntilCompletion(true);

    LocalFileSystem::from(worker)->resolveURL(worker, completedURL, callbacks.release());

    RefPtr<EntrySync> entry = resolveURLHelper.getResult(exceptionState);
    if (!entry)
        return 0;
    return entry.release();
}
Exemple #24
0
ScriptPromise ServiceWorkerClients::openWindow(ScriptState* scriptState,
                                               const String& url) {
  ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState);
  ScriptPromise promise = resolver->promise();
  ExecutionContext* context = scriptState->getExecutionContext();

  KURL parsedUrl = KURL(toWorkerGlobalScope(context)->location()->url(), url);
  if (!parsedUrl.isValid()) {
    resolver->reject(V8ThrowException::createTypeError(
        scriptState->isolate(), "'" + url + "' is not a valid URL."));
    return promise;
  }

  if (!context->getSecurityOrigin()->canDisplay(parsedUrl)) {
    resolver->reject(V8ThrowException::createTypeError(
        scriptState->isolate(),
        "'" + parsedUrl.elidedString() + "' cannot be opened."));
    return promise;
  }

  if (!context->isWindowInteractionAllowed()) {
    resolver->reject(DOMException::create(InvalidAccessError,
                                          "Not allowed to open a window."));
    return promise;
  }
  context->consumeWindowInteraction();

  ServiceWorkerGlobalScopeClient::from(context)->openWindow(
      parsedUrl, WTF::makeUnique<NavigateClientCallback>(resolver));
  return promise;
}
Exemple #25
0
static bool shouldTreatAsUniqueOrigin(const KURL& url)
{
    if (!url.isValid())
        return true;

    // FIXME: Do we need to unwrap the URL further?
    KURL innerURL = shouldUseInnerURL(url) ? extractInnerURL(url) : url;

    // FIXME: Check whether innerURL is valid.

    // For edge case URLs that were probably misparsed, make sure that the origin is unique.
    // FIXME: Do we really need to do this? This looks to be a hack around a
    // security bug in CFNetwork that might have been fixed.
    if (schemeRequiresAuthority(innerURL) && innerURL.host().isEmpty())
        return true;

    // SchemeRegistry needs a lower case protocol because it uses HashMaps
    // that assume the scheme has already been canonicalized.
    String protocol = innerURL.protocol().lower();

    if (SchemeRegistry::shouldTreatURLSchemeAsNoAccess(protocol))
        return true;

    // This is the common case.
    return false;
}
KXmlRpcServer::KXmlRpcServer( const KURL &url, QObject *parent, const char *name ) : QObject( parent, name ) {

	if ( url.isValid() )
		m_url = url;

	m_userAgent = "KDE XMLRPC resources";
}
Exemple #27
0
CachedResource* DocLoader::requestResource(CachedResource::Type type, const String& url, const String& charset, bool isPreload)
{
    KURL fullURL = m_doc->completeURL(url);

    if (!fullURL.isValid() || !canRequest(type, fullURL))
        return 0;

    if (cache()->disabled()) {
        DocumentResourceMap::iterator it = m_documentResources.find(fullURL.string());
        
        if (it != m_documentResources.end()) {
            it->second->setDocLoader(0);
            m_documentResources.remove(it);
        }
    }

    checkForReload(fullURL);

    CachedResource* resource = cache()->requestResource(this, type, fullURL, charset, isPreload);
    if (resource) {
        // Check final URL of resource to catch redirects.
        // See <https://bugs.webkit.org/show_bug.cgi?id=21963>.
        if (!canRequest(type, KURL(resource->url())))
            return 0;

        m_documentResources.set(resource->url(), resource);
        checkCacheObjectStatus(resource);
    }
    return resource;
}
PassRefPtr<EventSource> EventSource::create(ExecutionContext* context, const String& url, const Dictionary& eventSourceInit, ExceptionState& exceptionState)
{
    if (url.isEmpty()) {
        exceptionState.throwDOMException(SyntaxError, "Cannot open an EventSource to an empty URL.");
        return 0;
    }

    KURL fullURL = context->completeURL(url);
    if (!fullURL.isValid()) {
        exceptionState.throwDOMException(SyntaxError, "Cannot open an EventSource to '" + url + "'. The URL is invalid.");
        return 0;
    }

    // FIXME: Convert this to check the isolated world's Content Security Policy once webkit.org/b/104520 is solved.
    bool shouldBypassMainWorldContentSecurityPolicy = false;
    if (context->isDocument()) {
        Document* document = toDocument(context);
        shouldBypassMainWorldContentSecurityPolicy = document->frame()->script().shouldBypassMainWorldContentSecurityPolicy();
    }
    if (!shouldBypassMainWorldContentSecurityPolicy && !context->contentSecurityPolicy()->allowConnectToSource(fullURL)) {
        // We can safely expose the URL to JavaScript, as this exception is generate synchronously before any redirects take place.
        exceptionState.throwSecurityError("Refused to connect to '" + fullURL.elidedString() + "' because it violates the document's Content Security Policy.");
        return 0;
    }

    RefPtr<EventSource> source = adoptRef(new EventSource(context, fullURL, eventSourceInit));

    source->setPendingActivity(source.get());
    source->scheduleInitialConnect();
    source->suspendIfNeeded();

    return source.release();
}
String SVGImageLoader::sourceURI(const AtomicString& attribute) const
{
    KURL base = element()->baseURI();
    if (base.isValid())
        return KURL(base, stripLeadingAndTrailingHTMLSpaces(attribute)).string();
    return element()->document()->completeURL(stripLeadingAndTrailingHTMLSpaces(attribute));
}
Exemple #30
0
void DOMTreeView::slotSaveClicked()
{
  //kdDebug(90180) << "void KfingerCSSWidget::slotSaveAs()" << endl;
  KURL url = KFileDialog::getSaveFileName( part->url().url(), "*.html",
					   this, i18n("Save DOM Tree as HTML") );
  if (!(url.isEmpty()) && url.isValid()) {
    QFile file(url.path());

    if (file.exists()) {
      const QString title = i18n( "File Exists" );
      const QString text = i18n( "Do you really want to overwrite: \n%1?" ).arg(url.url());
      if (KMessageBox::Continue != KMessageBox::warningContinueCancel(this, text, title, i18n("Overwrite") ) ) {
	return;
      }
    }

    if (file.open(IO_WriteOnly) ) {
      kdDebug(90180) << "Opened File: " << url.url() << endl;
      m_textStream = new QTextStream(&file); //(stdOut)
      saveTreeAsHTML(part->document());
      file.close();
      kdDebug(90180) << "File closed " << endl;
      delete m_textStream;
    } else {
      const QString title = i18n( "Unable to Open File" );
      const QString text = i18n( "Unable to open \n %1 \n for writing" ).arg(url.path());
      KMessageBox::sorry( this, text, title );
    }
  } else {
    const QString title = i18n( "Invalid URL" );
    const QString text = i18n( "This URL \n %1 \n is not valid." ).arg(url.url());
    KMessageBox::sorry( this, text, title );
  }
}