atom_api_protocol.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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. #include "atom/browser/api/atom_api_protocol.h"
  5. #include "atom/browser/atom_browser_client.h"
  6. #include "atom/browser/atom_browser_main_parts.h"
  7. #include "atom/browser/browser.h"
  8. #include "atom/browser/net/url_request_async_asar_job.h"
  9. #include "atom/browser/net/url_request_buffer_job.h"
  10. #include "atom/browser/net/url_request_fetch_job.h"
  11. #include "atom/browser/net/url_request_stream_job.h"
  12. #include "atom/browser/net/url_request_string_job.h"
  13. #include "atom/common/native_mate_converters/callback.h"
  14. #include "atom/common/native_mate_converters/value_converter.h"
  15. #include "atom/common/node_includes.h"
  16. #include "atom/common/options_switches.h"
  17. #include "base/command_line.h"
  18. #include "base/strings/string_util.h"
  19. #include "content/public/browser/child_process_security_policy.h"
  20. #include "native_mate/dictionary.h"
  21. #include "url/url_util.h"
  22. using content::BrowserThread;
  23. namespace {
  24. // List of registered custom standard schemes.
  25. std::vector<std::string> g_standard_schemes;
  26. struct SchemeOptions {
  27. bool standard = false;
  28. bool secure = false;
  29. bool bypassCSP = false;
  30. bool allowServiceWorkers = false;
  31. bool supportFetchAPI = false;
  32. bool corsEnabled = false;
  33. };
  34. struct CustomScheme {
  35. std::string scheme;
  36. SchemeOptions options;
  37. };
  38. } // namespace
  39. namespace mate {
  40. template <>
  41. struct Converter<CustomScheme> {
  42. static bool FromV8(v8::Isolate* isolate,
  43. v8::Local<v8::Value> val,
  44. CustomScheme* out) {
  45. mate::Dictionary dict;
  46. if (!ConvertFromV8(isolate, val, &dict))
  47. return false;
  48. if (!dict.Get("scheme", &(out->scheme)))
  49. return false;
  50. mate::Dictionary opt;
  51. // options are optional. Default values specified in SchemeOptions are used
  52. if (dict.Get("privileges", &opt)) {
  53. opt.Get("standard", &(out->options.standard));
  54. opt.Get("supportFetchAPI", &(out->options.supportFetchAPI));
  55. opt.Get("secure", &(out->options.secure));
  56. opt.Get("bypassCSP", &(out->options.bypassCSP));
  57. opt.Get("allowServiceWorkers", &(out->options.allowServiceWorkers));
  58. opt.Get("supportFetchAPI", &(out->options.supportFetchAPI));
  59. opt.Get("corsEnabled", &(out->options.corsEnabled));
  60. }
  61. return true;
  62. }
  63. };
  64. } // namespace mate
  65. namespace atom {
  66. namespace api {
  67. std::vector<std::string> GetStandardSchemes() {
  68. return g_standard_schemes;
  69. }
  70. void RegisterSchemesAsPrivileged(v8::Local<v8::Value> val,
  71. mate::Arguments* args) {
  72. std::vector<CustomScheme> custom_schemes;
  73. if (!mate::ConvertFromV8(args->isolate(), val, &custom_schemes)) {
  74. args->ThrowError("Argument must be an array of custom schemes.");
  75. return;
  76. }
  77. std::vector<std::string> secure_schemes, cspbypassing_schemes, fetch_schemes,
  78. service_worker_schemes, cors_schemes;
  79. for (const auto& custom_scheme : custom_schemes) {
  80. // Register scheme to privileged list (https, wss, data, chrome-extension)
  81. if (custom_scheme.options.standard) {
  82. auto* policy = content::ChildProcessSecurityPolicy::GetInstance();
  83. url::AddStandardScheme(custom_scheme.scheme.c_str(),
  84. url::SCHEME_WITH_HOST);
  85. g_standard_schemes.push_back(custom_scheme.scheme);
  86. policy->RegisterWebSafeScheme(custom_scheme.scheme);
  87. }
  88. if (custom_scheme.options.secure) {
  89. secure_schemes.push_back(custom_scheme.scheme);
  90. url::AddSecureScheme(custom_scheme.scheme.c_str());
  91. }
  92. if (custom_scheme.options.bypassCSP) {
  93. cspbypassing_schemes.push_back(custom_scheme.scheme);
  94. url::AddCSPBypassingScheme(custom_scheme.scheme.c_str());
  95. }
  96. if (custom_scheme.options.corsEnabled) {
  97. cors_schemes.push_back(custom_scheme.scheme);
  98. url::AddCorsEnabledScheme(custom_scheme.scheme.c_str());
  99. }
  100. if (custom_scheme.options.supportFetchAPI) {
  101. fetch_schemes.push_back(custom_scheme.scheme);
  102. }
  103. if (custom_scheme.options.allowServiceWorkers) {
  104. service_worker_schemes.push_back(custom_scheme.scheme);
  105. }
  106. }
  107. const auto AppendSchemesToCmdLine = [](const char* switch_name,
  108. std::vector<std::string> schemes) {
  109. // Add the schemes to command line switches, so child processes can also
  110. // register them.
  111. base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
  112. switch_name, base::JoinString(schemes, ","));
  113. };
  114. AppendSchemesToCmdLine(atom::switches::kSecureSchemes, secure_schemes);
  115. AppendSchemesToCmdLine(atom::switches::kBypassCSPSchemes,
  116. cspbypassing_schemes);
  117. AppendSchemesToCmdLine(atom::switches::kCORSSchemes, cors_schemes);
  118. AppendSchemesToCmdLine(atom::switches::kFetchSchemes, fetch_schemes);
  119. AppendSchemesToCmdLine(atom::switches::kServiceWorkerSchemes,
  120. service_worker_schemes);
  121. AppendSchemesToCmdLine(atom::switches::kStandardSchemes, g_standard_schemes);
  122. }
  123. Protocol::Protocol(v8::Isolate* isolate, AtomBrowserContext* browser_context)
  124. : browser_context_(browser_context), weak_factory_(this) {
  125. Init(isolate);
  126. }
  127. Protocol::~Protocol() {}
  128. void Protocol::UnregisterProtocol(const std::string& scheme,
  129. mate::Arguments* args) {
  130. CompletionCallback callback;
  131. args->GetNext(&callback);
  132. auto* getter = static_cast<URLRequestContextGetter*>(
  133. browser_context_->GetRequestContext());
  134. base::PostTaskWithTraitsAndReplyWithResult(
  135. FROM_HERE, {content::BrowserThread::IO},
  136. base::BindOnce(&Protocol::UnregisterProtocolInIO,
  137. base::RetainedRef(getter), scheme),
  138. base::BindOnce(&Protocol::OnIOCompleted, GetWeakPtr(), callback));
  139. }
  140. // static
  141. Protocol::ProtocolError Protocol::UnregisterProtocolInIO(
  142. scoped_refptr<URLRequestContextGetter> request_context_getter,
  143. const std::string& scheme) {
  144. auto* job_factory = request_context_getter->job_factory();
  145. if (!job_factory->HasProtocolHandler(scheme))
  146. return PROTOCOL_NOT_REGISTERED;
  147. job_factory->SetProtocolHandler(scheme, nullptr);
  148. return PROTOCOL_OK;
  149. }
  150. bool IsProtocolHandledInIO(
  151. scoped_refptr<URLRequestContextGetter> request_context_getter,
  152. const std::string& scheme) {
  153. bool is_handled =
  154. request_context_getter->job_factory()->IsHandledProtocol(scheme);
  155. return is_handled;
  156. }
  157. void PromiseCallback(util::Promise promise, bool handled) {
  158. promise.Resolve(handled);
  159. }
  160. v8::Local<v8::Promise> Protocol::IsProtocolHandled(const std::string& scheme) {
  161. util::Promise promise(isolate());
  162. v8::Local<v8::Promise> handle = promise.GetHandle();
  163. auto* getter = static_cast<URLRequestContextGetter*>(
  164. browser_context_->GetRequestContext());
  165. base::PostTaskWithTraitsAndReplyWithResult(
  166. FROM_HERE, {content::BrowserThread::IO},
  167. base::BindOnce(&IsProtocolHandledInIO, base::RetainedRef(getter), scheme),
  168. base::BindOnce(&PromiseCallback, std::move(promise)));
  169. return handle;
  170. }
  171. void Protocol::UninterceptProtocol(const std::string& scheme,
  172. mate::Arguments* args) {
  173. CompletionCallback callback;
  174. args->GetNext(&callback);
  175. auto* getter = static_cast<URLRequestContextGetter*>(
  176. browser_context_->GetRequestContext());
  177. base::PostTaskWithTraitsAndReplyWithResult(
  178. FROM_HERE, {content::BrowserThread::IO},
  179. base::BindOnce(&Protocol::UninterceptProtocolInIO,
  180. base::RetainedRef(getter), scheme),
  181. base::BindOnce(&Protocol::OnIOCompleted, GetWeakPtr(), callback));
  182. }
  183. // static
  184. Protocol::ProtocolError Protocol::UninterceptProtocolInIO(
  185. scoped_refptr<URLRequestContextGetter> request_context_getter,
  186. const std::string& scheme) {
  187. return request_context_getter->job_factory()->UninterceptProtocol(scheme)
  188. ? PROTOCOL_OK
  189. : PROTOCOL_NOT_INTERCEPTED;
  190. }
  191. void Protocol::OnIOCompleted(const CompletionCallback& callback,
  192. ProtocolError error) {
  193. // The completion callback is optional.
  194. if (callback.is_null())
  195. return;
  196. v8::Locker locker(isolate());
  197. v8::HandleScope handle_scope(isolate());
  198. if (error == PROTOCOL_OK) {
  199. callback.Run(v8::Null(isolate()));
  200. } else {
  201. std::string str = ErrorCodeToString(error);
  202. callback.Run(v8::Exception::Error(mate::StringToV8(isolate(), str)));
  203. }
  204. }
  205. std::string Protocol::ErrorCodeToString(ProtocolError error) {
  206. switch (error) {
  207. case PROTOCOL_FAIL:
  208. return "Failed to manipulate protocol factory";
  209. case PROTOCOL_REGISTERED:
  210. return "The scheme has been registered";
  211. case PROTOCOL_NOT_REGISTERED:
  212. return "The scheme has not been registered";
  213. case PROTOCOL_INTERCEPTED:
  214. return "The scheme has been intercepted";
  215. case PROTOCOL_NOT_INTERCEPTED:
  216. return "The scheme has not been intercepted";
  217. default:
  218. return "Unexpected error";
  219. }
  220. }
  221. // static
  222. mate::Handle<Protocol> Protocol::Create(v8::Isolate* isolate,
  223. AtomBrowserContext* browser_context) {
  224. return mate::CreateHandle(isolate, new Protocol(isolate, browser_context));
  225. }
  226. // static
  227. void Protocol::BuildPrototype(v8::Isolate* isolate,
  228. v8::Local<v8::FunctionTemplate> prototype) {
  229. prototype->SetClassName(mate::StringToV8(isolate, "Protocol"));
  230. mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
  231. .SetMethod("registerStringProtocol",
  232. &Protocol::RegisterProtocol<URLRequestStringJob>)
  233. .SetMethod("registerBufferProtocol",
  234. &Protocol::RegisterProtocol<URLRequestBufferJob>)
  235. .SetMethod("registerFileProtocol",
  236. &Protocol::RegisterProtocol<URLRequestAsyncAsarJob>)
  237. .SetMethod("registerHttpProtocol",
  238. &Protocol::RegisterProtocol<URLRequestFetchJob>)
  239. .SetMethod("registerStreamProtocol",
  240. &Protocol::RegisterProtocol<URLRequestStreamJob>)
  241. .SetMethod("unregisterProtocol", &Protocol::UnregisterProtocol)
  242. .SetMethod("isProtocolHandled", &Protocol::IsProtocolHandled)
  243. .SetMethod("interceptStringProtocol",
  244. &Protocol::InterceptProtocol<URLRequestStringJob>)
  245. .SetMethod("interceptBufferProtocol",
  246. &Protocol::InterceptProtocol<URLRequestBufferJob>)
  247. .SetMethod("interceptFileProtocol",
  248. &Protocol::InterceptProtocol<URLRequestAsyncAsarJob>)
  249. .SetMethod("interceptHttpProtocol",
  250. &Protocol::InterceptProtocol<URLRequestFetchJob>)
  251. .SetMethod("interceptStreamProtocol",
  252. &Protocol::InterceptProtocol<URLRequestStreamJob>)
  253. .SetMethod("uninterceptProtocol", &Protocol::UninterceptProtocol);
  254. }
  255. } // namespace api
  256. } // namespace atom
  257. namespace {
  258. void RegisterSchemesAsPrivileged(v8::Local<v8::Value> val,
  259. mate::Arguments* args) {
  260. if (atom::Browser::Get()->is_ready()) {
  261. args->ThrowError(
  262. "protocol.registerSchemesAsPrivileged should be called before "
  263. "app is ready");
  264. return;
  265. }
  266. atom::api::RegisterSchemesAsPrivileged(val, args);
  267. }
  268. void Initialize(v8::Local<v8::Object> exports,
  269. v8::Local<v8::Value> unused,
  270. v8::Local<v8::Context> context,
  271. void* priv) {
  272. v8::Isolate* isolate = context->GetIsolate();
  273. mate::Dictionary dict(isolate, exports);
  274. dict.SetMethod("registerSchemesAsPrivileged", &RegisterSchemesAsPrivileged);
  275. dict.SetMethod("getStandardSchemes", &atom::api::GetStandardSchemes);
  276. }
  277. } // namespace
  278. NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_protocol, Initialize)