SCM Scm::loadFile(const QString& filename) { return protect(_load_file,(void*)filename.ascii()); }
v8::Local<v8::Value> ScriptController::callFunction(v8::Handle<v8::Function> function, v8::Handle<v8::Object> receiver, int argc, v8::Handle<v8::Value> args[]) { // Keep Frame (and therefore ScriptController) alive. RefPtr<Frame> protect(m_frame); return ScriptController::callFunctionWithInstrumentation(m_frame ? m_frame->document() : 0, function, receiver, argc, args); }
QString QsCodeMarker::markedUpCode( const QString& code, const Node * /* relative */, const QString& /* dirPath */ ) { return protect( code ); }
/** * Determine the value of the flag, and set it before returning. */ bool GetAndSet(bool new_value=true) { ScopeLock protect(mutex); bool old_value = value; value = new_value; return old_value; }
// In this method, we can clear |request| to tell content::WebURLLoaderImpl of // Chromium not to follow the redirect. This works only when this method is // called by RawResource::willSendRequest(). If called by // RawResource::didAddClient(), clearing |request| won't be propagated // to content::WebURLLoaderImpl. So, this loader must also get detached from // the resource by calling clearResource(). void DocumentThreadableLoader::redirectReceived(Resource* resource, ResourceRequest& request, const ResourceResponse& redirectResponse) { ASSERT(m_client); ASSERT_UNUSED(resource, resource == this->resource()); ASSERT(m_async); if (!m_actualRequest.isNull()) { reportResponseReceived(resource->identifier(), redirectResponse); handlePreflightFailure(redirectResponse.url().string(), "Response for preflight is invalid (redirect)"); // |this| may be dead here. request = ResourceRequest(); return; } if (m_redirectMode == WebURLRequest::FetchRedirectModeManual) { // Keep |this| alive even if the client release a reference in // responseReceived(). RefPtr<DocumentThreadableLoader> protect(this); // We use |m_redirectMode| to check the original redirect mode. // |request| is a new request for redirect. So we don't set the redirect // mode of it in WebURLLoaderImpl::Context::OnReceivedRedirect(). ASSERT(request.useStreamOnResponse()); // There is no need to read the body of redirect response because there // is no way to read the body of opaque-redirect filtered response's // internal response. // TODO(horo): If we support any API which expose the internal body, we // will have to read the body. And also HTTPCache changes will be needed // because it doesn't store the body of redirect responses. responseReceived(resource, redirectResponse, adoptPtr(new EmptyDataHandle())); if (m_client) { ASSERT(m_actualRequest.isNull()); notifyFinished(resource); } request = ResourceRequest(); return; } if (m_redirectMode == WebURLRequest::FetchRedirectModeError || !isAllowedByContentSecurityPolicy(request.url(), ContentSecurityPolicy::DidRedirect)) { ThreadableLoaderClient* client = m_client; clear(); client->didFailRedirectCheck(); // |this| may be dead here. request = ResourceRequest(); return; } // Allow same origin requests to continue after allowing clients to audit the redirect. if (isAllowedRedirect(request.url())) { if (m_client->isDocumentThreadableLoaderClient()) static_cast<DocumentThreadableLoaderClient*>(m_client)->willFollowRedirect(request, redirectResponse); return; } if (m_corsRedirectLimit <= 0) { ThreadableLoaderClient* client = m_client; clear(); client->didFailRedirectCheck(); // |this| may be dead here. } else if (m_options.crossOriginRequestPolicy == UseAccessControl) { --m_corsRedirectLimit; InspectorInstrumentation::didReceiveCORSRedirectResponse(document().frame(), resource->identifier(), document().frame()->loader().documentLoader(), redirectResponse, 0); bool allowRedirect = false; String accessControlErrorDescription; // Non-simple cross origin requests (both preflight and actual one) are // not allowed to follow redirect. if (m_crossOriginNonSimpleRequest) { accessControlErrorDescription = "The request was redirected to '"+ request.url().string() + "', which is disallowed for cross-origin requests that require preflight."; } else { // The redirect response must pass the access control check if the // original request was not same-origin. allowRedirect = CrossOriginAccessControl::isLegalRedirectLocation(request.url(), accessControlErrorDescription) && (m_sameOriginRequest || passesAccessControlCheck(redirectResponse, effectiveAllowCredentials(), securityOrigin(), accessControlErrorDescription, m_requestContext)); } if (allowRedirect) { // FIXME: consider combining this with CORS redirect handling performed by // CrossOriginAccessControl::handleRedirect(). clearResource(); RefPtr<SecurityOrigin> originalOrigin = SecurityOrigin::create(redirectResponse.url()); RefPtr<SecurityOrigin> requestOrigin = SecurityOrigin::create(request.url()); // If the original request wasn't same-origin, then if the request URL origin is not same origin with the original URL origin, // set the source origin to a globally unique identifier. (If the original request was same-origin, the origin of the new request // should be the original URL origin.) if (!m_sameOriginRequest && !originalOrigin->isSameSchemeHostPort(requestOrigin.get())) m_securityOrigin = SecurityOrigin::createUnique(); // Force any subsequent requests to use these checks. m_sameOriginRequest = false; // Since the request is no longer same-origin, if the user didn't request credentials in // the first place, update our state so we neither request them nor expect they must be allowed. if (m_resourceLoaderOptions.credentialsRequested == ClientDidNotRequestCredentials) m_forceDoNotAllowStoredCredentials = true; // Remove any headers that may have been added by the network layer that cause access control to fail. request.clearHTTPReferrer(); request.clearHTTPOrigin(); request.clearHTTPUserAgent(); // Add any CORS simple request headers which we previously saved from the original request. for (const auto& header : m_simpleRequestHeaders) request.setHTTPHeaderField(header.key, header.value); makeCrossOriginAccessRequest(request); // |this| may be dead here. return; } ThreadableLoaderClient* client = m_client; clear(); client->didFailAccessControlCheck(ResourceError(errorDomainBlinkInternal, 0, redirectResponse.url().string(), accessControlErrorDescription)); // |this| may be dead here. } else { ThreadableLoaderClient* client = m_client; clear(); client->didFailRedirectCheck(); // |this| may be dead here. } request = ResourceRequest(); }
void ResourceLoader::willSendRequestInternal(ResourceRequest& request, const ResourceResponse& redirectResponse) { // Protect this in this delegate method since the additional processing can do // anything including possibly derefing this; one example of this is Radar 3266216. Ref<ResourceLoader> protect(*this); ASSERT(!m_reachedTerminalState); #if ENABLE(CONTENT_EXTENSIONS) ASSERT(m_resourceType != ResourceType::Invalid); #endif // We need a resource identifier for all requests, even if FrameLoader is never going to see it (such as with CORS preflight requests). bool createdResourceIdentifier = false; if (!m_identifier) { m_identifier = m_frame->page()->progress().createUniqueIdentifier(); createdResourceIdentifier = true; } #if ENABLE(CONTENT_EXTENSIONS) if (frameLoader()) { Page* page = frameLoader()->frame().page(); if (page && m_documentLoader) { auto* userContentController = page->userContentController(); if (userContentController) userContentController->processContentExtensionRulesForLoad(*page, request, m_resourceType, *m_documentLoader); } } #endif if (request.isNull()) { didFail(cannotShowURLError()); return; } if (m_options.sendLoadCallbacks() == SendCallbacks) { if (createdResourceIdentifier) frameLoader()->notifier().assignIdentifierToInitialRequest(m_identifier, documentLoader(), request); #if PLATFORM(IOS) // If this ResourceLoader was stopped as a result of assignIdentifierToInitialRequest, bail out if (m_reachedTerminalState) return; #endif frameLoader()->notifier().willSendRequest(this, request, redirectResponse); } else InspectorInstrumentation::willSendRequest(m_frame.get(), m_identifier, m_frame->loader().documentLoader(), request, redirectResponse); bool isRedirect = !redirectResponse.isNull(); if (isRedirect) platformStrategies()->loaderStrategy()->resourceLoadScheduler()->crossOriginRedirectReceived(this, request.url()); m_request = request; if (isRedirect) { auto& redirectURL = request.url(); if (!m_documentLoader->isCommitted()) frameLoader()->client().dispatchDidReceiveServerRedirectForProvisionalLoad(); if (redirectURL.protocolIsData()) { // Handle data URL decoding locally. finishNetworkLoad(); loadDataURL(); } } }
void TrackingGlue::WaitStopped() { ScopeLock protect(mutex); StandbyThread::WaitStopped(); }
bool MetaTranslator::save( const QString& filename ) const { QFile f( filename ); if ( !f.open(IO_WriteOnly) ) return FALSE; QTextStream t( &f ); t.setCodec( QTextCodec::codecForName("ISO-8859-1") ); t << "<!DOCTYPE TS><TS>\n"; if ( codecName != "ISO-8859-1" ) t << "<defaultcodec>" << codecName << "</defaultcodec>\n"; TMM::ConstIterator m = mm.begin(); while ( m != mm.end() ) { TMMInv inv; TMMInv::Iterator i; bool contextIsUtf8 = m.key().utf8(); QCString context = m.key().context(); QCString comment = ""; do { if ( QCString(m.key().sourceText()) == ContextComment ) { if ( m.key().type() != MetaTranslatorMessage::Obsolete ) { contextIsUtf8 = m.key().utf8(); comment = QCString( m.key().comment() ); } } else { inv.insert( *m, m.key() ); } } while ( ++m != mm.end() && QCString(m.key().context()) == context ); t << "<context"; if ( contextIsUtf8 ) t << " encoding=\"UTF-8\""; t << ">\n"; t << " <name>" << evilBytes( context, contextIsUtf8 ) << "</name>\n"; if ( !comment.isEmpty() ) t << " <comment>" << evilBytes( comment, contextIsUtf8 ) << "</comment>\n"; for ( i = inv.begin(); i != inv.end(); ++i ) { // no need for such noise if ( (*i).type() == MetaTranslatorMessage::Obsolete && (*i).translation().isEmpty() ) continue; t << " <message"; if ( (*i).utf8() ) t << " encoding=\"UTF-8\""; t << ">\n" << " <source>" << evilBytes( (*i).sourceText(), (*i).utf8() ) << "</source>\n"; if ( !QCString((*i).comment()).isEmpty() ) t << " <comment>" << evilBytes( (*i).comment(), (*i).utf8() ) << "</comment>\n"; t << " <translation"; if ( (*i).type() == MetaTranslatorMessage::Unfinished ) t << " type=\"unfinished\""; else if ( (*i).type() == MetaTranslatorMessage::Obsolete ) t << " type=\"obsolete\""; t << ">" << protect( (*i).translation().utf8() ) << "</translation>\n"; t << " </message>\n"; } t << "</context>\n"; } t << "</TS>\n"; f.close(); return TRUE; }
void Notification::stopLoading() { m_iconData = 0; RefPtr<ThreadableLoader> protect(m_loader); m_loader->cancel(); }
void Logger::ClearBuffer() { Poco::ScopedRWLock protect(lock, true); logger.ClearBuffer(); }
bool Logger::IsLoggerActive() const { Poco::ScopedRWLock protect(lock, false); return logger.IsActive(); }
void Logger::LoggerNote(const TCHAR *text) { Poco::ScopedRWLock protect(lock, true); logger.LoggerNote(text); }
/** * Make the current environment persistent * @param[in] filename where to store * @param[in] dirname what to store (all files in this dir) * @param[in] flags superblock flags (refer ENVFS_FLAGS_* macros) * @return 0 on success, anything else in case of failure * * Note: This function will also be used on the host! See note in the header * of this file. */ int envfs_save(const char *filename, const char *dirname, unsigned flags) { struct envfs_super *super; int envfd, size, ret; struct action_data data = {}; void *buf = NULL, *wbuf; struct envfs_entry *env; if (!filename) filename = default_environment_path_get(); if (!dirname) dirname = "/env"; data.writep = NULL; data.base = dirname; #ifdef __BAREBOX__ defaultenv_load(TMPDIR, 0); #endif if (flags & ENVFS_FLAGS_FORCE_BUILT_IN) { size = 0; /* force no content */ } else { /* first pass: calculate size */ recursive_action(dirname, ACTION_RECURSE, file_action, NULL, &data, 0); recursive_action("/.defaultenv", ACTION_RECURSE, file_remove_action, NULL, &data, 0); size = 0; for (env = data.env; env; env = env->next) { size += PAD4(env->size); size += sizeof(struct envfs_inode); size += PAD4(strlen(env->name) + 1); size += sizeof(struct envfs_inode_end); } } buf = xzalloc(size + sizeof(struct envfs_super)); data.writep = buf + sizeof(struct envfs_super); super = buf; super->magic = ENVFS_32(ENVFS_MAGIC); super->major = ENVFS_MAJOR; super->minor = ENVFS_MINOR; super->size = ENVFS_32(size); super->flags = ENVFS_32(flags); if (!(flags & ENVFS_FLAGS_FORCE_BUILT_IN)) { /* second pass: copy files to buffer */ env = data.env; while (env) { struct envfs_entry *next = env->next; envfs_save_inode(&data, env); free(env->buf); free(env->name); free(env); env = next; } } super->crc = ENVFS_32(crc32(0, buf + sizeof(struct envfs_super), size)); super->sb_crc = ENVFS_32(crc32(0, buf, sizeof(struct envfs_super) - 4)); envfd = open(filename, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR); if (envfd < 0) { printf("could not open %s: %s\n", filename, errno_str()); ret = -errno; goto out1; } ret = protect(envfd, ~0, 0, 0); /* ENOSYS and EOPNOTSUPP aren't errors here, many devices don't need it */ if (ret && errno != ENOSYS && errno != EOPNOTSUPP) { printf("could not unprotect %s: %s\n", filename, errno_str()); goto out; } ret = erase(envfd, ~0, 0); /* ENOSYS and EOPNOTSUPP aren't errors here, many devices don't need it */ if (ret && errno != ENOSYS && errno != EOPNOTSUPP) { printf("could not erase %s: %s\n", filename, errno_str()); goto out; } size += sizeof(struct envfs_super); wbuf = buf; while (size) { ssize_t now = write(envfd, wbuf, size); if (now < 0) { ret = -errno; goto out; } wbuf += now; size -= now; } ret = protect(envfd, ~0, 0, 1); /* ENOSYS and EOPNOTSUPP aren't errors here, many devices don't need it */ if (ret && errno != ENOSYS && errno != EOPNOTSUPP) { printf("could not protect %s: %s\n", filename, errno_str()); goto out; } ret = 0; out: close(envfd); out1: free(buf); #ifdef __BAREBOX__ unlink_recursive(TMPDIR, NULL); #endif return ret; }
bool DeviceDescriptor::IsAlive() const { ScopeLock protect(device_blackboard->mutex); return device_blackboard->RealState(index).alive; }
void PluginStream::destroyStream() { if (m_streamState == StreamStopped) return; ASSERT(m_reason != WebReasonNone); ASSERT(!m_deliveryData || m_deliveryData->size() == 0); closeFile(m_tempFileHandle); bool newStreamCalled = m_stream.ndata; // Protect from destruction if: // NPN_DestroyStream is called from NPP_NewStream or // PluginStreamClient::streamDidFinishLoading() removes the last reference RefPtr<PluginStream> protect(this); if (newStreamCalled) { if (m_reason == NPRES_DONE && (m_transferMode == NP_ASFILE || m_transferMode == NP_ASFILEONLY)) { ASSERT(!m_path.isNull()); if (m_loader) m_loader->setDefersLoading(true); m_pluginFuncs->asfile(m_instance, &m_stream, m_path.utf8().data()); if (m_loader) m_loader->setDefersLoading(false); } if (m_streamState != StreamBeforeStarted) { if (m_loader) m_loader->setDefersLoading(true); NPError npErr = m_pluginFuncs->destroystream(m_instance, &m_stream, m_reason); if (m_loader) m_loader->setDefersLoading(false); LOG_NPERROR(npErr); } m_stream.ndata = 0; } if (m_sendNotification) { // Flash 9 can dereference null if we call NPP_URLNotify without first calling NPP_NewStream // for requests made with NPN_PostURLNotify; see <rdar://5588807> if (m_loader) m_loader->setDefersLoading(true); if (!newStreamCalled && m_quirks.contains(PluginQuirkFlashURLNotifyBug) && equalIgnoringCase(m_resourceRequest.httpMethod(), "POST")) { m_transferMode = NP_NORMAL; m_stream.url = ""; m_stream.notifyData = m_notifyData; static char emptyMimeType[] = ""; m_pluginFuncs->newstream(m_instance, emptyMimeType, &m_stream, false, &m_transferMode); m_pluginFuncs->destroystream(m_instance, &m_stream, m_reason); // in successful requests, the URL is dynamically allocated and freed in our // destructor, so reset it to 0 m_stream.url = 0; } m_pluginFuncs->urlnotify(m_instance, m_resourceRequest.url().string().utf8().data(), m_reason, m_notifyData); if (m_loader) m_loader->setDefersLoading(false); } m_streamState = StreamStopped; if (!m_loadManually && m_client) m_client->streamDidFinishLoading(this); if (!m_path.isNull()) deleteFile(m_path); }
unsigned RasterWeather::GetParameter() const { Poco::ScopedRWLock protect(lock, false); return _parameter; }
QString JavaCodeMarker::markedUpEnumValue(const QString &enumValue, const Node * /* relative */) { return protect(enumValue); }
unsigned RasterWeather::GetTime() const { Poco::ScopedRWLock protect(lock, false); return _weather_time; }
void TrackingGlue::StopAsync() { ScopeLock protect(mutex); StandbyThread::StopAsync(); }
void RasterWeather::Close() { Poco::ScopedRWLock protect(lock, true); _Close(); }
/** * Returns the current value of the flag. */ gcc_pure bool Get() const { ScopeLock protect(mutex); return value; }
void ResourceLoader::didSendData(blink::WebURLLoader*, unsigned long long bytesSent, unsigned long long totalBytesToBeSent) { ASSERT(m_state == Initialized); RefPtr<ResourceLoader> protect(this); m_resource->didSendData(bytesSent, totalBytesToBeSent); }
/** * Set a new value for the flag. */ void Set(bool _value=true) { ScopeLock protect(mutex); value = _value; }
void ResourceLoader::didReceiveResponse(blink::WebURLLoader*, const blink::WebURLResponse& response) { ASSERT(!response.isNull()); ASSERT(m_state == Initialized); bool isMultipartPayload = response.isMultipartPayload(); bool isValidStateTransition = (m_connectionState == ConnectionStateStarted || m_connectionState == ConnectionStateReceivedResponse); // In the case of multipart loads, calls to didReceiveData & didReceiveResponse can be interleaved. RELEASE_ASSERT(isMultipartPayload || isValidStateTransition); m_connectionState = ConnectionStateReceivedResponse; const ResourceResponse& resourceResponse = response.toResourceResponse(); if (responseNeedsAccessControlCheck()) { // If the response successfully validated a cached resource, perform // the access control with respect to it. Need to do this right here // before the resource switches clients over to that validated resource. Resource* resource = m_resource; if (resource->isCacheValidator() && resourceResponse.httpStatusCode() == 304) resource = m_resource->resourceToRevalidate(); else m_resource->setResponse(resourceResponse); if (!m_host->canAccessResource(resource, m_options.securityOrigin.get(), response.url())) { cancel(); return; } } // Reference the object in this method since the additional processing can do // anything including removing the last reference to this object. RefPtr<ResourceLoader> protect(this); m_resource->responseReceived(resourceResponse); if (m_state == Terminated) return; m_host->didReceiveResponse(m_resource, resourceResponse); if (response.toResourceResponse().isMultipart()) { // We don't count multiParts in a ResourceFetcher's request count m_requestCountTracker.clear(); if (!m_resource->isImage()) { cancel(); return; } } else if (isMultipartPayload) { // Since a subresource loader does not load multipart sections progressively, data was delivered to the loader all at once. // After the first multipart section is complete, signal to delegates that this load is "finished" m_host->subresourceLoaderFinishedLoadingOnePart(this); didFinishLoadingOnePart(0, blink::WebURLLoaderClient::kUnknownEncodedDataLength); } if (m_resource->response().httpStatusCode() < 400 || m_resource->shouldIgnoreHTTPStatusCodeErrors()) return; m_state = Finishing; if (!m_notifiedLoadComplete) { m_notifiedLoadComplete = true; m_host->didFailLoading(m_resource, ResourceError::cancelledError(m_request.url())); } m_resource->error(Resource::LoadError); cancel(); }
bool ResourceLoader::canAuthenticateAgainstProtectionSpace(const ProtectionSpace& protectionSpace) { Ref<ResourceLoader> protect(*this); return frameLoader()->client().canAuthenticateAgainstProtectionSpace(documentLoader(), identifier(), protectionSpace); }
void DoubleBufferWindow::OnPaint(Canvas &canvas) { ScopeLock protect(mutex); canvas.Copy(GetVisibleCanvas()); }
QString QsCodeMarker::markedUpSynopsis( const Node *node, const Node * /* relative */, SynopsisStyle style ) { QString synopsis; QStringList extras; QString name; name = taggedNode( node ); if ( style != Detailed ) name = linkTag( node, name ); name = "<@name>" + name + "</@name>"; if ( style == Detailed && !node->parent()->name().isEmpty() && node->type() != Node::Enum ) name.prepend( taggedNode(node->parent()) + "." ); switch ( node->type() ) { case Node::Class: synopsis = "class " + name; break; case Node::Function: { const FunctionNode *func = (const FunctionNode *) node; synopsis = name; if ( style == SeparateList ) { synopsis += "()"; } else { synopsis += " ("; if ( !func->parameters().isEmpty() ) { synopsis += " "; int numOptional = 0; QList<Parameter>::ConstIterator p = func->parameters().begin(); while ( p != func->parameters().end() ) { if ( !(*p).defaultValue().isEmpty() ) { if ( p == func->parameters().begin() ) { synopsis += "[ "; } else { synopsis += " [ , "; } numOptional++; } else { if ( p != func->parameters().begin() ) synopsis += ", "; } if ( !(*p).name().isEmpty() ) synopsis += "<@param>" + protect( (*p).name() ) + "</@param> : "; synopsis += protect( (*p).leftType() ); ++p; } for ( int i = 0; i < numOptional; i++ ) synopsis += " ]"; synopsis += " "; } synopsis += ")"; } if ( style != SeparateList && !func->returnType().isEmpty() ) synopsis += " : " + protect( func->returnType() ); if ( style == Detailed && func->metaness() == FunctionNode::Signal ) extras << "[signal]"; } break; case Node::Property: { const PropertyNode *property = (const PropertyNode *) node; synopsis = name; if ( style != SeparateList ) synopsis += " : " + property->dataType(); if ( style == Detailed && property->setters().isEmpty() ) extras << "[read only]"; } break; case Node::Enum: { /* The letters A to F and X (upper- and lower-case) can appear in a hexadecimal constant (e.g. 0x3F). */ QRegExp letterRegExp( "[G-WYZg-wyz_]" ); const EnumNode *enume = (const EnumNode *) node; synopsis = name; if ( style == Summary && !enume->items().isEmpty() ) { synopsis += " : "; QString comma; QList<EnumItem>::ConstIterator it = enume->items().begin(); while ( it != enume->items().end() ) { if ( enume->itemAccess((*it).name()) == Node::Public ) { synopsis += comma; synopsis += (*it).name(); if ( (*it).value().indexOf(letterRegExp) != -1 ) synopsis += " = " + (*it).value(); comma = ", "; } ++it; } } } break; case Node::Namespace: case Node::Typedef: default: synopsis = name; } if ( style == Summary ) { if ( node->status() == Node::Preliminary ) { extras << "(preliminary)"; } else if ( node->status() == Node::Deprecated ) { extras << "(deprecated)"; } else if ( node->status() == Node::Obsolete ) { extras << "(obsolete)"; } } QString extra; if ( !extras.isEmpty() ) extra = "<@extra>" + extras.join(" ") + "</@extra>"; return synopsis + extra; }
void PluginStream::startStream() { ASSERT(m_streamState == StreamBeforeStarted); const KURL& responseURL = m_resourceResponse.url(); // Some plugins (Flash) expect that javascript URLs are passed back decoded as this is the // format used when requesting the URL. if (protocolIsJavaScript(responseURL)) m_stream.url = fastStrDup(decodeURLEscapeSequences(responseURL.string()).utf8().data()); else m_stream.url = fastStrDup(responseURL.string().utf8().data()); CString mimeTypeStr = m_resourceResponse.mimeType().utf8(); long long expectedContentLength = m_resourceResponse.expectedContentLength(); if (m_resourceResponse.isHTTP()) { Vector<UChar> stringBuilder; String separator(": "); String statusLine = makeString("HTTP ", String::number(m_resourceResponse.httpStatusCode()), " OK\n"); stringBuilder.append(statusLine.characters(), statusLine.length()); HTTPHeaderMap::const_iterator end = m_resourceResponse.httpHeaderFields().end(); for (HTTPHeaderMap::const_iterator it = m_resourceResponse.httpHeaderFields().begin(); it != end; ++it) { stringBuilder.append(it->first.characters(), it->first.length()); stringBuilder.append(separator.characters(), separator.length()); stringBuilder.append(it->second.characters(), it->second.length()); stringBuilder.append('\n'); } m_headers = String::adopt(stringBuilder).utf8(); // If the content is encoded (most likely compressed), then don't send its length to the plugin, // which is only interested in the decoded length, not yet known at the moment. // <rdar://problem/4470599> tracks a request for -[NSURLResponse expectedContentLength] to incorporate this logic. String contentEncoding = m_resourceResponse.httpHeaderField("Content-Encoding"); if (!contentEncoding.isNull() && contentEncoding != "identity") expectedContentLength = -1; } m_stream.headers = m_headers.data(); m_stream.pdata = 0; m_stream.ndata = this; m_stream.end = max(expectedContentLength, 0LL); m_stream.lastmodified = m_resourceResponse.lastModifiedDate(); m_stream.notifyData = m_notifyData; m_transferMode = NP_NORMAL; m_offset = 0; m_reason = WebReasonNone; // Protect the stream if destroystream is called from within the newstream handler RefPtr<PluginStream> protect(this); // calling into a plug-in could result in re-entrance if the plug-in yields // control to the system (rdar://5744899). prevent this by deferring further // loading while calling into the plug-in. if (m_loader) m_loader->setDefersLoading(true); NPError npErr = m_pluginFuncs->newstream(m_instance, (NPMIMEType)mimeTypeStr.data(), &m_stream, false, &m_transferMode); if (m_loader) m_loader->setDefersLoading(false); // If the stream was destroyed in the call to newstream we return if (m_reason != WebReasonNone) return; if (npErr != NPERR_NO_ERROR) { cancelAndDestroyStream(npErr); return; } m_streamState = StreamStarted; if (m_transferMode == NP_NORMAL) return; m_path = openTemporaryFile("WKP", m_tempFileHandle); // Something went wrong, cancel loading the stream if (!isHandleValid(m_tempFileHandle)) cancelAndDestroyStream(NPRES_NETWORK_ERR); }
void MainResourceLoader::continueAfterContentPolicy(PolicyAction contentPolicy, const ResourceResponse& r) { KURL url = request().url(); const String& mimeType = r.mimeType(); switch (contentPolicy) { case PolicyUse: { // Prevent remote web archives from loading because they can claim to be from any domain and thus avoid cross-domain security checks (4120255). bool isRemoteWebArchive = equalIgnoringCase("application/x-webarchive", mimeType) && !m_substituteData.isValid() && !url.isLocalFile(); if (!frameLoader()->canShowMIMEType(mimeType) || isRemoteWebArchive) { frameLoader()->policyChecker()->cannotShowMIMEType(r); // Check reachedTerminalState since the load may have already been cancelled inside of _handleUnimplementablePolicyWithErrorCode::. if (!reachedTerminalState()) stopLoadingForPolicyChange(); return; } break; } case PolicyDownload: // m_handle can be null, e.g. when loading a substitute resource from application cache. if (!m_handle) { receivedError(cannotShowURLError()); return; } frameLoader()->client()->download(m_handle.get(), request(), m_handle.get()->request(), r); // It might have gone missing if (frameLoader()) receivedError(interruptionForPolicyChangeError()); return; case PolicyIgnore: stopLoadingForPolicyChange(); return; default: ASSERT_NOT_REACHED(); } RefPtr<MainResourceLoader> protect(this); if (r.isHTTP()) { int status = r.httpStatusCode(); if (status < 200 || status >= 300) { bool hostedByObject = frameLoader()->isHostedByObjectElement(); frameLoader()->handleFallbackContent(); // object elements are no longer rendered after we fallback, so don't // keep trying to process data from their load if (hostedByObject) cancel(); } } // we may have cancelled this load as part of switching to fallback content if (!reachedTerminalState()) ResourceLoader::didReceiveResponse(r); if (frameLoader() && !frameLoader()->isStopping()) { if (m_substituteData.isValid()) { if (m_substituteData.content()->size()) didReceiveData(m_substituteData.content()->data(), m_substituteData.content()->size(), m_substituteData.content()->size(), true); if (frameLoader() && !frameLoader()->isStopping()) didFinishLoading(); } else if (shouldLoadAsEmptyDocument(url) || frameLoader()->representationExistsForURLScheme(url.protocol())) didFinishLoading(); } }
void JSEventListener::handleEvent(ScriptExecutionContext* scriptExecutionContext, Event* event) { ASSERT(scriptExecutionContext); if (!scriptExecutionContext || scriptExecutionContext->isJSExecutionForbidden()) return; JSLock lock(SilenceAssertionsOnly); JSObject* jsFunction = this->jsFunction(scriptExecutionContext); if (!jsFunction) return; JSDOMGlobalObject* globalObject = toJSDOMGlobalObject(scriptExecutionContext, m_isolatedWorld.get()); if (!globalObject) return; if (scriptExecutionContext->isDocument()) { JSDOMWindow* window = static_cast<JSDOMWindow*>(globalObject); Frame* frame = window->impl()->frame(); if (!frame) return; // The window must still be active in its frame. See <https://bugs.webkit.org/show_bug.cgi?id=21921>. // FIXME: A better fix for this may be to change DOMWindow::frame() to not return a frame the detached window used to be in. if (frame->domWindow() != window->impl()) return; // FIXME: Is this check needed for other contexts? ScriptController* script = frame->script(); if (!script->canExecuteScripts(AboutToExecuteScript) || script->isPaused()) return; } ExecState* exec = globalObject->globalExec(); JSValue handleEventFunction = jsFunction; CallData callData; CallType callType = getCallData(handleEventFunction, callData); // If jsFunction is not actually a function, see if it implements the EventListener interface and use that if (callType == CallTypeNone) { handleEventFunction = jsFunction->get(exec, Identifier(exec, "handleEvent")); callType = getCallData(handleEventFunction, callData); } if (callType != CallTypeNone) { RefPtr<JSEventListener> protect(this); MarkedArgumentBuffer args; args.append(toJS(exec, globalObject, event)); Event* savedEvent = globalObject->currentEvent(); globalObject->setCurrentEvent(event); JSGlobalData& globalData = globalObject->globalData(); DynamicGlobalObjectScope globalObjectScope(globalData, globalData.dynamicGlobalObject ? globalData.dynamicGlobalObject : globalObject); globalData.timeoutChecker.start(); JSValue thisValue = handleEventFunction == jsFunction ? toJS(exec, globalObject, event->currentTarget()) : jsFunction; JSValue retval = scriptExecutionContext->isDocument() ? JSMainThreadExecState::call(exec, handleEventFunction, callType, callData, thisValue, args) : JSC::call(exec, handleEventFunction, callType, callData, thisValue, args); globalData.timeoutChecker.stop(); globalObject->setCurrentEvent(savedEvent); #if ENABLE(WORKERS) if (scriptExecutionContext->isWorkerContext()) { bool terminatorCausedException = (exec->hadException() && isTerminatedExecutionException(exec->exception())); if (terminatorCausedException || globalData.terminator.shouldTerminate()) static_cast<WorkerContext*>(scriptExecutionContext)->script()->forbidExecution(); } #endif if (exec->hadException()) { event->target()->uncaughtExceptionInEventHandler(); reportCurrentException(exec); } else { if (!retval.isUndefinedOrNull() && event->storesResultAsString()) event->storeResult(ustringToString(retval.toString(exec)->value(exec))); if (m_isAttribute) { if (retval.isFalse()) event->preventDefault(); } } } }