ResourceLoader.cpp 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Base64.h>
  27. #include <AK/Debug.h>
  28. #include <AK/JsonObject.h>
  29. #include <LibCore/EventLoop.h>
  30. #include <LibCore/File.h>
  31. #include <LibProtocol/Client.h>
  32. #include <LibProtocol/Download.h>
  33. #include <LibWeb/Loader/ContentFilter.h>
  34. #include <LibWeb/Loader/LoadRequest.h>
  35. #include <LibWeb/Loader/Resource.h>
  36. #include <LibWeb/Loader/ResourceLoader.h>
  37. namespace Web {
  38. ResourceLoader& ResourceLoader::the()
  39. {
  40. static ResourceLoader* s_the;
  41. if (!s_the)
  42. s_the = &ResourceLoader::construct().leak_ref();
  43. return *s_the;
  44. }
  45. ResourceLoader::ResourceLoader()
  46. : m_protocol_client(Protocol::Client::construct())
  47. , m_user_agent("Mozilla/4.0 (SerenityOS; x86) LibWeb+LibJS (Not KHTML, nor Gecko) LibWeb")
  48. {
  49. }
  50. void ResourceLoader::load_sync(const URL& url, Function<void(ReadonlyBytes, const HashMap<String, String, CaseInsensitiveStringTraits>& response_headers)> success_callback, Function<void(const String&)> error_callback)
  51. {
  52. Core::EventLoop loop;
  53. load(
  54. url,
  55. [&](auto data, auto& response_headers) {
  56. success_callback(data, response_headers);
  57. loop.quit(0);
  58. },
  59. [&](auto& string) {
  60. if (error_callback)
  61. error_callback(string);
  62. loop.quit(0);
  63. });
  64. loop.exec();
  65. }
  66. static HashMap<LoadRequest, NonnullRefPtr<Resource>> s_resource_cache;
  67. RefPtr<Resource> ResourceLoader::load_resource(Resource::Type type, const LoadRequest& request)
  68. {
  69. if (!request.is_valid())
  70. return nullptr;
  71. auto it = s_resource_cache.find(request);
  72. if (it != s_resource_cache.end()) {
  73. if (it->value->type() != type) {
  74. dbgln("FIXME: Not using cached resource for {} since there's a type mismatch.", request.url());
  75. } else {
  76. dbgln<debug_cache>("Reusing cached resource for: {}", request.url());
  77. return it->value;
  78. }
  79. }
  80. auto resource = Resource::create({}, type, request);
  81. s_resource_cache.set(request, resource);
  82. load(
  83. request,
  84. [=](auto data, auto& headers) {
  85. const_cast<Resource&>(*resource).did_load({}, data, headers);
  86. },
  87. [=](auto& error) {
  88. const_cast<Resource&>(*resource).did_fail({}, error);
  89. });
  90. return resource;
  91. }
  92. void ResourceLoader::load(const LoadRequest& request, Function<void(ReadonlyBytes, const HashMap<String, String, CaseInsensitiveStringTraits>& response_headers)> success_callback, Function<void(const String&)> error_callback)
  93. {
  94. auto& url = request.url();
  95. if (is_port_blocked(url.port())) {
  96. dbgln("ResourceLoader::load: Error: blocked port {} from URL {}", url.port(), url);
  97. return;
  98. }
  99. if (ContentFilter::the().is_filtered(url)) {
  100. dbgln("\033[32;1mResourceLoader::load: URL was filtered! {}\033[0m", url);
  101. error_callback("URL was filtered");
  102. return;
  103. }
  104. if (url.protocol() == "about") {
  105. dbgln("Loading about: URL {}", url);
  106. deferred_invoke([success_callback = move(success_callback)](auto&) {
  107. success_callback(String::empty().to_byte_buffer(), {});
  108. });
  109. return;
  110. }
  111. if (url.protocol() == "data") {
  112. dbgln("ResourceLoader loading a data URL with mime-type: '{}', base64={}, payload='{}'",
  113. url.data_mime_type(),
  114. url.data_payload_is_base64(),
  115. url.data_payload());
  116. ByteBuffer data;
  117. if (url.data_payload_is_base64())
  118. data = decode_base64(url.data_payload());
  119. else
  120. data = url.data_payload().to_byte_buffer();
  121. deferred_invoke([data = move(data), success_callback = move(success_callback)](auto&) {
  122. success_callback(data, {});
  123. });
  124. return;
  125. }
  126. if (url.protocol() == "file") {
  127. auto f = Core::File::construct();
  128. f->set_filename(url.path());
  129. if (!f->open(Core::IODevice::OpenMode::ReadOnly)) {
  130. dbgln("ResourceLoader::load: Error: {}", f->error_string());
  131. if (error_callback)
  132. error_callback(f->error_string());
  133. return;
  134. }
  135. auto data = f->read_all();
  136. deferred_invoke([data = move(data), success_callback = move(success_callback)](auto&) {
  137. success_callback(data, {});
  138. });
  139. return;
  140. }
  141. if (url.protocol() == "http" || url.protocol() == "https" || url.protocol() == "gemini") {
  142. HashMap<String, String> headers;
  143. headers.set("User-Agent", m_user_agent);
  144. headers.set("Accept-Encoding", "gzip");
  145. for (auto& it : request.headers()) {
  146. headers.set(it.key, it.value);
  147. }
  148. auto download = protocol_client().start_download(request.method(), url.to_string(), headers, request.body());
  149. if (!download) {
  150. if (error_callback)
  151. error_callback("Failed to initiate load");
  152. return;
  153. }
  154. download->on_buffered_download_finish = [this, success_callback = move(success_callback), error_callback = move(error_callback), download](bool success, auto, auto& response_headers, auto status_code, ReadonlyBytes payload) {
  155. if (status_code.has_value() && status_code.value() >= 400 && status_code.value() <= 499) {
  156. if (error_callback)
  157. error_callback(String::formatted("HTTP error ({})", status_code.value()));
  158. return;
  159. }
  160. --m_pending_loads;
  161. if (on_load_counter_change)
  162. on_load_counter_change();
  163. if (!success) {
  164. if (error_callback)
  165. error_callback("HTTP load failed");
  166. return;
  167. }
  168. deferred_invoke([download](auto&) {
  169. // Clear circular reference of `download` captured by copy
  170. const_cast<Protocol::Download&>(*download).on_buffered_download_finish = nullptr;
  171. });
  172. success_callback(payload, response_headers);
  173. };
  174. download->set_should_buffer_all_input(true);
  175. download->on_certificate_requested = []() -> Protocol::Download::CertificateAndKey {
  176. return {};
  177. };
  178. ++m_pending_loads;
  179. if (on_load_counter_change)
  180. on_load_counter_change();
  181. return;
  182. }
  183. if (error_callback)
  184. error_callback(String::formatted("Protocol not implemented: {}", url.protocol()));
  185. }
  186. void ResourceLoader::load(const URL& url, Function<void(ReadonlyBytes, const HashMap<String, String, CaseInsensitiveStringTraits>& response_headers)> success_callback, Function<void(const String&)> error_callback)
  187. {
  188. LoadRequest request;
  189. request.set_url(url);
  190. load(request, move(success_callback), move(error_callback));
  191. }
  192. bool ResourceLoader::is_port_blocked(int port)
  193. {
  194. int ports[] { 1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42,
  195. 43, 53, 77, 79, 87, 95, 101, 102, 103, 104, 109, 110, 111, 113,
  196. 115, 117, 119, 123, 135, 139, 143, 179, 389, 465, 512, 513, 514,
  197. 515, 526, 530, 531, 532, 540, 556, 563, 587, 601, 636, 993, 995,
  198. 2049, 3659, 4045, 6000, 6379, 6665, 6666, 6667, 6668, 6669, 9000 };
  199. for (auto blocked_port : ports)
  200. if (port == blocked_port)
  201. return true;
  202. return false;
  203. }
  204. }