This source file includes following definitions.
- resource_client_
- willSendRequest
- didSendData
- didReceiveResponse
- didReceiveData
- didFinishLoading
- didFail
- visitHeader
- GetAllHeaders
- GetResponseInfo
- initialize
- destroy
- scriptableObject
- pluginNPP
- getFormValue
- paint
- updateGeometry
- updateFocus
- updateVisibility
- acceptsInputEvents
- handleInputEvent
- didReceiveResponse
- didReceiveData
- didFinishLoading
- didFailLoading
- didFinishLoadingFrameRequest
- didFailLoadingFrameRequest
- isPlaceholder
- willSendRequest
- didSendData
- didReceiveResponse
- didDownloadData
- didReceiveData
- didReceiveCachedMetadata
- didFinishLoading
- didFail
- loader_client_
- SetWindow
- SetAcceptsInputEvents
- WillDestroyWindow
- CompleteURL
- CancelResource
- SetPostData
- IsValidUrl
- RouteToFrame
- GetWindowScriptNPObject
- GetPluginElement
- FindProxyForUrl
- SetCookie
- GetCookies
- URLRedirectResponse
- CheckIfRunInsecureContent
- GetAcceleratedSurface
- AcceleratedPluginEnabledRendering
- AcceleratedPluginAllocatedIOSurface
- AcceleratedPluginSwappedIOSurface
- Invalidate
- InvalidateRect
- OnDownloadPluginSrcUrl
- GetClientFromLoader
- GetClientInfoFromLoader
- willSendRequest
- didSendData
- didReceiveResponse
- didReceiveData
- didFinishLoading
- didFail
- RemoveClient
- RemoveClient
- SetContainer
- HandleURLRequest
- HandleURLRequestInternal
- GetNextResourceId
- InitiateHTTPRequest
- CancelDocumentLoad
- InitiateHTTPRangeRequest
- DidStartLoading
- DidStopLoading
- SetDeferResourceLoading
- IsOffTheRecord
- HandleHttpMultipartResponse
- ReinitializePluginForResponse
- TearDownPluginInstance
- SetReferrer
#include "content/renderer/npapi/webplugin_impl.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/debug/crash_logging.h"
#include "base/logging.h"
#include "base/memory/linked_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/user_metrics_action.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "cc/layers/io_surface_layer.h"
#include "content/child/appcache/web_application_cache_host_impl.h"
#include "content/child/npapi/plugin_host.h"
#include "content/child/npapi/plugin_instance.h"
#include "content/child/npapi/webplugin_delegate_impl.h"
#include "content/child/npapi/webplugin_resource_client.h"
#include "content/common/view_messages.h"
#include "content/public/common/content_constants.h"
#include "content/public/common/content_switches.h"
#include "content/public/renderer/content_renderer_client.h"
#include "content/renderer/npapi/webplugin_delegate_proxy.h"
#include "content/renderer/render_frame_impl.h"
#include "content/renderer/render_process.h"
#include "content/renderer/render_thread_impl.h"
#include "content/renderer/render_view_impl.h"
#include "net/base/escape.h"
#include "net/base/net_errors.h"
#include "net/http/http_response_headers.h"
#include "skia/ext/platform_canvas.h"
#include "third_party/WebKit/public/platform/WebCString.h"
#include "third_party/WebKit/public/platform/WebCookieJar.h"
#include "third_party/WebKit/public/platform/WebCursorInfo.h"
#include "third_party/WebKit/public/platform/WebData.h"
#include "third_party/WebKit/public/platform/WebHTTPBody.h"
#include "third_party/WebKit/public/platform/WebHTTPHeaderVisitor.h"
#include "third_party/WebKit/public/platform/WebURL.h"
#include "third_party/WebKit/public/platform/WebURLError.h"
#include "third_party/WebKit/public/platform/WebURLLoader.h"
#include "third_party/WebKit/public/platform/WebURLLoaderClient.h"
#include "third_party/WebKit/public/platform/WebURLResponse.h"
#include "third_party/WebKit/public/web/WebConsoleMessage.h"
#include "third_party/WebKit/public/web/WebDocument.h"
#include "third_party/WebKit/public/web/WebFrame.h"
#include "third_party/WebKit/public/web/WebInputEvent.h"
#include "third_party/WebKit/public/web/WebKit.h"
#include "third_party/WebKit/public/web/WebPluginContainer.h"
#include "third_party/WebKit/public/web/WebPluginParams.h"
#include "third_party/WebKit/public/web/WebURLLoaderOptions.h"
#include "third_party/WebKit/public/web/WebView.h"
#include "ui/gfx/rect.h"
#include "url/gurl.h"
#include "url/url_util.h"
#include "webkit/child/multipart_response_delegate.h"
#include "webkit/renderer/compositor_bindings/web_layer_impl.h"
using blink::WebCanvas;
using blink::WebConsoleMessage;
using blink::WebCookieJar;
using blink::WebCString;
using blink::WebCursorInfo;
using blink::WebData;
using blink::WebDataSource;
using blink::WebFrame;
using blink::WebHTTPBody;
using blink::WebHTTPHeaderVisitor;
using blink::WebInputEvent;
using blink::WebKeyboardEvent;
using blink::WebMouseEvent;
using blink::WebPluginContainer;
using blink::WebPluginParams;
using blink::WebRect;
using blink::WebString;
using blink::WebURL;
using blink::WebURLError;
using blink::WebURLLoader;
using blink::WebURLLoaderClient;
using blink::WebURLLoaderOptions;
using blink::WebURLRequest;
using blink::WebURLResponse;
using blink::WebVector;
using blink::WebView;
using webkit_glue::MultipartResponseDelegate;
namespace content {
namespace {
class MultiPartResponseClient : public WebURLLoaderClient {
public:
explicit MultiPartResponseClient(WebPluginResourceClient* resource_client)
: byte_range_lower_bound_(0), resource_client_(resource_client) {}
virtual void willSendRequest(
WebURLLoader*, WebURLRequest&, const WebURLResponse&) {}
virtual void didSendData(
WebURLLoader*, unsigned long long, unsigned long long) {}
virtual void didReceiveResponse(
WebURLLoader*, const WebURLResponse& response) {
int64 byte_range_upper_bound, instance_size;
if (!MultipartResponseDelegate::ReadContentRanges(
response,
&byte_range_lower_bound_,
&byte_range_upper_bound,
&instance_size)) {
NOTREACHED();
}
}
virtual void didReceiveData(WebURLLoader*,
const char* data,
int data_length,
int encoded_data_length) {
resource_client_->DidReceiveData(
data, data_length, byte_range_lower_bound_);
byte_range_lower_bound_ += data_length;
}
virtual void didFinishLoading(WebURLLoader*,
double finishTime,
int64_t total_encoded_data_length) {}
virtual void didFail(WebURLLoader*, const WebURLError&) {}
private:
int64 byte_range_lower_bound_;
WebPluginResourceClient* resource_client_;
};
class HeaderFlattener : public WebHTTPHeaderVisitor {
public:
explicit HeaderFlattener(std::string* buf) : buf_(buf) {
}
virtual void visitHeader(const WebString& name, const WebString& value) {
if (!name.isEmpty() && !value.isEmpty()) {
buf_->append(name.utf8());
buf_->append(": ");
buf_->append(value.utf8());
buf_->append("\n");
}
}
private:
std::string* buf_;
};
std::string GetAllHeaders(const WebURLResponse& response) {
std::string result;
const WebString& status = response.httpStatusText();
if (status.isEmpty())
return result;
result = base::StringPrintf("HTTP %d ", response.httpStatusCode());
result.append(status.utf8());
result.append("\n");
HeaderFlattener flattener(&result);
response.visitHTTPHeaderFields(&flattener);
return result;
}
struct ResponseInfo {
GURL url;
std::string mime_type;
uint32 last_modified;
uint32 expected_length;
};
void GetResponseInfo(const WebURLResponse& response,
ResponseInfo* response_info) {
response_info->url = response.url();
response_info->mime_type = response.mimeType().utf8();
response_info->last_modified =
static_cast<uint32>(response.lastModifiedDate());
response_info->expected_length =
static_cast<uint32>(std::max(response.expectedContentLength(), 0LL));
WebString content_encoding =
response.httpHeaderField(WebString::fromUTF8("Content-Encoding"));
if (!content_encoding.isNull() &&
!EqualsASCII(content_encoding, "identity")) {
response_info->expected_length = 0;
}
}
}
struct WebPluginImpl::ClientInfo {
unsigned long id;
WebPluginResourceClient* client;
blink::WebURLRequest request;
bool pending_failure_notification;
linked_ptr<blink::WebURLLoader> loader;
bool notify_redirects;
bool is_plugin_src_load;
int64 data_offset;
};
bool WebPluginImpl::initialize(WebPluginContainer* container) {
if (!render_view_.get()) {
LOG(ERROR) << "No RenderView";
return false;
}
WebPluginDelegateProxy* plugin_delegate = new WebPluginDelegateProxy(
this, mime_type_, render_view_, render_frame_);
npp_ = plugin_delegate->GetPluginNPP();
SetContainer(container);
bool ok = plugin_delegate->Initialize(
plugin_url_, arg_names_, arg_values_, load_manually_);
if (!ok) {
plugin_delegate->PluginDestroyed();
blink::WebPlugin* replacement_plugin =
GetContentClient()->renderer()->CreatePluginReplacement(
render_frame_, file_path_);
if (!replacement_plugin)
return false;
destroy();
container->setPlugin(replacement_plugin);
return replacement_plugin->initialize(container);
}
delegate_ = plugin_delegate;
return true;
}
void WebPluginImpl::destroy() {
SetContainer(NULL);
base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
}
NPObject* WebPluginImpl::scriptableObject() {
if (!delegate_)
return NULL;
return delegate_->GetPluginScriptableObject();
}
NPP WebPluginImpl::pluginNPP() {
return npp_;
}
bool WebPluginImpl::getFormValue(blink::WebString& value) {
if (!delegate_)
return false;
base::string16 form_value;
if (!delegate_->GetFormValue(&form_value))
return false;
value = form_value;
return true;
}
void WebPluginImpl::paint(WebCanvas* canvas, const WebRect& paint_rect) {
if (!delegate_ || !container_)
return;
#if defined(OS_WIN)
container_->reportGeometry();
#endif
delegate_->Paint(canvas, paint_rect);
}
void WebPluginImpl::updateGeometry(
const WebRect& window_rect, const WebRect& clip_rect,
const WebVector<WebRect>& cutout_rects, bool is_visible) {
WebPluginGeometry new_geometry;
new_geometry.window = window_;
new_geometry.window_rect = window_rect;
new_geometry.clip_rect = clip_rect;
new_geometry.visible = is_visible;
new_geometry.rects_valid = true;
for (size_t i = 0; i < cutout_rects.size(); ++i)
new_geometry.cutout_rects.push_back(cutout_rects[i]);
if (window_ && (first_geometry_update_ || !new_geometry.Equals(geometry_))) {
render_frame_->GetRenderWidget()->SchedulePluginMove(new_geometry);
if (first_geometry_update_ && window_) {
InvalidateRect(window_rect);
}
}
if (delegate_ && (first_geometry_update_ ||
new_geometry.window_rect != geometry_.window_rect ||
new_geometry.clip_rect != geometry_.clip_rect)) {
delegate_->UpdateGeometry(new_geometry.window_rect, new_geometry.clip_rect);
}
if (first_geometry_update_) {
if (!load_manually_ && plugin_url_.is_valid()) {
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&WebPluginImpl::OnDownloadPluginSrcUrl,
weak_factory_.GetWeakPtr()));
}
}
#if defined(OS_WIN)
if (!first_geometry_update_)
geometry_ = new_geometry;
#else
geometry_ = new_geometry;
#endif
first_geometry_update_ = false;
}
void WebPluginImpl::updateFocus(bool focused) {
if (accepts_input_events_)
delegate_->SetFocus(focused);
}
void WebPluginImpl::updateVisibility(bool visible) {
if (!window_)
return;
WebPluginGeometry move;
move.window = window_;
move.window_rect = gfx::Rect();
move.clip_rect = gfx::Rect();
move.rects_valid = false;
move.visible = visible;
render_frame_->GetRenderWidget()->SchedulePluginMove(move);
}
bool WebPluginImpl::acceptsInputEvents() {
return accepts_input_events_;
}
bool WebPluginImpl::handleInputEvent(
const WebInputEvent& event, WebCursorInfo& cursor_info) {
if (event.type == WebInputEvent::ContextMenu)
return true;
WebCursor::CursorInfo web_cursor_info;
bool ret = delegate_->HandleInputEvent(event, &web_cursor_info);
cursor_info.type = web_cursor_info.type;
cursor_info.hotSpot = web_cursor_info.hotspot;
cursor_info.customImage = web_cursor_info.custom_image;
cursor_info.imageScaleFactor = web_cursor_info.image_scale_factor;
#if defined(OS_WIN)
cursor_info.externalHandle = web_cursor_info.external_handle;
#endif
return ret;
}
void WebPluginImpl::didReceiveResponse(const WebURLResponse& response) {
ignore_response_error_ = false;
ResponseInfo response_info;
GetResponseInfo(response, &response_info);
delegate_->DidReceiveManualResponse(
response_info.url,
response_info.mime_type,
GetAllHeaders(response),
response_info.expected_length,
response_info.last_modified);
}
void WebPluginImpl::didReceiveData(const char* data, int data_length) {
delegate_->DidReceiveManualData(data, data_length);
}
void WebPluginImpl::didFinishLoading() {
delegate_->DidFinishManualLoading();
}
void WebPluginImpl::didFailLoading(const WebURLError& error) {
if (!ignore_response_error_)
delegate_->DidManualLoadFail();
}
void WebPluginImpl::didFinishLoadingFrameRequest(
const WebURL& url, void* notify_data) {
if (delegate_) {
delegate_->DidFinishLoadWithReason(
url, NPRES_DONE, reinterpret_cast<intptr_t>(notify_data));
}
}
void WebPluginImpl::didFailLoadingFrameRequest(
const WebURL& url, void* notify_data, const WebURLError& error) {
if (!delegate_)
return;
NPReason reason =
error.reason == net::ERR_ABORTED ? NPRES_USER_BREAK : NPRES_NETWORK_ERR;
delegate_->DidFinishLoadWithReason(
url, reason, reinterpret_cast<intptr_t>(notify_data));
}
bool WebPluginImpl::isPlaceholder() {
return false;
}
WebPluginImpl::LoaderClient::LoaderClient(WebPluginImpl* parent)
: parent_(parent) {}
void WebPluginImpl::LoaderClient::willSendRequest(
blink::WebURLLoader* loader, blink::WebURLRequest& newRequest,
const blink::WebURLResponse& redirectResponse) {
parent_->willSendRequest(loader, newRequest, redirectResponse);
}
void WebPluginImpl::LoaderClient::didSendData(
blink::WebURLLoader* loader, unsigned long long bytesSent,
unsigned long long totalBytesToBeSent) {
parent_->didSendData(loader, bytesSent, totalBytesToBeSent);
}
void WebPluginImpl::LoaderClient::didReceiveResponse(
blink::WebURLLoader* loader, const blink::WebURLResponse& response) {
parent_->didReceiveResponse(loader, response);
}
void WebPluginImpl::LoaderClient::didDownloadData(
blink::WebURLLoader* loader, int dataLength, int encodedDataLength) {
}
void WebPluginImpl::LoaderClient::didReceiveData(
blink::WebURLLoader* loader, const char* data,
int dataLength, int encodedDataLength) {
parent_->didReceiveData(loader, data, dataLength, encodedDataLength);
}
void WebPluginImpl::LoaderClient::didReceiveCachedMetadata(
blink::WebURLLoader* loader, const char* data, int dataLength) {
}
void WebPluginImpl::LoaderClient::didFinishLoading(
blink::WebURLLoader* loader, double finishTime,
int64_t total_encoded_data_length) {
parent_->didFinishLoading(loader, finishTime);
}
void WebPluginImpl::LoaderClient::didFail(
blink::WebURLLoader* loader, const blink::WebURLError& error) {
parent_->didFail(loader, error);
}
WebPluginImpl::WebPluginImpl(
WebFrame* webframe,
const WebPluginParams& params,
const base::FilePath& file_path,
const base::WeakPtr<RenderViewImpl>& render_view,
RenderFrameImpl* render_frame)
: windowless_(false),
window_(gfx::kNullPluginWindow),
accepts_input_events_(false),
render_frame_(render_frame),
render_view_(render_view),
webframe_(webframe),
delegate_(NULL),
container_(NULL),
npp_(NULL),
plugin_url_(params.url),
load_manually_(params.loadManually),
first_geometry_update_(true),
ignore_response_error_(false),
file_path_(file_path),
mime_type_(base::UTF16ToASCII(params.mimeType)),
weak_factory_(this),
loader_client_(this) {
DCHECK_EQ(params.attributeNames.size(), params.attributeValues.size());
StringToLowerASCII(&mime_type_);
for (size_t i = 0; i < params.attributeNames.size(); ++i) {
arg_names_.push_back(params.attributeNames[i].utf8());
arg_values_.push_back(params.attributeValues[i].utf8());
}
base::debug::SetCrashKeyValue("subresource_url", plugin_url_.spec());
}
WebPluginImpl::~WebPluginImpl() {
}
void WebPluginImpl::SetWindow(gfx::PluginWindowHandle window) {
if (window) {
DCHECK(!windowless_);
window_ = window;
#if defined(OS_MACOSX)
windowless_ = true;
accepts_input_events_ = true;
#else
accepts_input_events_ = false;
#if defined(USE_X11)
render_frame_->Send(new ViewHostMsg_CreatePluginContainer(
render_frame_->GetRenderWidget()->routing_id(), window));
#endif
#endif
} else {
DCHECK(!window_);
windowless_ = true;
accepts_input_events_ = true;
}
}
void WebPluginImpl::SetAcceptsInputEvents(bool accepts) {
accepts_input_events_ = accepts;
}
void WebPluginImpl::WillDestroyWindow(gfx::PluginWindowHandle window) {
DCHECK_EQ(window, window_);
window_ = gfx::kNullPluginWindow;
if (render_view_.get()) {
#if defined(USE_X11)
render_frame_->Send(new ViewHostMsg_DestroyPluginContainer(
render_frame_->GetRenderWidget()->routing_id(), window));
#endif
render_frame_->GetRenderWidget()->CleanupWindowInPluginMoves(window);
}
}
GURL WebPluginImpl::CompleteURL(const char* url) {
if (!webframe_) {
NOTREACHED();
return GURL();
}
return webframe_->document().completeURL(WebString::fromUTF8(url));
}
void WebPluginImpl::CancelResource(unsigned long id) {
for (size_t i = 0; i < clients_.size(); ++i) {
if (clients_[i].id == id) {
if (clients_[i].loader.get()) {
clients_[i].loader->setDefersLoading(false);
clients_[i].loader->cancel();
RemoveClient(i);
}
return;
}
}
}
bool WebPluginImpl::SetPostData(WebURLRequest* request,
const char *buf,
uint32 length) {
std::vector<std::string> names;
std::vector<std::string> values;
std::vector<char> body;
bool rv = PluginHost::SetPostData(buf, length, &names, &values, &body);
for (size_t i = 0; i < names.size(); ++i) {
request->addHTTPHeaderField(WebString::fromUTF8(names[i]),
WebString::fromUTF8(values[i]));
}
WebString content_type_header = WebString::fromUTF8("Content-Type");
const WebString& content_type =
request->httpHeaderField(content_type_header);
if (content_type.isEmpty()) {
request->setHTTPHeaderField(
content_type_header,
WebString::fromUTF8("application/x-www-form-urlencoded"));
}
WebHTTPBody http_body;
if (body.size()) {
http_body.initialize();
http_body.appendData(WebData(&body[0], body.size()));
}
request->setHTTPBody(http_body);
return rv;
}
bool WebPluginImpl::IsValidUrl(const GURL& url, Referrer referrer_flag) {
if (referrer_flag == PLUGIN_SRC &&
mime_type_ == kFlashPluginSwfMimeType &&
url.GetOrigin() != plugin_url_.GetOrigin()) {
const char* url_to_check(url.spec().data());
url_parse::Parsed parsed;
url_parse::ParseStandardURL(url_to_check, strlen(url_to_check), &parsed);
if (parsed.path.begin <= parsed.scheme.end())
return true;
std::string string_to_search;
string_to_search.assign(url_to_check + parsed.scheme.end(),
parsed.path.begin - parsed.scheme.end());
if (string_to_search.find("@") != std::string::npos ||
string_to_search.find(";") != std::string::npos ||
string_to_search.find("\\") != std::string::npos)
return false;
}
return true;
}
WebPluginImpl::RoutingStatus WebPluginImpl::RouteToFrame(
const char* url,
bool is_javascript_url,
bool popups_allowed,
const char* method,
const char* target,
const char* buf,
unsigned int len,
int notify_id,
Referrer referrer_flag) {
if (!target)
return NOT_ROUTED;
if (!webframe_)
return NOT_ROUTED;
WebString target_str = WebString::fromUTF8(target);
if (is_javascript_url) {
WebFrame* target_frame =
webframe_->view()->findFrameByName(target_str, webframe_);
if (target_frame != webframe_) {
const char kMessage[] =
"Ignoring cross-frame javascript URL load requested by plugin.";
webframe_->addMessageToConsole(
WebConsoleMessage(WebConsoleMessage::LevelError,
WebString::fromUTF8(kMessage)));
return ROUTED;
}
return NOT_ROUTED;
}
GURL complete_url = CompleteURL(url);
if (!WebPluginImpl::IsValidUrl(complete_url, referrer_flag))
return INVALID_URL;
if (strcmp(method, "GET") != 0) {
if (!complete_url.SchemeIsHTTPOrHTTPS())
return INVALID_URL;
}
WebURLRequest request(complete_url);
SetReferrer(&request, referrer_flag);
request.setHTTPMethod(WebString::fromUTF8(method));
request.setFirstPartyForCookies(
webframe_->document().firstPartyForCookies());
request.setHasUserGesture(popups_allowed);
if (len > 0) {
if (!SetPostData(&request, buf, len)) {
NOTREACHED();
return ROUTED;
}
}
container_->loadFrameRequest(
request, target_str, notify_id != 0, reinterpret_cast<void*>(notify_id));
return ROUTED;
}
NPObject* WebPluginImpl::GetWindowScriptNPObject() {
if (!webframe_) {
NOTREACHED();
return NULL;
}
return webframe_->windowObject();
}
NPObject* WebPluginImpl::GetPluginElement() {
return container_->scriptableObjectForElement();
}
bool WebPluginImpl::FindProxyForUrl(const GURL& url, std::string* proxy_list) {
return false;
}
void WebPluginImpl::SetCookie(const GURL& url,
const GURL& first_party_for_cookies,
const std::string& cookie) {
if (!render_view_.get())
return;
WebCookieJar* cookie_jar = render_frame_->cookie_jar();
if (!cookie_jar) {
DLOG(WARNING) << "No cookie jar!";
return;
}
cookie_jar->setCookie(
url, first_party_for_cookies, WebString::fromUTF8(cookie));
}
std::string WebPluginImpl::GetCookies(const GURL& url,
const GURL& first_party_for_cookies) {
if (!render_view_.get())
return std::string();
WebCookieJar* cookie_jar = render_frame_->cookie_jar();
if (!cookie_jar) {
DLOG(WARNING) << "No cookie jar!";
return std::string();
}
return base::UTF16ToUTF8(cookie_jar->cookies(url, first_party_for_cookies));
}
void WebPluginImpl::URLRedirectResponse(bool allow, int resource_id) {
for (size_t i = 0; i < clients_.size(); ++i) {
if (clients_[i].id == static_cast<unsigned long>(resource_id)) {
if (clients_[i].loader.get()) {
if (allow) {
clients_[i].loader->setDefersLoading(false);
} else {
clients_[i].loader->cancel();
if (clients_[i].client)
clients_[i].client->DidFail(clients_[i].id);
}
}
break;
}
}
}
bool WebPluginImpl::CheckIfRunInsecureContent(const GURL& url) {
if (!webframe_)
return true;
return webframe_->checkIfRunInsecureContent(url);
}
#if defined(OS_MACOSX)
WebPluginAcceleratedSurface* WebPluginImpl::GetAcceleratedSurface(
gfx::GpuPreference gpu_preference) {
return NULL;
}
void WebPluginImpl::AcceleratedPluginEnabledRendering() {
}
void WebPluginImpl::AcceleratedPluginAllocatedIOSurface(int32 width,
int32 height,
uint32 surface_id) {
next_io_surface_allocated_ = true;
next_io_surface_width_ = width;
next_io_surface_height_ = height;
next_io_surface_id_ = surface_id;
}
void WebPluginImpl::AcceleratedPluginSwappedIOSurface() {
if (!container_)
return;
if (next_io_surface_allocated_) {
if (next_io_surface_id_) {
if (!io_surface_layer_.get()) {
io_surface_layer_ = cc::IOSurfaceLayer::Create();
web_layer_.reset(new webkit::WebLayerImpl(io_surface_layer_));
container_->setWebLayer(web_layer_.get());
}
io_surface_layer_->SetIOSurfaceProperties(
next_io_surface_id_,
gfx::Size(next_io_surface_width_, next_io_surface_height_));
} else {
container_->setWebLayer(NULL);
web_layer_.reset();
io_surface_layer_ = NULL;
}
next_io_surface_allocated_ = false;
} else {
if (io_surface_layer_.get())
io_surface_layer_->SetNeedsDisplay();
}
}
#endif
void WebPluginImpl::Invalidate() {
if (container_)
container_->invalidate();
}
void WebPluginImpl::InvalidateRect(const gfx::Rect& rect) {
if (container_)
container_->invalidateRect(rect);
}
void WebPluginImpl::OnDownloadPluginSrcUrl() {
HandleURLRequestInternal(
plugin_url_.spec().c_str(), "GET", NULL, NULL, 0, 0, false, DOCUMENT_URL,
false, true);
}
WebPluginResourceClient* WebPluginImpl::GetClientFromLoader(
WebURLLoader* loader) {
ClientInfo* client_info = GetClientInfoFromLoader(loader);
if (client_info)
return client_info->client;
return NULL;
}
WebPluginImpl::ClientInfo* WebPluginImpl::GetClientInfoFromLoader(
WebURLLoader* loader) {
for (size_t i = 0; i < clients_.size(); ++i) {
if (clients_[i].loader.get() == loader)
return &clients_[i];
}
NOTREACHED();
return 0;
}
void WebPluginImpl::willSendRequest(WebURLLoader* loader,
WebURLRequest& request,
const WebURLResponse& response) {
WebPluginImpl::ClientInfo* client_info = GetClientInfoFromLoader(loader);
if (client_info) {
if (client_info->is_plugin_src_load &&
webframe_ &&
!webframe_->checkIfRunInsecureContent(request.url())) {
loader->cancel();
client_info->client->DidFail(client_info->id);
return;
}
if (net::HttpResponseHeaders::IsRedirectResponseCode(
response.httpStatusCode())) {
if (!client_info->notify_redirects) {
if (response.httpStatusCode() == 307 &&
LowerCaseEqualsASCII(request.httpMethod().utf8(), "post")) {
GURL original_request_url(response.url());
GURL response_url(request.url());
if (original_request_url.GetOrigin() != response_url.GetOrigin()) {
loader->setDefersLoading(true);
loader->cancel();
client_info->client->DidFail(client_info->id);
return;
}
}
} else {
loader->setDefersLoading(true);
}
}
client_info->client->WillSendRequest(request.url(),
response.httpStatusCode());
}
}
void WebPluginImpl::didSendData(WebURLLoader* loader,
unsigned long long bytes_sent,
unsigned long long total_bytes_to_be_sent) {
}
void WebPluginImpl::didReceiveResponse(WebURLLoader* loader,
const WebURLResponse& response) {
static const int kHttpPartialResponseStatusCode = 206;
static const int kHttpResponseSuccessStatusCode = 200;
WebPluginResourceClient* client = GetClientFromLoader(loader);
if (!client)
return;
ResponseInfo response_info;
GetResponseInfo(response, &response_info);
ClientInfo* client_info = GetClientInfoFromLoader(loader);
if (!client_info)
return;
bool request_is_seekable = true;
if (client->IsMultiByteResponseExpected()) {
if (response.httpStatusCode() == kHttpPartialResponseStatusCode) {
ClientInfo* client_info = GetClientInfoFromLoader(loader);
if (!client_info)
return;
if (HandleHttpMultipartResponse(response, client)) {
client_info->data_offset = 0;
return;
}
int64 upper_bound = 0, instance_size = 0;
MultipartResponseDelegate::ReadContentRanges(response,
&client_info->data_offset,
&upper_bound,
&instance_size);
} else if (response.httpStatusCode() == kHttpResponseSuccessStatusCode) {
RenderThreadImpl::current()->RecordAction(
base::UserMetricsAction("Plugin_200ForByteRange"));
if (!ReinitializePluginForResponse(loader)) {
NOTREACHED();
return;
}
request_is_seekable = false;
delete client;
client = NULL;
for (size_t i = 0; i < clients_.size(); ++i) {
if (clients_[i].loader.get() == loader) {
WebPluginResourceClient* resource_client =
delegate_->CreateResourceClient(clients_[i].id, plugin_url_, 0);
clients_[i].client = resource_client;
client = resource_client;
break;
}
}
DCHECK(client != NULL);
}
}
loader->setDefersLoading(true);
client->DidReceiveResponse(
response_info.mime_type,
GetAllHeaders(response),
response_info.expected_length,
response_info.last_modified,
request_is_seekable);
const GURL& url = response.url();
if (url.SchemeIs("http") || url.SchemeIs("https")) {
if (response.httpStatusCode() < 100 || response.httpStatusCode() >= 400) {
ClientInfo* client_info = GetClientInfoFromLoader(loader);
if (client_info) {
client_info->pending_failure_notification = true;
}
}
}
}
void WebPluginImpl::didReceiveData(WebURLLoader* loader,
const char *buffer,
int data_length,
int encoded_data_length) {
WebPluginResourceClient* client = GetClientFromLoader(loader);
if (!client)
return;
MultiPartResponseHandlerMap::iterator index =
multi_part_response_map_.find(client);
if (index != multi_part_response_map_.end()) {
MultipartResponseDelegate* multi_part_handler = (*index).second;
DCHECK(multi_part_handler != NULL);
multi_part_handler->OnReceivedData(buffer,
data_length,
encoded_data_length);
} else {
loader->setDefersLoading(true);
ClientInfo* client_info = GetClientInfoFromLoader(loader);
client->DidReceiveData(buffer, data_length, client_info->data_offset);
client_info->data_offset += data_length;
}
}
void WebPluginImpl::didFinishLoading(WebURLLoader* loader, double finishTime) {
ClientInfo* client_info = GetClientInfoFromLoader(loader);
if (client_info && client_info->client) {
MultiPartResponseHandlerMap::iterator index =
multi_part_response_map_.find(client_info->client);
if (index != multi_part_response_map_.end()) {
delete (*index).second;
multi_part_response_map_.erase(index);
DidStopLoading();
}
loader->setDefersLoading(true);
WebPluginResourceClient* resource_client = client_info->client;
client_info->client = NULL;
resource_client->DidFinishLoading(client_info->id);
}
}
void WebPluginImpl::didFail(WebURLLoader* loader,
const WebURLError& error) {
ClientInfo* client_info = GetClientInfoFromLoader(loader);
if (client_info && client_info->client) {
loader->setDefersLoading(true);
WebPluginResourceClient* resource_client = client_info->client;
client_info->client = NULL;
resource_client->DidFail(client_info->id);
}
}
void WebPluginImpl::RemoveClient(size_t i) {
clients_.erase(clients_.begin() + i);
}
void WebPluginImpl::RemoveClient(WebURLLoader* loader) {
for (size_t i = 0; i < clients_.size(); ++i) {
if (clients_[i].loader.get() == loader) {
RemoveClient(i);
return;
}
}
}
void WebPluginImpl::SetContainer(WebPluginContainer* container) {
if (!container)
TearDownPluginInstance(NULL);
container_ = container;
if (container_)
container_->allowScriptObjects();
}
void WebPluginImpl::HandleURLRequest(const char* url,
const char* method,
const char* target,
const char* buf,
unsigned int len,
int notify_id,
bool popups_allowed,
bool notify_redirects) {
HandleURLRequestInternal(
url, method, target, buf, len, notify_id, popups_allowed, PLUGIN_SRC,
notify_redirects, false);
}
void WebPluginImpl::HandleURLRequestInternal(const char* url,
const char* method,
const char* target,
const char* buf,
unsigned int len,
int notify_id,
bool popups_allowed,
Referrer referrer_flag,
bool notify_redirects,
bool is_plugin_src_load) {
bool is_javascript_url = url_util::FindAndCompareScheme(
url, strlen(url), "javascript", NULL);
RoutingStatus routing_status = RouteToFrame(
url, is_javascript_url, popups_allowed, method, target, buf, len,
notify_id, referrer_flag);
if (routing_status == ROUTED)
return;
if (is_javascript_url) {
GURL gurl(url);
WebString result = container_->executeScriptURL(gurl, popups_allowed);
if (delegate_) {
delegate_->SendJavaScriptStream(
gurl, result.utf8(), !result.isNull(), notify_id);
}
return;
}
unsigned long resource_id = GetNextResourceId();
if (!resource_id)
return;
GURL complete_url = CompleteURL(url);
if (!WebPluginImpl::IsValidUrl(complete_url, referrer_flag))
return;
if ((routing_status == INVALID_URL) ||
(routing_status == GENERAL_FAILURE)) {
WebPluginResourceClient* resource_client = delegate_->CreateResourceClient(
resource_id, complete_url, notify_id);
if (resource_client)
resource_client->DidFail(resource_id);
return;
}
if (!delegate_)
return;
if (!CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableDirectNPAPIRequests)) {
WebURLRequest request(complete_url);
SetReferrer(&request, referrer_flag);
GURL referrer(
request.httpHeaderField(WebString::fromUTF8("Referer")).utf8());
GURL first_party_for_cookies = webframe_->document().firstPartyForCookies();
delegate_->FetchURL(resource_id, notify_id, complete_url,
first_party_for_cookies, method, buf, len, referrer,
notify_redirects, is_plugin_src_load, 0,
render_frame_->GetRoutingID(),
render_view_->GetRoutingID());
} else {
WebPluginResourceClient* resource_client = delegate_->CreateResourceClient(
resource_id, complete_url, notify_id);
if (!resource_client)
return;
InitiateHTTPRequest(resource_id, resource_client, complete_url, method, buf,
len, NULL, referrer_flag, notify_redirects,
is_plugin_src_load);
}
}
unsigned long WebPluginImpl::GetNextResourceId() {
if (!webframe_)
return 0;
WebView* view = webframe_->view();
if (!view)
return 0;
return view->createUniqueIdentifierForRequest();
}
bool WebPluginImpl::InitiateHTTPRequest(unsigned long resource_id,
WebPluginResourceClient* client,
const GURL& url,
const char* method,
const char* buf,
int buf_len,
const char* range_info,
Referrer referrer_flag,
bool notify_redirects,
bool is_plugin_src_load) {
if (!client) {
NOTREACHED();
return false;
}
ClientInfo info;
info.id = resource_id;
info.client = client;
info.request.initialize();
info.request.setURL(url);
info.request.setFirstPartyForCookies(
webframe_->document().firstPartyForCookies());
info.request.setRequestorProcessID(delegate_->GetProcessId());
info.request.setTargetType(WebURLRequest::TargetIsObject);
info.request.setHTTPMethod(WebString::fromUTF8(method));
info.pending_failure_notification = false;
info.notify_redirects = notify_redirects;
info.is_plugin_src_load = is_plugin_src_load;
info.data_offset = 0;
if (range_info) {
info.request.addHTTPHeaderField(WebString::fromUTF8("Range"),
WebString::fromUTF8(range_info));
}
if (strcmp(method, "POST") == 0) {
SetPostData(&info.request, buf, buf_len);
}
SetReferrer(&info.request, referrer_flag);
WebURLLoaderOptions options;
options.allowCredentials = true;
options.crossOriginRequestPolicy =
WebURLLoaderOptions::CrossOriginRequestPolicyAllow;
info.loader.reset(webframe_->createAssociatedURLLoader(options));
if (!info.loader.get())
return false;
info.loader->loadAsynchronously(info.request, &loader_client_);
clients_.push_back(info);
return true;
}
void WebPluginImpl::CancelDocumentLoad() {
if (webframe_) {
ignore_response_error_ = true;
webframe_->stopLoading();
}
}
void WebPluginImpl::InitiateHTTPRangeRequest(
const char* url, const char* range_info, int range_request_id) {
unsigned long resource_id = GetNextResourceId();
if (!resource_id)
return;
GURL complete_url = CompleteURL(url);
if (!WebPluginImpl::IsValidUrl(complete_url,
load_manually_ ? NO_REFERRER : PLUGIN_SRC))
return;
WebPluginResourceClient* resource_client =
delegate_->CreateSeekableResourceClient(resource_id, range_request_id);
InitiateHTTPRequest(
resource_id, resource_client, complete_url, "GET", NULL, 0, range_info,
load_manually_ ? NO_REFERRER : PLUGIN_SRC, false, false);
}
void WebPluginImpl::DidStartLoading() {
if (render_view_.get()) {
render_view_->DidStartLoading();
}
}
void WebPluginImpl::DidStopLoading() {
if (render_view_.get()) {
render_view_->DidStopLoading();
}
}
void WebPluginImpl::SetDeferResourceLoading(unsigned long resource_id,
bool defer) {
std::vector<ClientInfo>::iterator client_index = clients_.begin();
while (client_index != clients_.end()) {
ClientInfo& client_info = *client_index;
if (client_info.id == resource_id) {
client_info.loader->setDefersLoading(defer);
if (!defer && client_info.client &&
client_info.pending_failure_notification) {
WebPluginResourceClient* resource_client = client_info.client;
client_info.loader->cancel();
clients_.erase(client_index++);
resource_client->DidFail(resource_id);
}
break;
}
client_index++;
}
}
bool WebPluginImpl::IsOffTheRecord() {
return false;
}
bool WebPluginImpl::HandleHttpMultipartResponse(
const WebURLResponse& response, WebPluginResourceClient* client) {
std::string multipart_boundary;
if (!MultipartResponseDelegate::ReadMultipartBoundary(
response, &multipart_boundary)) {
return false;
}
DidStartLoading();
MultiPartResponseClient* multi_part_response_client =
new MultiPartResponseClient(client);
MultipartResponseDelegate* multi_part_response_handler =
new MultipartResponseDelegate(multi_part_response_client, NULL,
response,
multipart_boundary);
multi_part_response_map_[client] = multi_part_response_handler;
return true;
}
bool WebPluginImpl::ReinitializePluginForResponse(
WebURLLoader* loader) {
WebFrame* webframe = webframe_;
if (!webframe)
return false;
WebView* webview = webframe->view();
if (!webview)
return false;
WebPluginContainer* container_widget = container_;
TearDownPluginInstance(loader);
container_ = container_widget;
webframe_ = webframe;
WebPluginDelegateProxy* plugin_delegate = new WebPluginDelegateProxy(
this, mime_type_, render_view_, render_frame_);
npp_ = plugin_delegate->GetPluginNPP();
container_->allowScriptObjects();
bool ok = plugin_delegate && plugin_delegate->Initialize(
plugin_url_, arg_names_, arg_values_, load_manually_);
if (!ok) {
container_->clearScriptObjects();
container_ = NULL;
return false;
}
delegate_ = plugin_delegate;
container_->reportGeometry();
container_->invalidate();
return true;
}
void WebPluginImpl::TearDownPluginInstance(
WebURLLoader* loader_to_ignore) {
if (container_) {
container_->clearScriptObjects();
container_->setWebLayer(NULL);
}
if (delegate_) {
DCHECK(container_);
container_->allowScriptObjects();
delegate_->PluginDestroyed();
delegate_ = NULL;
container_->clearScriptObjects();
}
std::vector<ClientInfo>::iterator client_index = clients_.begin();
while (client_index != clients_.end()) {
ClientInfo& client_info = *client_index;
if (loader_to_ignore == client_info.loader) {
client_index++;
continue;
}
if (client_info.loader.get())
client_info.loader->cancel();
client_index = clients_.erase(client_index);
}
webframe_ = NULL;
weak_factory_.InvalidateWeakPtrs();
}
void WebPluginImpl::SetReferrer(blink::WebURLRequest* request,
Referrer referrer_flag) {
switch (referrer_flag) {
case DOCUMENT_URL:
webframe_->setReferrerForRequest(*request, GURL());
break;
case PLUGIN_SRC:
webframe_->setReferrerForRequest(*request, plugin_url_);
break;
default:
break;
}
}
}