3a0064687f29156e583fe9b1e50e483e25372332
[platform/framework/web/crosswalk.git] / src / xwalk / extensions / common / xwalk_extension_server.cc
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.
4
5 #include "xwalk/extensions/common/xwalk_extension_server.h"
6
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"
19
20 namespace xwalk {
21 namespace extensions {
22
23 // Threshold to determine using shared memory or message
24 const size_t kInlineMessageMaxSize = 256 * 1024;
25
26 XWalkExtensionServer::XWalkExtensionServer()
27     : sender_(NULL),
28       renderer_process_handle_(base::kNullProcessHandle),
29       permissions_delegate_(NULL) {}
30
31 XWalkExtensionServer::~XWalkExtensionServer() {
32   DeleteInstanceMap();
33   STLDeleteValues(&extensions_);
34 }
35
36 bool XWalkExtensionServer::OnMessageReceived(const IPC::Message& message) {
37   bool handled = true;
38   IPC_BEGIN_MESSAGE_MAP(XWalkExtensionServer, message)
39     IPC_MESSAGE_HANDLER(XWalkExtensionServerMsg_CreateInstance,
40         OnCreateInstance)
41     IPC_MESSAGE_HANDLER(XWalkExtensionServerMsg_DestroyInstance,
42         OnDestroyInstance)
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,
49         OnGetExtensions)
50     IPC_MESSAGE_UNHANDLED(handled = false)
51   IPC_END_MESSAGE_MAP()
52
53   return handled;
54 }
55
56 void XWalkExtensionServer::OnChannelConnected(int32 peer_pid) {
57   CHECK(base::OpenProcessHandle(peer_pid, &renderer_process_handle_));
58 }
59
60 void XWalkExtensionServer::OnCreateInstance(int64_t instance_id,
61     std::string name) {
62   ExtensionMap::const_iterator it = extensions_.find(name);
63
64   if (it == extensions_.end()) {
65     LOG(WARNING) << "Can't create instance of extension: " << name
66         << ". Extension is not registered.";
67     return;
68   }
69
70   XWalkExtensionInstance* instance = it->second->CreateInstance();
71   if (!instance) {
72     LOG(WARNING) << "Can't create instance of extension: " << name
73         << ". CreateInstance() return invalid pointer.";
74     return;
75   }
76
77   instance->SetPostMessageCallback(
78       base::Bind(&XWalkExtensionServer::PostMessageToJSCallback,
79                  base::Unretained(this), instance_id));
80
81   instance->SetSendSyncReplyCallback(
82       base::Bind(&XWalkExtensionServer::SendSyncReplyToJSCallback,
83                  base::Unretained(this), instance_id));
84
85   InstanceExecutionData data;
86   data.instance = instance;
87   data.pending_reply = NULL;
88
89   instances_[instance_id] = data;
90 }
91
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: "
97                  << instance_id;
98     return;
99   }
100
101   const InstanceExecutionData& data = it->second;
102
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());
112 }
113
114 void XWalkExtensionServer::Initialize(IPC::Sender* sender) {
115   base::AutoLock l(sender_lock_);
116   DCHECK(!sender_);
117   sender_ = sender;
118 }
119
120 bool XWalkExtensionServer::Send(IPC::Message* msg) {
121   base::AutoLock l(sender_lock_);
122   if (!sender_)
123     return false;
124   return sender_->Send(msg);
125 }
126
127 namespace {
128
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) {
133     char c = name[i];
134     if (IsAsciiDigit(c)) {
135       if (!digit_or_underscore_allowed)
136         return false;
137     } else if (c == '_') {
138       if (!digit_or_underscore_allowed)
139         return false;
140     } else if (c == '.') {
141       if (!dot_allowed)
142         return false;
143       dot_allowed = false;
144       digit_or_underscore_allowed = false;
145     } else if (IsAsciiAlpha(c)) {
146       dot_allowed = true;
147       digit_or_underscore_allowed = true;
148     } else {
149       return false;
150     }
151   }
152
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.
155   return dot_allowed;
156 }
157
158 }  // namespace
159
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();
165     return false;
166   }
167
168   if (ContainsKey(extension_symbols_, extension->name())) {
169     LOG(WARNING) << "Ignoring extension with name already registered: "
170                  << extension->name();
171     return false;
172   }
173
174   if (!ValidateExtensionEntryPoints(extension->entry_points())) {
175     LOG(WARNING) << "Ignoring extension '" << extension->name()
176                  << "' with invalid entry point.";
177     return false;
178   }
179
180   const std::vector<std::string>& entry_points = extension->entry_points();
181
182   for (const std::string& entry_point : entry_points) {
183     extension_symbols_.insert(entry_point);
184   }
185
186   std::string name = extension->name();
187   extension_symbols_.insert(name);
188   extensions_[name] = extension.release();
189   return true;
190 }
191
192 bool XWalkExtensionServer::ContainsExtension(
193     const std::string& extension_name) const {
194   return ContainsKey(extensions_, extension_name);
195 }
196
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());
201
202   scoped_ptr<IPC::Message> message(
203       new XWalkExtensionClientMsg_PostMessageToJS(instance_id, wrapped_msg));
204   if (message->size() <= kInlineMessageMaxSize) {
205     Send(message.release());
206     return;
207   }
208
209   base::SharedMemoryCreateOptions options;
210   options.size = message->size();
211   options.share_read_only = true;
212
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";
216     return;
217   }
218
219   memcpy(shared_memory.memory(), message->data(), message->size());
220
221   base::SharedMemoryHandle handle;
222   shared_memory.GiveReadOnlyToProcess(renderer_process_handle_, &handle);
223
224   Send(new XWalkExtensionClientMsg_PostOutOfLineMessageToJS(handle,
225                                                             message->size()));
226 }
227
228 void XWalkExtensionServer::SendSyncReplyToJSCallback(
229     int64_t instance_id, scoped_ptr<base::Value> reply) {
230
231   InstanceMap::iterator it = instances_.find(instance_id);
232   if (it == instances_.end()) {
233     LOG(WARNING) << "Can't SendSyncMessage to invalid Extension instance id: "
234                  << instance_id;
235     return;
236   }
237
238   InstanceExecutionData& data = it->second;
239   if (!data.pending_reply) {
240     LOG(WARNING) << "There's no pending SyncMessage for instance id: "
241                  << instance_id;
242     return;
243   }
244
245   base::ListValue wrapped_reply;
246   wrapped_reply.Append(reply.release());
247
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);
255
256   data.pending_reply = NULL;
257 }
258
259 void XWalkExtensionServer::DeleteInstanceMap() {
260   InstanceMap::iterator it = instances_.begin();
261   int pending_replies_left = 0;
262
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;
268     }
269   }
270
271   instances_.clear();
272
273   if (pending_replies_left > 0) {
274     LOG(WARNING) << pending_replies_left
275                  << " pending replies left when destroying server.";
276   }
277 }
278
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))
283       return false;
284
285     if (ContainsKey(extension_symbols_, entry_point)) {
286       LOG(WARNING) << "Entry point '" << entry_point
287                    << "' clashes with another extension entry point.";
288       return false;
289     }
290   }
291
292   return true;
293 }
294
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: "
300                  << instance_id;
301     return;
302   }
303
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;
308     return;
309   }
310
311   data.pending_reply = ipc_reply;
312
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;
322
323   instance->HandleSyncMessage(value.Pass());
324 }
325
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;
330     return;
331   }
332
333   InstanceExecutionData& data = it->second;
334
335   delete data.instance;
336   instances_.erase(it);
337
338   Send(new XWalkExtensionClientMsg_InstanceDestroyed(instance_id));
339 }
340
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;
347
348     extension_parameters.name = extension->name();
349     extension_parameters.js_api = extension->javascript_api();
350
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);
354     }
355
356     reply->push_back(extension_parameters);
357   }
358 }
359
360 void XWalkExtensionServer::Invalidate() {
361   base::AutoLock l(sender_lock_);
362   sender_ = NULL;
363 }
364
365 namespace {
366 base::FilePath::StringType GetNativeLibraryPattern() {
367   const base::string16 library_pattern = base::GetNativeLibraryName(
368       base::UTF8ToUTF16("*"));
369 #if defined(OS_WIN)
370   return library_pattern;
371 #else
372   return base::UTF16ToUTF8(library_pattern);
373 #endif
374 }
375 }  // namespace
376
377 std::vector<std::string> RegisterExternalExtensionsInDirectory(
378     XWalkExtensionServer* server, const base::FilePath& dir,
379     scoped_ptr<base::ValueMap> runtime_variables) {
380   CHECK(server);
381
382   std::vector<std::string> registered_extensions;
383
384   if (!base::DirectoryExists(dir)) {
385     LOG(WARNING) << "Couldn't load external extensions from non-existent"
386                  << " directory " << dir.AsUTF8Unsafe();
387     return registered_extensions;
388   }
389
390   base::FileEnumerator libraries(
391       dir, false, base::FileEnumerator::FILES, GetNativeLibraryPattern());
392
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));
397
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());
403
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>());
410     } else {
411       LOG(WARNING) << "Failed to initialize extension: "
412                    << extension_path.AsUTF8Unsafe();
413     }
414   }
415
416   return registered_extensions;
417 }
418
419 bool ValidateExtensionNameForTesting(const std::string& extension_name) {
420   return ValidateExtensionIdentifier(extension_name);
421 }
422
423 }  // namespace extensions
424 }  // namespace xwalk
425