Run Tizen Webapps in single process mode
[platform/framework/web/crosswalk-tizen.git] / atom / browser / api / atom_api_protocol.cc
1 // Copyright (c) 2013 GitHub, Inc.
2 // Use of this source code is governed by the MIT license that can be
3 // found in the LICENSE file.
4
5 #include "atom/browser/api/atom_api_protocol.h"
6
7 #include "atom/browser/atom_browser_client.h"
8 #include "atom/browser/atom_browser_main_parts.h"
9 #include "atom/browser/browser.h"
10 #include "atom/browser/net/url_request_async_asar_job.h"
11 #include "atom/browser/net/url_request_buffer_job.h"
12 #include "atom/browser/net/url_request_fetch_job.h"
13 #include "atom/browser/net/url_request_string_job.h"
14 #include "atom/common/native_mate_converters/callback.h"
15 #include "atom/common/native_mate_converters/value_converter.h"
16 #include "atom/common/node_includes.h"
17 #include "atom/common/options_switches.h"
18 #include "base/command_line.h"
19 #include "base/strings/string_util.h"
20 #include "content/public/browser/child_process_security_policy.h"
21 #include "native_mate/dictionary.h"
22 #include "tizen/common/env_variables.h"
23 #include "url/url_util.h"
24
25 using content::BrowserThread;
26
27 namespace atom {
28
29 namespace api {
30
31 namespace {
32
33 // List of registered custom standard schemes.
34 std::vector<std::string> g_standard_schemes;
35
36 // Clear protocol handlers in IO thread.
37 void ClearJobFactoryInIO(
38     scoped_refptr<brightray::URLRequestContextGetter> request_context_getter) {
39   auto job_factory = static_cast<AtomURLRequestJobFactory*>(
40       request_context_getter->job_factory());
41   job_factory->Clear();
42 }
43
44 }  // namespace
45
46 std::vector<std::string> GetStandardSchemes() {
47   return g_standard_schemes;
48 }
49
50 void RegisterStandardSchemes(const std::vector<std::string>& schemes,
51                              mate::Arguments* args) {
52   g_standard_schemes = schemes;
53
54   auto* policy = content::ChildProcessSecurityPolicy::GetInstance();
55   for (const std::string& scheme : schemes) {
56     url::AddStandardScheme(scheme.c_str(), url::SCHEME_WITHOUT_PORT);
57     policy->RegisterWebSafeScheme(scheme);
58   }
59
60   // add switches to register as standard
61   base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
62       atom::switches::kStandardSchemes, base::JoinString(schemes, ","));
63
64   mate::Dictionary opts;
65   bool secure = false;
66   if (args->GetNext(&opts) && opts.Get("secure", &secure) && secure) {
67     // add switches to register as secure
68     base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
69       atom::switches::kSecureSchemes, base::JoinString(schemes, ","));
70   }
71 }
72
73 Protocol::Protocol(v8::Isolate* isolate, AtomBrowserContext* browser_context)
74     : request_context_getter_(browser_context->GetRequestContext()),
75       weak_factory_(this) {
76   Init(isolate);
77 }
78
79 Protocol::~Protocol() {
80   content::BrowserThread::PostTask(
81       content::BrowserThread::IO, FROM_HERE,
82       base::Bind(ClearJobFactoryInIO, request_context_getter_));
83 }
84
85 void Protocol::RegisterServiceWorkerSchemes(
86     const std::vector<std::string>& schemes) {
87   atom::AtomBrowserClient::SetCustomServiceWorkerSchemes(schemes);
88 }
89
90 void Protocol::UnregisterProtocol(
91     const std::string& scheme, mate::Arguments* args) {
92   CompletionCallback callback;
93   args->GetNext(&callback);
94   content::BrowserThread::PostTaskAndReplyWithResult(
95       content::BrowserThread::IO, FROM_HERE,
96       base::Bind(&Protocol::UnregisterProtocolInIO,
97                  request_context_getter_, scheme),
98       base::Bind(&Protocol::OnIOCompleted,
99                  GetWeakPtr(), callback));
100 }
101
102 // static
103 Protocol::ProtocolError Protocol::UnregisterProtocolInIO(
104     scoped_refptr<brightray::URLRequestContextGetter> request_context_getter,
105     const std::string& scheme) {
106   auto job_factory = static_cast<AtomURLRequestJobFactory*>(
107       request_context_getter->job_factory());
108   if (!job_factory->HasProtocolHandler(scheme))
109     return PROTOCOL_NOT_REGISTERED;
110   job_factory->SetProtocolHandler(scheme, nullptr);
111   return PROTOCOL_OK;
112 }
113
114 void Protocol::IsProtocolHandled(const std::string& scheme,
115                                  const BooleanCallback& callback) {
116   content::BrowserThread::PostTaskAndReplyWithResult(
117       content::BrowserThread::IO, FROM_HERE,
118       base::Bind(&Protocol::IsProtocolHandledInIO,
119                  request_context_getter_, scheme),
120       callback);
121 }
122
123 // static
124 bool Protocol::IsProtocolHandledInIO(
125     scoped_refptr<brightray::URLRequestContextGetter> request_context_getter,
126     const std::string& scheme) {
127   return request_context_getter->job_factory()->IsHandledProtocol(scheme);
128 }
129
130 void Protocol::UninterceptProtocol(
131     const std::string& scheme, mate::Arguments* args) {
132   CompletionCallback callback;
133   args->GetNext(&callback);
134   content::BrowserThread::PostTaskAndReplyWithResult(
135       content::BrowserThread::IO, FROM_HERE,
136       base::Bind(&Protocol::UninterceptProtocolInIO,
137                  request_context_getter_, scheme),
138       base::Bind(&Protocol::OnIOCompleted,
139                  GetWeakPtr(), callback));
140 }
141
142 // static
143 Protocol::ProtocolError Protocol::UninterceptProtocolInIO(
144     scoped_refptr<brightray::URLRequestContextGetter> request_context_getter,
145     const std::string& scheme) {
146   return static_cast<AtomURLRequestJobFactory*>(
147       request_context_getter->job_factory())->UninterceptProtocol(scheme) ?
148           PROTOCOL_OK : PROTOCOL_NOT_INTERCEPTED;
149 }
150
151 void Protocol::OnIOCompleted(
152     const CompletionCallback& callback, ProtocolError error) {
153   // The completion callback is optional.
154   if (callback.is_null())
155     return;
156
157   if (!::tizen::is_single_process)
158     v8::Locker locker(isolate());
159   v8::HandleScope handle_scope(isolate());
160
161   if (error == PROTOCOL_OK) {
162     callback.Run(v8::Null(isolate()));
163   } else {
164     std::string str = ErrorCodeToString(error);
165     callback.Run(v8::Exception::Error(mate::StringToV8(isolate(), str)));
166   }
167 }
168
169 std::string Protocol::ErrorCodeToString(ProtocolError error) {
170   switch (error) {
171     case PROTOCOL_FAIL: return "Failed to manipulate protocol factory";
172     case PROTOCOL_REGISTERED: return "The scheme has been registered";
173     case PROTOCOL_NOT_REGISTERED: return "The scheme has not been registered";
174     case PROTOCOL_INTERCEPTED: return "The scheme has been intercepted";
175     case PROTOCOL_NOT_INTERCEPTED: return "The scheme has not been intercepted";
176     default: return "Unexpected error";
177   }
178 }
179
180 AtomURLRequestJobFactory* Protocol::GetJobFactoryInIO() const {
181   request_context_getter_->GetURLRequestContext();  // Force init.
182   return static_cast<AtomURLRequestJobFactory*>(
183       static_cast<brightray::URLRequestContextGetter*>(
184           request_context_getter_.get())->job_factory());
185 }
186
187 // static
188 mate::Handle<Protocol> Protocol::Create(
189     v8::Isolate* isolate, AtomBrowserContext* browser_context) {
190   return mate::CreateHandle(isolate, new Protocol(isolate, browser_context));
191 }
192
193 // static
194 void Protocol::BuildPrototype(
195     v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> prototype) {
196   prototype->SetClassName(mate::StringToV8(isolate, "Protocol"));
197   mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
198       .SetMethod("registerServiceWorkerSchemes",
199                  &Protocol::RegisterServiceWorkerSchemes)
200       .SetMethod("registerStringProtocol",
201                  &Protocol::RegisterProtocol<URLRequestStringJob>)
202       .SetMethod("registerBufferProtocol",
203                  &Protocol::RegisterProtocol<URLRequestBufferJob>)
204       .SetMethod("registerFileProtocol",
205                  &Protocol::RegisterProtocol<URLRequestAsyncAsarJob>)
206       .SetMethod("registerHttpProtocol",
207                  &Protocol::RegisterProtocol<URLRequestFetchJob>)
208       .SetMethod("unregisterProtocol", &Protocol::UnregisterProtocol)
209       .SetMethod("isProtocolHandled", &Protocol::IsProtocolHandled)
210       .SetMethod("interceptStringProtocol",
211                  &Protocol::InterceptProtocol<URLRequestStringJob>)
212       .SetMethod("interceptBufferProtocol",
213                  &Protocol::InterceptProtocol<URLRequestBufferJob>)
214       .SetMethod("interceptFileProtocol",
215                  &Protocol::InterceptProtocol<URLRequestAsyncAsarJob>)
216       .SetMethod("interceptHttpProtocol",
217                  &Protocol::InterceptProtocol<URLRequestFetchJob>)
218       .SetMethod("uninterceptProtocol", &Protocol::UninterceptProtocol);
219 }
220
221 }  // namespace api
222
223 }  // namespace atom
224
225 namespace {
226
227 void RegisterStandardSchemes(
228     const std::vector<std::string>& schemes, mate::Arguments* args) {
229   if (atom::Browser::Get()->is_ready()) {
230     args->ThrowError("protocol.registerStandardSchemes should be called before "
231                      "app is ready");
232     return;
233   }
234
235   atom::api::RegisterStandardSchemes(schemes, args);
236 }
237
238 void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
239                 v8::Local<v8::Context> context, void* priv) {
240   v8::Isolate* isolate = context->GetIsolate();
241   mate::Dictionary dict(isolate, exports);
242   dict.SetMethod("registerStandardSchemes", &RegisterStandardSchemes);
243   dict.SetMethod("getStandardSchemes", &atom::api::GetStandardSchemes);
244 }
245
246 }  // namespace
247
248 NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_browser_protocol, Initialize)