atom_api_protocol.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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. v8::Local<v8::Promise> Protocol::IsProtocolHandled(const std::string& scheme) {
  158. util::Promise promise(isolate());
  159. v8::Local<v8::Promise> handle = promise.GetHandle();
  160. auto* getter = static_cast<URLRequestContextGetter*>(
  161. browser_context_->GetRequestContext());
  162. base::PostTaskWithTraitsAndReplyWithResult(
  163. FROM_HERE, {content::BrowserThread::IO},
  164. base::BindOnce(&IsProtocolHandledInIO, base::RetainedRef(getter), scheme),
  165. base::BindOnce(util::Promise::ResolvePromise<bool>, std::move(promise)));
  166. return handle;
  167. }
  168. void Protocol::UninterceptProtocol(const std::string& scheme,
  169. mate::Arguments* args) {
  170. CompletionCallback callback;
  171. args->GetNext(&callback);
  172. auto* getter = static_cast<URLRequestContextGetter*>(
  173. browser_context_->GetRequestContext());
  174. base::PostTaskWithTraitsAndReplyWithResult(
  175. FROM_HERE, {content::BrowserThread::IO},
  176. base::BindOnce(&Protocol::UninterceptProtocolInIO,
  177. base::RetainedRef(getter), scheme),
  178. base::BindOnce(&Protocol::OnIOCompleted, GetWeakPtr(), callback));
  179. }
  180. // static
  181. Protocol::ProtocolError Protocol::UninterceptProtocolInIO(
  182. scoped_refptr<URLRequestContextGetter> request_context_getter,
  183. const std::string& scheme) {
  184. return request_context_getter->job_factory()->UninterceptProtocol(scheme)
  185. ? PROTOCOL_OK
  186. : PROTOCOL_NOT_INTERCEPTED;
  187. }
  188. void Protocol::OnIOCompleted(const CompletionCallback& callback,
  189. ProtocolError error) {
  190. // The completion callback is optional.
  191. if (callback.is_null())
  192. return;
  193. v8::Locker locker(isolate());
  194. v8::HandleScope handle_scope(isolate());
  195. if (error == PROTOCOL_OK) {
  196. callback.Run(v8::Null(isolate()));
  197. } else {
  198. std::string str = ErrorCodeToString(error);
  199. callback.Run(v8::Exception::Error(mate::StringToV8(isolate(), str)));
  200. }
  201. }
  202. std::string Protocol::ErrorCodeToString(ProtocolError error) {
  203. switch (error) {
  204. case PROTOCOL_FAIL:
  205. return "Failed to manipulate protocol factory";
  206. case PROTOCOL_REGISTERED:
  207. return "The scheme has been registered";
  208. case PROTOCOL_NOT_REGISTERED:
  209. return "The scheme has not been registered";
  210. case PROTOCOL_INTERCEPTED:
  211. return "The scheme has been intercepted";
  212. case PROTOCOL_NOT_INTERCEPTED:
  213. return "The scheme has not been intercepted";
  214. default:
  215. return "Unexpected error";
  216. }
  217. }
  218. // static
  219. mate::Handle<Protocol> Protocol::Create(v8::Isolate* isolate,
  220. AtomBrowserContext* browser_context) {
  221. return mate::CreateHandle(isolate, new Protocol(isolate, browser_context));
  222. }
  223. // static
  224. void Protocol::BuildPrototype(v8::Isolate* isolate,
  225. v8::Local<v8::FunctionTemplate> prototype) {
  226. prototype->SetClassName(mate::StringToV8(isolate, "Protocol"));
  227. mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
  228. .SetMethod("registerStringProtocol",
  229. &Protocol::RegisterProtocol<URLRequestStringJob>)
  230. .SetMethod("registerBufferProtocol",
  231. &Protocol::RegisterProtocol<URLRequestBufferJob>)
  232. .SetMethod("registerFileProtocol",
  233. &Protocol::RegisterProtocol<URLRequestAsyncAsarJob>)
  234. .SetMethod("registerHttpProtocol",
  235. &Protocol::RegisterProtocol<URLRequestFetchJob>)
  236. .SetMethod("registerStreamProtocol",
  237. &Protocol::RegisterProtocol<URLRequestStreamJob>)
  238. .SetMethod("unregisterProtocol", &Protocol::UnregisterProtocol)
  239. .SetMethod("isProtocolHandled", &Protocol::IsProtocolHandled)
  240. .SetMethod("interceptStringProtocol",
  241. &Protocol::InterceptProtocol<URLRequestStringJob>)
  242. .SetMethod("interceptBufferProtocol",
  243. &Protocol::InterceptProtocol<URLRequestBufferJob>)
  244. .SetMethod("interceptFileProtocol",
  245. &Protocol::InterceptProtocol<URLRequestAsyncAsarJob>)
  246. .SetMethod("interceptHttpProtocol",
  247. &Protocol::InterceptProtocol<URLRequestFetchJob>)
  248. .SetMethod("interceptStreamProtocol",
  249. &Protocol::InterceptProtocol<URLRequestStreamJob>)
  250. .SetMethod("uninterceptProtocol", &Protocol::UninterceptProtocol);
  251. }
  252. } // namespace api
  253. } // namespace atom
  254. namespace {
  255. void RegisterSchemesAsPrivileged(v8::Local<v8::Value> val,
  256. mate::Arguments* args) {
  257. if (atom::Browser::Get()->is_ready()) {
  258. args->ThrowError(
  259. "protocol.registerSchemesAsPrivileged should be called before "
  260. "app is ready");
  261. return;
  262. }
  263. atom::api::RegisterSchemesAsPrivileged(val, args);
  264. }
  265. void Initialize(v8::Local<v8::Object> exports,
  266. v8::Local<v8::Value> unused,
  267. v8::Local<v8::Context> context,
  268. void* priv) {
  269. v8::Isolate* isolate = context->GetIsolate();
  270. mate::Dictionary dict(isolate, exports);
  271. dict.SetMethod("registerSchemesAsPrivileged", &RegisterSchemesAsPrivileged);
  272. dict.SetMethod("getStandardSchemes", &atom::api::GetStandardSchemes);
  273. }
  274. } // namespace
  275. NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_protocol, Initialize)