1 // Copyright (c) 2013 Intel Corporation. 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 "xwalk/extensions/common/xwalk_extension_server.h"
7 #include "base/file_util.h"
8 #include "base/files/file_enumerator.h"
9 #include "base/files/file_path.h"
10 #include "base/memory/shared_memory.h"
11 #include "base/strings/string16.h"
12 #include "base/strings/utf_string_conversions.h"
13 #include "base/stl_util.h"
14 #include "content/public/browser/render_process_host.h"
15 #include "ipc/ipc_message.h"
16 #include "ipc/ipc_sender.h"
17 #include "xwalk/extensions/common/xwalk_extension_messages.h"
18 #include "xwalk/extensions/common/xwalk_external_extension.h"
21 namespace extensions {
23 // Threshold to determine using shared memory or message
24 const size_t kInlineMessageMaxSize = 256 * 1024;
26 XWalkExtensionServer::XWalkExtensionServer()
28 renderer_process_handle_(base::kNullProcessHandle),
29 permissions_delegate_(NULL) {}
31 XWalkExtensionServer::~XWalkExtensionServer() {
33 STLDeleteValues(&extensions_);
36 bool XWalkExtensionServer::OnMessageReceived(const IPC::Message& message) {
38 IPC_BEGIN_MESSAGE_MAP(XWalkExtensionServer, message)
39 IPC_MESSAGE_HANDLER(XWalkExtensionServerMsg_CreateInstance,
41 IPC_MESSAGE_HANDLER(XWalkExtensionServerMsg_DestroyInstance,
43 IPC_MESSAGE_HANDLER(XWalkExtensionServerMsg_PostMessageToNative,
44 OnPostMessageToNative)
45 IPC_MESSAGE_HANDLER_DELAY_REPLY(
46 XWalkExtensionServerMsg_SendSyncMessageToNative,
47 OnSendSyncMessageToNative)
48 IPC_MESSAGE_HANDLER(XWalkExtensionServerMsg_GetExtensions,
50 IPC_MESSAGE_UNHANDLED(handled = false)
56 void XWalkExtensionServer::OnChannelConnected(int32 peer_pid) {
57 CHECK(base::OpenProcessHandle(peer_pid, &renderer_process_handle_));
60 void XWalkExtensionServer::OnCreateInstance(int64_t instance_id,
62 ExtensionMap::const_iterator it = extensions_.find(name);
64 if (it == extensions_.end()) {
65 LOG(WARNING) << "Can't create instance of extension: " << name
66 << ". Extension is not registered.";
70 XWalkExtensionInstance* instance = it->second->CreateInstance();
72 LOG(WARNING) << "Can't create instance of extension: " << name
73 << ". CreateInstance() return invalid pointer.";
77 instance->SetPostMessageCallback(
78 base::Bind(&XWalkExtensionServer::PostMessageToJSCallback,
79 base::Unretained(this), instance_id));
81 instance->SetSendSyncReplyCallback(
82 base::Bind(&XWalkExtensionServer::SendSyncReplyToJSCallback,
83 base::Unretained(this), instance_id));
85 InstanceExecutionData data;
86 data.instance = instance;
87 data.pending_reply = NULL;
89 instances_[instance_id] = data;
92 void XWalkExtensionServer::OnPostMessageToNative(int64_t instance_id,
93 const base::ListValue& msg) {
94 InstanceMap::const_iterator it = instances_.find(instance_id);
95 if (it == instances_.end()) {
96 LOG(WARNING) << "Can't PostMessage to invalid Extension instance id: "
101 const InstanceExecutionData& data = it->second;
103 // The const_cast is needed to remove the only Value contained by the
104 // ListValue (which is solely used as wrapper, since Value doesn't
105 // have param traits for serialization) and we pass the ownership to to
106 // HandleMessage. It is safe to do this because the |msg| won't be used
107 // anywhere else when this function returns. Saves a DeepCopy(), which
108 // can be costly depending on the size of Value.
109 scoped_ptr<base::Value> value;
110 const_cast<base::ListValue*>(&msg)->Remove(0, &value);
111 data.instance->HandleMessage(value.Pass());
114 void XWalkExtensionServer::Initialize(IPC::Sender* sender) {
115 base::AutoLock l(sender_lock_);
120 bool XWalkExtensionServer::Send(IPC::Message* msg) {
121 base::AutoLock l(sender_lock_);
124 return sender_->Send(msg);
129 bool ValidateExtensionIdentifier(const std::string& name) {
130 bool dot_allowed = false;
131 bool digit_or_underscore_allowed = false;
132 for (size_t i = 0; i < name.size(); ++i) {
134 if (IsAsciiDigit(c)) {
135 if (!digit_or_underscore_allowed)
137 } else if (c == '_') {
138 if (!digit_or_underscore_allowed)
140 } else if (c == '.') {
144 digit_or_underscore_allowed = false;
145 } else if (IsAsciiAlpha(c)) {
147 digit_or_underscore_allowed = true;
153 // If after going through the entire name we finish with dot_allowed, it means
154 // the previous character is not a dot, so it's a valid name.
160 bool XWalkExtensionServer::RegisterExtension(
161 scoped_ptr<XWalkExtension> extension) {
162 if (!ValidateExtensionIdentifier(extension->name())) {
163 LOG(WARNING) << "Ignoring extension with invalid name: "
164 << extension->name();
168 if (ContainsKey(extension_symbols_, extension->name())) {
169 LOG(WARNING) << "Ignoring extension with name already registered: "
170 << extension->name();
174 if (!ValidateExtensionEntryPoints(extension->entry_points())) {
175 LOG(WARNING) << "Ignoring extension '" << extension->name()
176 << "' with invalid entry point.";
180 const std::vector<std::string>& entry_points = extension->entry_points();
182 for (const std::string& entry_point : entry_points) {
183 extension_symbols_.insert(entry_point);
186 std::string name = extension->name();
187 extension_symbols_.insert(name);
188 extensions_[name] = extension.release();
192 bool XWalkExtensionServer::ContainsExtension(
193 const std::string& extension_name) const {
194 return ContainsKey(extensions_, extension_name);
197 void XWalkExtensionServer::PostMessageToJSCallback(
198 int64_t instance_id, scoped_ptr<base::Value> msg) {
199 base::ListValue wrapped_msg;
200 wrapped_msg.Append(msg.release());
202 scoped_ptr<IPC::Message> message(
203 new XWalkExtensionClientMsg_PostMessageToJS(instance_id, wrapped_msg));
204 if (message->size() <= kInlineMessageMaxSize) {
205 Send(message.release());
209 base::SharedMemoryCreateOptions options;
210 options.size = message->size();
211 options.share_read_only = true;
213 base::SharedMemory shared_memory;
214 if (!shared_memory.Create(options) || !shared_memory.Map(message->size())) {
215 LOG(WARNING) << "Can't create shared memory to send out of line message";
219 memcpy(shared_memory.memory(), message->data(), message->size());
221 base::SharedMemoryHandle handle;
222 shared_memory.GiveReadOnlyToProcess(renderer_process_handle_, &handle);
224 Send(new XWalkExtensionClientMsg_PostOutOfLineMessageToJS(handle,
228 void XWalkExtensionServer::SendSyncReplyToJSCallback(
229 int64_t instance_id, scoped_ptr<base::Value> reply) {
231 InstanceMap::iterator it = instances_.find(instance_id);
232 if (it == instances_.end()) {
233 LOG(WARNING) << "Can't SendSyncMessage to invalid Extension instance id: "
238 InstanceExecutionData& data = it->second;
239 if (!data.pending_reply) {
240 LOG(WARNING) << "There's no pending SyncMessage for instance id: "
245 base::ListValue wrapped_reply;
246 wrapped_reply.Append(reply.release());
248 // TODO(cmarcelo): we need to inline WriteReplyParams here because it takes
249 // a copy of the parameter and ListValue is noncopyable. This may be
250 // improved in ipc_message_utils.h so we don't need to inline the code here.
251 XWalkExtensionServerMsg_SendSyncMessageToNative::ReplyParam
252 reply_param(wrapped_reply);
253 IPC::WriteParam(data.pending_reply, reply_param);
254 Send(data.pending_reply);
256 data.pending_reply = NULL;
259 void XWalkExtensionServer::DeleteInstanceMap() {
260 InstanceMap::iterator it = instances_.begin();
261 int pending_replies_left = 0;
263 for (; it != instances_.end(); ++it) {
264 delete it->second.instance;
265 if (it->second.pending_reply) {
266 pending_replies_left++;
267 delete it->second.pending_reply;
273 if (pending_replies_left > 0) {
274 LOG(WARNING) << pending_replies_left
275 << " pending replies left when destroying server.";
279 bool XWalkExtensionServer::ValidateExtensionEntryPoints(
280 const std::vector<std::string>& entry_points) {
281 for (const std::string& entry_point : entry_points) {
282 if (!ValidateExtensionIdentifier(entry_point))
285 if (ContainsKey(extension_symbols_, entry_point)) {
286 LOG(WARNING) << "Entry point '" << entry_point
287 << "' clashes with another extension entry point.";
295 void XWalkExtensionServer::OnSendSyncMessageToNative(int64_t instance_id,
296 const base::ListValue& msg, IPC::Message* ipc_reply) {
297 InstanceMap::iterator it = instances_.find(instance_id);
298 if (it == instances_.end()) {
299 LOG(WARNING) << "Can't SendSyncMessage to invalid Extension instance id: "
304 InstanceExecutionData& data = it->second;
305 if (data.pending_reply) {
306 LOG(WARNING) << "There's already a pending Sync Message for "
307 << "Extension instance id: " << instance_id;
311 data.pending_reply = ipc_reply;
313 // The const_cast is needed to remove the only Value contained by the
314 // ListValue (which is solely used as wrapper, since Value doesn't
315 // have param traits for serialization) and we pass the ownership to to
316 // HandleMessage. It is safe to do this because the |msg| won't be used
317 // anywhere else when this function returns. Saves a DeepCopy(), which
318 // can be costly depending on the size of Value.
319 scoped_ptr<base::Value> value;
320 const_cast<base::ListValue*>(&msg)->Remove(0, &value);
321 XWalkExtensionInstance* instance = data.instance;
323 instance->HandleSyncMessage(value.Pass());
326 void XWalkExtensionServer::OnDestroyInstance(int64_t instance_id) {
327 InstanceMap::iterator it = instances_.find(instance_id);
328 if (it == instances_.end()) {
329 LOG(WARNING) << "Can't destroy inexistent instance:" << instance_id;
333 InstanceExecutionData& data = it->second;
335 delete data.instance;
336 instances_.erase(it);
338 Send(new XWalkExtensionClientMsg_InstanceDestroyed(instance_id));
341 void XWalkExtensionServer::OnGetExtensions(
342 std::vector<XWalkExtensionServerMsg_ExtensionRegisterParams>* reply) {
343 ExtensionMap::iterator it = extensions_.begin();
344 for (; it != extensions_.end(); ++it) {
345 XWalkExtensionServerMsg_ExtensionRegisterParams extension_parameters;
346 XWalkExtension* extension = it->second;
348 extension_parameters.name = extension->name();
349 extension_parameters.js_api = extension->javascript_api();
351 const std::vector<std::string>& entry_points = extension->entry_points();
352 for (const std::string& entry_point : entry_points) {
353 extension_parameters.entry_points.push_back(entry_point);
356 reply->push_back(extension_parameters);
360 void XWalkExtensionServer::Invalidate() {
361 base::AutoLock l(sender_lock_);
366 base::FilePath::StringType GetNativeLibraryPattern() {
367 const base::string16 library_pattern = base::GetNativeLibraryName(
368 base::UTF8ToUTF16("*"));
370 return library_pattern;
372 return base::UTF16ToUTF8(library_pattern);
377 std::vector<std::string> RegisterExternalExtensionsInDirectory(
378 XWalkExtensionServer* server, const base::FilePath& dir,
379 scoped_ptr<base::ValueMap> runtime_variables) {
382 std::vector<std::string> registered_extensions;
384 if (!base::DirectoryExists(dir)) {
385 LOG(WARNING) << "Couldn't load external extensions from non-existent"
386 << " directory " << dir.AsUTF8Unsafe();
387 return registered_extensions;
390 base::FileEnumerator libraries(
391 dir, false, base::FileEnumerator::FILES, GetNativeLibraryPattern());
393 for (base::FilePath extension_path = libraries.Next();
394 !extension_path.empty(); extension_path = libraries.Next()) {
395 scoped_ptr<XWalkExternalExtension> extension(
396 new XWalkExternalExtension(extension_path));
398 // Let the extension know about its own path, so it can be used
399 // as an identifier in case you have symlinks to extensions to force it
400 // load multiple times.
401 (*runtime_variables)["extension_path"] =
402 new base::StringValue(extension_path.AsUTF8Unsafe());
404 extension->set_runtime_variables(*runtime_variables);
405 if (server->permissions_delegate())
406 extension->set_permissions_delegate(server->permissions_delegate());
407 if (extension->Initialize()) {
408 registered_extensions.push_back(extension->name());
409 server->RegisterExtension(extension.PassAs<XWalkExtension>());
411 LOG(WARNING) << "Failed to initialize extension: "
412 << extension_path.AsUTF8Unsafe();
416 return registered_extensions;
419 bool ValidateExtensionNameForTesting(const std::string& extension_name) {
420 return ValidateExtensionIdentifier(extension_name);
423 } // namespace extensions