Add a new SequencedSocketData class.
[chromium-blink-merge.git] / content / child / npapi / plugin_host.cc
blobcdda9e41578897312d7faf4c33172ff63d721f7a
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/child/npapi/plugin_host.h"
7 #include "base/command_line.h"
8 #include "base/files/file_util.h"
9 #include "base/lazy_instance.h"
10 #include "base/logging.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/strings/string_piece.h"
13 #include "base/strings/string_util.h"
14 #include "base/strings/sys_string_conversions.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "build/build_config.h"
17 #include "content/child/npapi/plugin_instance.h"
18 #include "content/child/npapi/plugin_lib.h"
19 #include "content/child/npapi/plugin_stream_url.h"
20 #include "content/child/npapi/webplugin_delegate.h"
21 #include "content/public/common/content_client.h"
22 #include "content/public/common/content_switches.h"
23 #include "content/public/common/user_agent.h"
24 #include "content/public/common/webplugininfo.h"
25 #include "net/base/filename_util.h"
26 #include "third_party/WebKit/public/web/WebBindings.h"
27 #include "third_party/WebKit/public/web/WebKit.h"
28 #include "third_party/npapi/bindings/npruntime.h"
29 #include "ui/gl/gl_implementation.h"
30 #include "ui/gl/gl_surface.h"
32 using blink::WebBindings;
34 // Declarations for stub implementations of deprecated functions, which are no
35 // longer listed in npapi.h.
36 extern "C" {
37 void* NPN_GetJavaEnv();
38 void* NPN_GetJavaPeer(NPP);
41 namespace content {
43 // Finds a PluginInstance from an NPP.
44 // The caller must take a reference if needed.
45 static PluginInstance* FindInstance(NPP id) {
46 if (id == NULL) {
47 return NULL;
49 return reinterpret_cast<PluginInstance*>(id->ndata);
52 #if defined(OS_MACOSX)
53 // Returns true if Core Animation plugins are supported. This requires that the
54 // OS supports shared accelerated surfaces via IOSurface. This is true on Snow
55 // Leopard and higher.
56 static bool SupportsCoreAnimationPlugins() {
57 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
58 switches::kDisableCoreAnimationPlugins))
59 return false;
60 // We also need to be running with desktop GL and not the software
61 // OSMesa renderer in order to share accelerated surfaces between
62 // processes. Because on MacOS we lazy-initialize GLSurface in the
63 // renderer process here, ensure we're not also initializing GL somewhere
64 // else, and that we only do this once.
65 static gfx::GLImplementation implementation = gfx::kGLImplementationNone;
66 if (implementation == gfx::kGLImplementationNone) {
67 // Not initialized yet.
68 DCHECK_EQ(implementation, gfx::GetGLImplementation())
69 << "GL already initialized by someone else to: "
70 << gfx::GetGLImplementation();
71 if (!gfx::GLSurface::InitializeOneOff()) {
72 return false;
74 implementation = gfx::GetGLImplementation();
76 return (implementation == gfx::kGLImplementationDesktopGL);
78 #endif
80 PluginHost::PluginHost() {
81 InitializeHostFuncs();
84 PluginHost::~PluginHost() {
87 PluginHost *PluginHost::Singleton() {
88 CR_DEFINE_STATIC_LOCAL(scoped_refptr<PluginHost>, singleton, ());
89 if (singleton.get() == NULL) {
90 singleton = new PluginHost();
93 DCHECK(singleton.get() != NULL);
94 return singleton.get();
97 void PluginHost::InitializeHostFuncs() {
98 memset(&host_funcs_, 0, sizeof(host_funcs_));
99 host_funcs_.size = sizeof(host_funcs_);
100 host_funcs_.version = (NP_VERSION_MAJOR << 8) | (NP_VERSION_MINOR);
102 // The "basic" functions
103 host_funcs_.geturl = &NPN_GetURL;
104 host_funcs_.posturl = &NPN_PostURL;
105 host_funcs_.requestread = &NPN_RequestRead;
106 host_funcs_.newstream = &NPN_NewStream;
107 host_funcs_.write = &NPN_Write;
108 host_funcs_.destroystream = &NPN_DestroyStream;
109 host_funcs_.status = &NPN_Status;
110 host_funcs_.uagent = &NPN_UserAgent;
111 host_funcs_.memalloc = &NPN_MemAlloc;
112 host_funcs_.memfree = &NPN_MemFree;
113 host_funcs_.memflush = &NPN_MemFlush;
114 host_funcs_.reloadplugins = &NPN_ReloadPlugins;
116 // Stubs for deprecated Java functions
117 host_funcs_.getJavaEnv = &NPN_GetJavaEnv;
118 host_funcs_.getJavaPeer = &NPN_GetJavaPeer;
120 // Advanced functions we implement
121 host_funcs_.geturlnotify = &NPN_GetURLNotify;
122 host_funcs_.posturlnotify = &NPN_PostURLNotify;
123 host_funcs_.getvalue = &NPN_GetValue;
124 host_funcs_.setvalue = &NPN_SetValue;
125 host_funcs_.invalidaterect = &NPN_InvalidateRect;
126 host_funcs_.invalidateregion = &NPN_InvalidateRegion;
127 host_funcs_.forceredraw = &NPN_ForceRedraw;
129 // These come from the Javascript Engine
130 host_funcs_.getstringidentifier = WebBindings::getStringIdentifier;
131 host_funcs_.getstringidentifiers = WebBindings::getStringIdentifiers;
132 host_funcs_.getintidentifier = WebBindings::getIntIdentifier;
133 host_funcs_.identifierisstring = WebBindings::identifierIsString;
134 host_funcs_.utf8fromidentifier = WebBindings::utf8FromIdentifier;
135 host_funcs_.intfromidentifier = WebBindings::intFromIdentifier;
136 host_funcs_.createobject = WebBindings::createObject;
137 host_funcs_.retainobject = WebBindings::retainObject;
138 host_funcs_.releaseobject = WebBindings::releaseObject;
139 host_funcs_.invoke = WebBindings::invoke;
140 host_funcs_.invokeDefault = WebBindings::invokeDefault;
141 host_funcs_.evaluate = WebBindings::evaluate;
142 host_funcs_.getproperty = WebBindings::getProperty;
143 host_funcs_.setproperty = WebBindings::setProperty;
144 host_funcs_.removeproperty = WebBindings::removeProperty;
145 host_funcs_.hasproperty = WebBindings::hasProperty;
146 host_funcs_.hasmethod = WebBindings::hasMethod;
147 host_funcs_.releasevariantvalue = WebBindings::releaseVariantValue;
148 host_funcs_.setexception = WebBindings::setException;
149 host_funcs_.pushpopupsenabledstate = NPN_PushPopupsEnabledState;
150 host_funcs_.poppopupsenabledstate = NPN_PopPopupsEnabledState;
151 host_funcs_.enumerate = WebBindings::enumerate;
152 host_funcs_.pluginthreadasynccall = NPN_PluginThreadAsyncCall;
153 host_funcs_.construct = WebBindings::construct;
154 host_funcs_.getvalueforurl = NPN_GetValueForURL;
155 host_funcs_.setvalueforurl = NPN_SetValueForURL;
156 host_funcs_.getauthenticationinfo = NPN_GetAuthenticationInfo;
157 host_funcs_.scheduletimer = NPN_ScheduleTimer;
158 host_funcs_.unscheduletimer = NPN_UnscheduleTimer;
159 host_funcs_.popupcontextmenu = NPN_PopUpContextMenu;
160 host_funcs_.convertpoint = NPN_ConvertPoint;
161 host_funcs_.handleevent = NPN_HandleEvent;
162 host_funcs_.unfocusinstance = NPN_UnfocusInstance;
163 host_funcs_.urlredirectresponse = NPN_URLRedirectResponse;
166 void PluginHost::PatchNPNetscapeFuncs(NPNetscapeFuncs* overrides) {
167 // When running in the plugin process, we need to patch the NPN functions
168 // that the plugin calls to interact with NPObjects that we give. Otherwise
169 // the plugin will call the v8 NPN functions, which won't work since we have
170 // an NPObjectProxy and not a real v8 implementation.
171 if (overrides->invoke)
172 host_funcs_.invoke = overrides->invoke;
174 if (overrides->invokeDefault)
175 host_funcs_.invokeDefault = overrides->invokeDefault;
177 if (overrides->evaluate)
178 host_funcs_.evaluate = overrides->evaluate;
180 if (overrides->getproperty)
181 host_funcs_.getproperty = overrides->getproperty;
183 if (overrides->setproperty)
184 host_funcs_.setproperty = overrides->setproperty;
186 if (overrides->removeproperty)
187 host_funcs_.removeproperty = overrides->removeproperty;
189 if (overrides->hasproperty)
190 host_funcs_.hasproperty = overrides->hasproperty;
192 if (overrides->hasmethod)
193 host_funcs_.hasmethod = overrides->hasmethod;
195 if (overrides->setexception)
196 host_funcs_.setexception = overrides->setexception;
198 if (overrides->enumerate)
199 host_funcs_.enumerate = overrides->enumerate;
202 bool PluginHost::SetPostData(const char* buf,
203 uint32 length,
204 std::vector<std::string>* names,
205 std::vector<std::string>* values,
206 std::vector<char>* body) {
207 // Use a state table to do the parsing. Whitespace must be
208 // trimmed after the fact if desired. In our case, we actually
209 // don't care about the whitespace, because we're just going to
210 // pass this back into another POST. This function strips out the
211 // "Content-length" header and does not append it to the request.
214 // This parser takes action only on state changes.
216 // Transition table:
217 // : \n NULL Other
218 // 0 GetHeader 1 2 4 0
219 // 1 GetValue 1 0 3 1
220 // 2 GetData 2 2 3 2
221 // 3 DONE
222 // 4 ERR
224 enum { INPUT_COLON=0, INPUT_NEWLINE, INPUT_NULL, INPUT_OTHER };
225 enum { GETNAME, GETVALUE, GETDATA, DONE, ERR };
226 int statemachine[3][4] = { { GETVALUE, GETDATA, GETDATA, GETNAME },
227 { GETVALUE, GETNAME, DONE, GETVALUE },
228 { GETDATA, GETDATA, DONE, GETDATA } };
229 std::string name, value;
230 const char* ptr = static_cast<const char*>(buf);
231 const char* start = ptr;
232 int state = GETNAME; // initial state
233 bool done = false;
234 bool err = false;
235 do {
236 int input;
238 // Translate the current character into an input
239 // for the state table.
240 switch (*ptr) {
241 case ':' :
242 input = INPUT_COLON;
243 break;
244 case '\n':
245 input = INPUT_NEWLINE;
246 break;
247 case 0 :
248 input = INPUT_NULL;
249 break;
250 default :
251 input = INPUT_OTHER;
252 break;
255 int newstate = statemachine[state][input];
257 // Take action based on the new state.
258 if (state != newstate) {
259 switch (newstate) {
260 case GETNAME:
261 // Got a value.
262 value = std::string(start, ptr - start);
263 base::TrimWhitespace(value, base::TRIM_ALL, &value);
264 // If the name field is empty, we'll skip this header
265 // but we won't error out.
266 if (!name.empty() && name != "content-length") {
267 names->push_back(name);
268 values->push_back(value);
270 start = ptr + 1;
271 break;
272 case GETVALUE:
273 // Got a header.
274 name = base::StringToLowerASCII(std::string(start, ptr - start));
275 base::TrimWhitespace(name, base::TRIM_ALL, &name);
276 start = ptr + 1;
277 break;
278 case GETDATA: {
279 // Finished headers, now get body
280 if (*ptr)
281 start = ptr + 1;
282 size_t previous_size = body->size();
283 size_t new_body_size = length - static_cast<int>(start - buf);
284 body->resize(previous_size + new_body_size);
285 if (!body->empty())
286 memcpy(&body->front() + previous_size, start, new_body_size);
287 done = true;
288 break;
290 case ERR:
291 // error
292 err = true;
293 done = true;
294 break;
297 state = newstate;
298 ptr++;
299 } while (!done);
301 return !err;
304 } // namespace content
306 extern "C" {
308 using content::FindInstance;
309 using content::PluginHost;
310 using content::PluginInstance;
311 using content::WebPlugin;
313 // Allocates memory from the host's memory space.
314 void* NPN_MemAlloc(uint32_t size) {
315 // Note: We must use the same allocator/deallocator
316 // that is used by the javascript library, as some of the
317 // JS APIs will pass memory to the plugin which the plugin
318 // will attempt to free.
319 return malloc(size);
322 // Deallocates memory from the host's memory space
323 void NPN_MemFree(void* ptr) {
324 if (ptr != NULL && ptr != reinterpret_cast<void*>(-1))
325 free(ptr);
328 // Requests that the host free a specified amount of memory.
329 uint32_t NPN_MemFlush(uint32_t size) {
330 // This is not relevant on Windows; MAC specific
331 return size;
334 // This is for dynamic discovery of new plugins.
335 // Should force a re-scan of the plugins directory to load new ones.
336 void NPN_ReloadPlugins(NPBool reload_pages) {
337 blink::resetPluginCache(reload_pages ? true : false);
340 // Requests a range of bytes for a seekable stream.
341 NPError NPN_RequestRead(NPStream* stream, NPByteRange* range_list) {
342 if (!stream || !range_list)
343 return NPERR_GENERIC_ERROR;
345 scoped_refptr<PluginInstance> plugin(
346 reinterpret_cast<PluginInstance*>(stream->ndata));
347 if (!plugin.get())
348 return NPERR_GENERIC_ERROR;
350 plugin->RequestRead(stream, range_list);
351 return NPERR_NO_ERROR;
354 // Generic form of GetURL for common code between GetURL and GetURLNotify.
355 static NPError GetURLNotify(NPP id,
356 const char* url,
357 const char* target,
358 bool notify,
359 void* notify_data) {
360 if (!url)
361 return NPERR_INVALID_URL;
363 scoped_refptr<PluginInstance> plugin(FindInstance(id));
364 if (!plugin.get()) {
365 return NPERR_GENERIC_ERROR;
368 plugin->RequestURL(url, "GET", target, NULL, 0, notify, notify_data);
369 return NPERR_NO_ERROR;
372 // Requests creation of a new stream with the contents of the
373 // specified URL; gets notification of the result.
374 NPError NPN_GetURLNotify(NPP id,
375 const char* url,
376 const char* target,
377 void* notify_data) {
378 // This is identical to NPN_GetURL, but after finishing, the
379 // browser will call NPP_URLNotify to inform the plugin that
380 // it has completed.
382 // According to the NPAPI documentation, if target == _self
383 // or a parent to _self, the browser should return NPERR_INVALID_PARAM,
384 // because it can't notify the plugin once deleted. This is
385 // absolutely false; firefox doesn't do this, and Flash relies on
386 // being able to use this.
388 // Also according to the NPAPI documentation, we should return
389 // NPERR_INVALID_URL if the url requested is not valid. However,
390 // this would require that we synchronously start fetching the
391 // URL. That just isn't practical. As such, there really is
392 // no way to return this error. From looking at the Firefox
393 // implementation, it doesn't look like Firefox does this either.
395 return GetURLNotify(id, url, target, true, notify_data);
398 NPError NPN_GetURL(NPP id, const char* url, const char* target) {
399 // Notes:
400 // Request from the Plugin to fetch content either for the plugin
401 // or to be placed into a browser window.
403 // If target == null, the browser fetches content and streams to plugin.
404 // otherwise, the browser loads content into an existing browser frame.
405 // If the target is the window/frame containing the plugin, the plugin
406 // may be destroyed.
407 // If the target is _blank, a mailto: or news: url open content in a new
408 // browser window
409 // If the target is _self, no other instance of the plugin is created. The
410 // plugin continues to operate in its own window
412 return GetURLNotify(id, url, target, false, 0);
415 // Generic form of PostURL for common code between PostURL and PostURLNotify.
416 static NPError PostURLNotify(NPP id,
417 const char* url,
418 const char* target,
419 uint32_t len,
420 const char* buf,
421 NPBool file,
422 bool notify,
423 void* notify_data) {
424 if (!url)
425 return NPERR_INVALID_URL;
427 scoped_refptr<PluginInstance> plugin(FindInstance(id));
428 if (!plugin.get()) {
429 NOTREACHED();
430 return NPERR_GENERIC_ERROR;
433 std::string post_file_contents;
435 if (file) {
436 // Post data to be uploaded from a file. This can be handled in two
437 // ways.
438 // 1. Read entire file and send the contents as if it was a post data
439 // specified in the argument
440 // 2. Send just the file details and read them in the browser at the
441 // time of sending the request.
442 // Approach 2 is more efficient but complicated. Approach 1 has a major
443 // drawback of sending potentially large data over two IPC hops. In a way
444 // 'large data over IPC' problem exists as it is in case of plugin giving
445 // the data directly instead of in a file.
446 // Currently we are going with the approach 1 to get the feature working.
447 // We can optimize this later with approach 2.
449 // TODO(joshia): Design a scheme to send a file descriptor instead of
450 // entire file contents across.
452 // Security alert:
453 // ---------------
454 // Here we are blindly uploading whatever file requested by a plugin.
455 // This is risky as someone could exploit a plugin to send private
456 // data in arbitrary locations.
457 // A malicious (non-sandboxed) plugin has unfeterred access to OS
458 // resources and can do this anyway without using browser's HTTP stack.
459 // FWIW, Firefox and Safari don't perform any security checks.
461 if (!buf)
462 return NPERR_FILE_NOT_FOUND;
464 std::string file_path_ascii(buf);
465 base::FilePath file_path;
466 static const char kFileUrlPrefix[] = "file:";
467 if (StartsWithASCII(file_path_ascii, kFileUrlPrefix, false)) {
468 GURL file_url(file_path_ascii);
469 DCHECK(file_url.SchemeIsFile());
470 net::FileURLToFilePath(file_url, &file_path);
471 } else {
472 file_path = base::FilePath::FromUTF8Unsafe(file_path_ascii);
475 base::File::Info post_file_info;
476 if (!base::GetFileInfo(file_path, &post_file_info) ||
477 post_file_info.is_directory)
478 return NPERR_FILE_NOT_FOUND;
480 if (!base::ReadFileToString(file_path, &post_file_contents))
481 return NPERR_FILE_NOT_FOUND;
483 buf = post_file_contents.c_str();
484 len = post_file_contents.size();
487 // The post data sent by a plugin contains both headers
488 // and post data. Example:
489 // Content-type: text/html
490 // Content-length: 200
492 // <200 bytes of content here>
494 // Unfortunately, our stream needs these broken apart,
495 // so we need to parse the data and set headers and data
496 // separately.
497 plugin->RequestURL(url, "POST", target, buf, len, notify, notify_data);
498 return NPERR_NO_ERROR;
501 NPError NPN_PostURLNotify(NPP id,
502 const char* url,
503 const char* target,
504 uint32_t len,
505 const char* buf,
506 NPBool file,
507 void* notify_data) {
508 return PostURLNotify(id, url, target, len, buf, file, true, notify_data);
511 NPError NPN_PostURL(NPP id,
512 const char* url,
513 const char* target,
514 uint32_t len,
515 const char* buf,
516 NPBool file) {
517 // POSTs data to an URL, either from a temp file or a buffer.
518 // If file is true, buf contains a temp file (which host will delete after
519 // completing), and len contains the length of the filename.
520 // If file is false, buf contains the data to send, and len contains the
521 // length of the buffer
523 // If target is null,
524 // server response is returned to the plugin
525 // If target is _current, _self, or _top,
526 // server response is written to the plugin window and plugin is unloaded.
527 // If target is _new or _blank,
528 // server response is written to a new browser window
529 // If target is an existing frame,
530 // server response goes to that frame.
532 // For protocols other than FTP
533 // file uploads must be line-end converted from \r\n to \n
535 // Note: you cannot specify headers (even a blank line) in a memory buffer,
536 // use NPN_PostURLNotify
538 return PostURLNotify(id, url, target, len, buf, file, false, 0);
541 NPError NPN_NewStream(NPP id,
542 NPMIMEType type,
543 const char* target,
544 NPStream** stream) {
545 // Requests creation of a new data stream produced by the plugin,
546 // consumed by the browser.
548 // Browser should put this stream into a window target.
550 // TODO: implement me
551 DVLOG(1) << "NPN_NewStream is not implemented yet.";
552 return NPERR_GENERIC_ERROR;
555 int32_t NPN_Write(NPP id, NPStream* stream, int32_t len, void* buffer) {
556 // Writes data to an existing Plugin-created stream.
558 // TODO: implement me
559 DVLOG(1) << "NPN_Write is not implemented yet.";
560 return NPERR_GENERIC_ERROR;
563 NPError NPN_DestroyStream(NPP id, NPStream* stream, NPReason reason) {
564 // Destroys a stream (could be created by plugin or browser).
566 // Reasons:
567 // NPRES_DONE - normal completion
568 // NPRES_USER_BREAK - user terminated
569 // NPRES_NETWORK_ERROR - network error (all errors fit here?)
573 scoped_refptr<PluginInstance> plugin(FindInstance(id));
574 if (plugin.get() == NULL) {
575 NOTREACHED();
576 return NPERR_GENERIC_ERROR;
579 return plugin->NPP_DestroyStream(stream, reason);
582 const char* NPN_UserAgent(NPP id) {
583 #if defined(OS_WIN)
584 // Flash passes in a null id during the NP_initialize call. We need to
585 // default to the Mozilla user agent if we don't have an NPP instance or
586 // else Flash won't request windowless mode.
587 bool use_mozilla_user_agent = true;
588 if (id) {
589 scoped_refptr<PluginInstance> plugin = FindInstance(id);
590 if (plugin.get() && !plugin->use_mozilla_user_agent())
591 use_mozilla_user_agent = false;
594 if (use_mozilla_user_agent)
595 return "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9a1) "
596 "Gecko/20061103 Firefox/2.0a1";
597 #endif
599 // Provide a consistent user-agent string with memory that lasts
600 // long enough for the caller to read it.
601 static base::LazyInstance<std::string>::Leaky leaky_user_agent =
602 LAZY_INSTANCE_INITIALIZER;
603 if (leaky_user_agent == NULL)
604 leaky_user_agent.Get() = content::GetContentClient()->GetUserAgent();
605 return leaky_user_agent.Get().c_str();
608 void NPN_Status(NPP id, const char* message) {
609 // Displays a message on the status line of the browser window.
611 // TODO: implement me
612 DVLOG(1) << "NPN_Status is not implemented yet.";
615 void NPN_InvalidateRect(NPP id, NPRect *invalidRect) {
616 // Invalidates specified drawing area prior to repainting or refreshing a
617 // windowless plugin
619 // Before a windowless plugin can refresh part of its drawing area, it must
620 // first invalidate it. This function causes the NPP_HandleEvent method to
621 // pass an update event or a paint message to the plugin. After calling
622 // this method, the plugin receives a paint message asynchronously.
624 // The browser redraws invalid areas of the document and any windowless
625 // plugins at regularly timed intervals. To force a paint message, the
626 // plugin can call NPN_ForceRedraw after calling this method.
628 scoped_refptr<PluginInstance> plugin(FindInstance(id));
629 if (plugin.get() && plugin->webplugin()) {
630 if (invalidRect) {
631 #if defined(OS_WIN)
632 if (!plugin->windowless()) {
633 RECT rect = {0};
634 rect.left = invalidRect->left;
635 rect.right = invalidRect->right;
636 rect.top = invalidRect->top;
637 rect.bottom = invalidRect->bottom;
638 ::InvalidateRect(plugin->window_handle(), &rect, false);
639 return;
641 #endif
642 gfx::Rect rect(invalidRect->left,
643 invalidRect->top,
644 invalidRect->right - invalidRect->left,
645 invalidRect->bottom - invalidRect->top);
646 plugin->webplugin()->InvalidateRect(rect);
647 } else {
648 plugin->webplugin()->Invalidate();
653 void NPN_InvalidateRegion(NPP id, NPRegion invalidRegion) {
654 // Invalidates a specified drawing region prior to repainting
655 // or refreshing a window-less plugin.
657 // Similar to NPN_InvalidateRect.
659 // TODO: this is overkill--add platform-specific region handling (at the
660 // very least, fetch the region's bounding box and pass it to InvalidateRect).
661 scoped_refptr<PluginInstance> plugin(FindInstance(id));
662 DCHECK(plugin.get() != NULL);
663 if (plugin.get() && plugin->webplugin())
664 plugin->webplugin()->Invalidate();
667 void NPN_ForceRedraw(NPP id) {
668 // Forces repaint for a windowless plugin.
670 // We deliberately do not implement this; we don't want plugins forcing
671 // synchronous paints.
674 NPError NPN_GetValue(NPP id, NPNVariable variable, void* value) {
675 // Allows the plugin to query the browser for information
677 // Variables:
678 // NPNVxDisplay (unix only)
679 // NPNVxtAppContext (unix only)
680 // NPNVnetscapeWindow (win only) - Gets the native window on which the
681 // plugin drawing occurs, returns HWND
682 // NPNVjavascriptEnabledBool: tells whether Javascript is enabled
683 // NPNVasdEnabledBool: tells whether SmartUpdate is enabled
684 // NPNVOfflineBool: tells whether offline-mode is enabled
686 NPError rv = NPERR_GENERIC_ERROR;
688 switch (static_cast<int>(variable)) {
689 case NPNVWindowNPObject: {
690 scoped_refptr<PluginInstance> plugin(FindInstance(id));
691 if (!plugin.get()) {
692 NOTREACHED();
693 return NPERR_INVALID_INSTANCE_ERROR;
695 NPObject *np_object = plugin->webplugin()->GetWindowScriptNPObject();
696 // Return value is expected to be retained, as
697 // described here:
698 // <http://www.mozilla.org/projects/plugins/npruntime.html#browseraccess>
699 if (np_object) {
700 WebBindings::retainObject(np_object);
701 void **v = (void **)value;
702 *v = np_object;
703 rv = NPERR_NO_ERROR;
704 } else {
705 NOTREACHED();
707 break;
709 case NPNVPluginElementNPObject: {
710 scoped_refptr<PluginInstance> plugin(FindInstance(id));
711 if (!plugin.get()) {
712 NOTREACHED();
713 return NPERR_INVALID_INSTANCE_ERROR;
715 NPObject *np_object = plugin->webplugin()->GetPluginElement();
716 // Return value is expected to be retained, as
717 // described here:
718 // <http://www.mozilla.org/projects/plugins/npruntime.html#browseraccess>
719 if (np_object) {
720 WebBindings::retainObject(np_object);
721 void** v = static_cast<void**>(value);
722 *v = np_object;
723 rv = NPERR_NO_ERROR;
724 } else {
725 NOTREACHED();
727 break;
729 #if !defined(OS_MACOSX) // OS X doesn't have windowed plugins.
730 case NPNVnetscapeWindow: {
731 scoped_refptr<PluginInstance> plugin = FindInstance(id);
732 if (!plugin.get()) {
733 NOTREACHED();
734 return NPERR_INVALID_INSTANCE_ERROR;
736 gfx::PluginWindowHandle handle = plugin->window_handle();
737 *((void**)value) = (void*)handle;
738 rv = NPERR_NO_ERROR;
739 break;
741 #endif
742 case NPNVjavascriptEnabledBool: {
743 // yes, JS is enabled.
744 *((void**)value) = (void*)1;
745 rv = NPERR_NO_ERROR;
746 break;
748 case NPNVSupportsWindowless: {
749 NPBool* supports_windowless = reinterpret_cast<NPBool*>(value);
750 *supports_windowless = true;
751 rv = NPERR_NO_ERROR;
752 break;
754 case NPNVprivateModeBool: {
755 NPBool* private_mode = reinterpret_cast<NPBool*>(value);
756 scoped_refptr<PluginInstance> plugin(FindInstance(id));
757 if (!plugin.get()) {
758 NOTREACHED();
759 return NPERR_INVALID_INSTANCE_ERROR;
761 *private_mode = plugin->webplugin()->IsOffTheRecord();
762 rv = NPERR_NO_ERROR;
763 break;
765 #if defined(OS_MACOSX)
766 case NPNVpluginDrawingModel: {
767 // return the drawing model that was negotiated when we initialized.
768 scoped_refptr<PluginInstance> plugin(FindInstance(id));
769 if (!plugin.get()) {
770 NOTREACHED();
771 return NPERR_INVALID_INSTANCE_ERROR;
773 *reinterpret_cast<int*>(value) = plugin->drawing_model();
774 rv = NPERR_NO_ERROR;
775 break;
777 case NPNVsupportsCoreGraphicsBool:
778 case NPNVsupportsCocoaBool: {
779 // These drawing and event models are always supported.
780 NPBool* supports_model = reinterpret_cast<NPBool*>(value);
781 *supports_model = true;
782 rv = NPERR_NO_ERROR;
783 break;
785 case NPNVsupportsInvalidatingCoreAnimationBool:
786 case NPNVsupportsCoreAnimationBool: {
787 NPBool* supports_model = reinterpret_cast<NPBool*>(value);
788 *supports_model = content::SupportsCoreAnimationPlugins();
789 rv = NPERR_NO_ERROR;
790 break;
792 #ifndef NP_NO_CARBON
793 case NPNVsupportsCarbonBool:
794 #endif
795 #ifndef NP_NO_QUICKDRAW
796 case NPNVsupportsQuickDrawBool:
797 #endif
798 case NPNVsupportsOpenGLBool: {
799 // These models are never supported. OpenGL was never widely supported,
800 // and QuickDraw and Carbon have been deprecated for quite some time.
801 NPBool* supports_model = reinterpret_cast<NPBool*>(value);
802 *supports_model = false;
803 rv = NPERR_NO_ERROR;
804 break;
806 case NPNVsupportsCompositingCoreAnimationPluginsBool: {
807 NPBool* supports_compositing = reinterpret_cast<NPBool*>(value);
808 *supports_compositing = content::SupportsCoreAnimationPlugins();
809 rv = NPERR_NO_ERROR;
810 break;
812 case NPNVsupportsUpdatedCocoaTextInputBool: {
813 // We support the clarifications to the Cocoa IME event spec.
814 NPBool* supports_update = reinterpret_cast<NPBool*>(value);
815 *supports_update = true;
816 rv = NPERR_NO_ERROR;
817 break;
819 #endif // OS_MACOSX
820 default:
821 DVLOG(1) << "NPN_GetValue(" << variable << ") is not implemented yet.";
822 break;
824 return rv;
827 NPError NPN_SetValue(NPP id, NPPVariable variable, void* value) {
828 // Allows the plugin to set various modes
830 scoped_refptr<PluginInstance> plugin(FindInstance(id));
831 if (!plugin.get()) {
832 NOTREACHED();
833 return NPERR_INVALID_INSTANCE_ERROR;
835 switch(variable) {
836 case NPPVpluginWindowBool: {
837 // Sets windowless mode for display of the plugin
838 // Note: the documentation at
839 // http://developer.mozilla.org/en/docs/NPN_SetValue is wrong. When
840 // value is NULL, the mode is set to true. This is the same way Mozilla
841 // works.
842 plugin->set_windowless(value == 0);
843 return NPERR_NO_ERROR;
845 case NPPVpluginTransparentBool: {
846 // Sets transparent mode for display of the plugin
848 // Transparent plugins require the browser to paint the background
849 // before having the plugin paint. By default, windowless plugins
850 // are transparent. Making a windowless plugin opaque means that
851 // the plugin does not require the browser to paint the background.
852 bool mode = (value != 0);
853 plugin->set_transparent(mode);
854 return NPERR_NO_ERROR;
856 case NPPVjavascriptPushCallerBool:
857 // Specifies whether you are pushing or popping the JSContext off.
858 // the stack
859 // TODO: implement me
860 DVLOG(1) << "NPN_SetValue(NPPVJavascriptPushCallerBool) is not "
861 "implemented.";
862 return NPERR_GENERIC_ERROR;
863 case NPPVpluginKeepLibraryInMemory:
864 // Tells browser that plugin library should live longer than usual.
865 // TODO: implement me
866 DVLOG(1) << "NPN_SetValue(NPPVpluginKeepLibraryInMemory) is not "
867 "implemented.";
868 return NPERR_GENERIC_ERROR;
869 #if defined(OS_MACOSX)
870 case NPPVpluginDrawingModel: {
871 intptr_t model = reinterpret_cast<intptr_t>(value);
872 if (model == NPDrawingModelCoreGraphics ||
873 ((model == NPDrawingModelInvalidatingCoreAnimation ||
874 model == NPDrawingModelCoreAnimation) &&
875 content::SupportsCoreAnimationPlugins())) {
876 plugin->set_drawing_model(static_cast<NPDrawingModel>(model));
877 return NPERR_NO_ERROR;
879 return NPERR_GENERIC_ERROR;
881 case NPPVpluginEventModel: {
882 // Only the Cocoa event model is supported.
883 intptr_t model = reinterpret_cast<intptr_t>(value);
884 if (model == NPEventModelCocoa) {
885 plugin->set_event_model(static_cast<NPEventModel>(model));
886 return NPERR_NO_ERROR;
888 return NPERR_GENERIC_ERROR;
890 #endif
891 default:
892 // TODO: implement me
893 DVLOG(1) << "NPN_SetValue(" << variable << ") is not implemented.";
894 break;
897 NOTREACHED();
898 return NPERR_GENERIC_ERROR;
901 void* NPN_GetJavaEnv() {
902 // TODO: implement me
903 DVLOG(1) << "NPN_GetJavaEnv is not implemented.";
904 return NULL;
907 void* NPN_GetJavaPeer(NPP) {
908 // TODO: implement me
909 DVLOG(1) << "NPN_GetJavaPeer is not implemented.";
910 return NULL;
913 void NPN_PushPopupsEnabledState(NPP id, NPBool enabled) {
914 scoped_refptr<PluginInstance> plugin(FindInstance(id));
915 if (plugin.get())
916 plugin->PushPopupsEnabledState(enabled ? true : false);
919 void NPN_PopPopupsEnabledState(NPP id) {
920 scoped_refptr<PluginInstance> plugin(FindInstance(id));
921 if (plugin.get())
922 plugin->PopPopupsEnabledState();
925 void NPN_PluginThreadAsyncCall(NPP id,
926 void (*func)(void*),
927 void* user_data) {
928 scoped_refptr<PluginInstance> plugin(FindInstance(id));
929 if (plugin.get())
930 plugin->PluginThreadAsyncCall(func, user_data);
933 NPError NPN_GetValueForURL(NPP id,
934 NPNURLVariable variable,
935 const char* url,
936 char** value,
937 uint32_t* len) {
938 if (!id)
939 return NPERR_INVALID_PARAM;
941 if (!url || !*url || !len)
942 return NPERR_INVALID_URL;
944 *len = 0;
945 std::string result;
947 switch (variable) {
948 case NPNURLVProxy: {
949 result = "DIRECT";
950 scoped_refptr<PluginInstance> plugin(FindInstance(id));
951 if (!plugin.get())
952 return NPERR_GENERIC_ERROR;
954 WebPlugin* webplugin = plugin->webplugin();
955 if (!webplugin)
956 return NPERR_GENERIC_ERROR;
958 if (!webplugin->FindProxyForUrl(GURL(std::string(url)), &result))
959 return NPERR_GENERIC_ERROR;
960 break;
962 case NPNURLVCookie: {
963 scoped_refptr<PluginInstance> plugin(FindInstance(id));
964 if (!plugin.get())
965 return NPERR_GENERIC_ERROR;
967 WebPlugin* webplugin = plugin->webplugin();
968 if (!webplugin)
969 return NPERR_GENERIC_ERROR;
971 // Bypass third-party cookie blocking by using the url as the
972 // first_party_for_cookies.
973 GURL cookies_url((std::string(url)));
974 result = webplugin->GetCookies(cookies_url, cookies_url);
975 break;
977 default:
978 return NPERR_GENERIC_ERROR;
981 // Allocate this using the NPAPI allocator. The plugin will call
982 // NPN_Free to free this.
983 *value = static_cast<char*>(NPN_MemAlloc(result.length() + 1));
984 base::strlcpy(*value, result.c_str(), result.length() + 1);
985 *len = result.length();
987 return NPERR_NO_ERROR;
990 NPError NPN_SetValueForURL(NPP id,
991 NPNURLVariable variable,
992 const char* url,
993 const char* value,
994 uint32_t len) {
995 if (!id)
996 return NPERR_INVALID_PARAM;
998 if (!url || !*url)
999 return NPERR_INVALID_URL;
1001 switch (variable) {
1002 case NPNURLVCookie: {
1003 scoped_refptr<PluginInstance> plugin(FindInstance(id));
1004 if (!plugin.get())
1005 return NPERR_GENERIC_ERROR;
1007 WebPlugin* webplugin = plugin->webplugin();
1008 if (!webplugin)
1009 return NPERR_GENERIC_ERROR;
1011 std::string cookie(value, len);
1012 GURL cookies_url((std::string(url)));
1013 webplugin->SetCookie(cookies_url, cookies_url, cookie);
1014 return NPERR_NO_ERROR;
1016 case NPNURLVProxy:
1017 // We don't support setting proxy values, fall through...
1018 break;
1019 default:
1020 // Fall through and return an error...
1021 break;
1024 return NPERR_GENERIC_ERROR;
1027 NPError NPN_GetAuthenticationInfo(NPP id,
1028 const char* protocol,
1029 const char* host,
1030 int32_t port,
1031 const char* scheme,
1032 const char* realm,
1033 char** username,
1034 uint32_t* ulen,
1035 char** password,
1036 uint32_t* plen) {
1037 if (!id || !protocol || !host || !scheme || !realm || !username ||
1038 !ulen || !password || !plen)
1039 return NPERR_INVALID_PARAM;
1041 // TODO: implement me (bug 23928)
1042 return NPERR_GENERIC_ERROR;
1045 uint32_t NPN_ScheduleTimer(NPP id,
1046 uint32_t interval,
1047 NPBool repeat,
1048 void (*func)(NPP id, uint32_t timer_id)) {
1049 scoped_refptr<PluginInstance> plugin(FindInstance(id));
1050 if (!plugin.get())
1051 return 0;
1053 return plugin->ScheduleTimer(interval, repeat, func);
1056 void NPN_UnscheduleTimer(NPP id, uint32_t timer_id) {
1057 scoped_refptr<PluginInstance> plugin(FindInstance(id));
1058 if (plugin.get())
1059 plugin->UnscheduleTimer(timer_id);
1062 NPError NPN_PopUpContextMenu(NPP id, NPMenu* menu) {
1063 if (!menu)
1064 return NPERR_INVALID_PARAM;
1066 scoped_refptr<PluginInstance> plugin(FindInstance(id));
1067 if (plugin.get()) {
1068 return plugin->PopUpContextMenu(menu);
1070 NOTREACHED();
1071 return NPERR_GENERIC_ERROR;
1074 NPBool NPN_ConvertPoint(NPP id, double sourceX, double sourceY,
1075 NPCoordinateSpace sourceSpace,
1076 double *destX, double *destY,
1077 NPCoordinateSpace destSpace) {
1078 scoped_refptr<PluginInstance> plugin(FindInstance(id));
1079 if (plugin.get()) {
1080 return plugin->ConvertPoint(
1081 sourceX, sourceY, sourceSpace, destX, destY, destSpace);
1083 NOTREACHED();
1084 return false;
1087 NPBool NPN_HandleEvent(NPP id, void *event, NPBool handled) {
1088 // TODO: Implement advanced key handling: http://crbug.com/46578
1089 NOTIMPLEMENTED();
1090 return false;
1093 NPBool NPN_UnfocusInstance(NPP id, NPFocusDirection direction) {
1094 // TODO: Implement advanced key handling: http://crbug.com/46578
1095 NOTIMPLEMENTED();
1096 return false;
1099 void NPN_URLRedirectResponse(NPP instance, void* notify_data, NPBool allow) {
1100 scoped_refptr<PluginInstance> plugin(FindInstance(instance));
1101 if (plugin.get()) {
1102 plugin->URLRedirectResponse(!!allow, notify_data);
1106 } // extern "C"