ResourceLoader.cpp 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. /*
  2. * Copyright (c) 2018-2020, 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/JsonObject.h>
  28. #include <AK/SharedBuffer.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/LoadRequest.h>
  34. #include <LibWeb/Loader/Resource.h>
  35. #include <LibWeb/Loader/ResourceLoader.h>
  36. //#define CACHE_DEBUG
  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(const ByteBuffer&, 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. dbg() << "FIXME: Not using cached resource for " << request.url() << " since there's a type mismatch.";
  75. } else {
  76. #ifdef CACHE_DEBUG
  77. dbg() << "Reusing cached resource for: " << request.url();
  78. #endif
  79. return it->value;
  80. }
  81. }
  82. auto resource = Resource::create({}, type, request);
  83. s_resource_cache.set(request, resource);
  84. load(
  85. request.url(),
  86. [=](auto& data, auto& headers) {
  87. const_cast<Resource&>(*resource).did_load({}, data, headers);
  88. },
  89. [=](auto& error) {
  90. const_cast<Resource&>(*resource).did_fail({}, error);
  91. });
  92. return resource;
  93. }
  94. void ResourceLoader::load(const URL& url, Function<void(const ByteBuffer&, const HashMap<String, String, CaseInsensitiveStringTraits>& response_headers)> success_callback, Function<void(const String&)> error_callback)
  95. {
  96. if (is_port_blocked(url.port())) {
  97. dbg() << "ResourceLoader::load: Error: blocked port " << url.port() << " for URL: " << url;
  98. return;
  99. }
  100. if (url.protocol() == "about") {
  101. dbg() << "Loading about: URL " << url;
  102. deferred_invoke([success_callback = move(success_callback)](auto&) {
  103. success_callback(ByteBuffer::wrap(const_cast<char*>(String::empty().characters()), 1), {});
  104. });
  105. return;
  106. }
  107. if (url.protocol() == "data") {
  108. dbg() << "ResourceLoader loading a data URL with mime-type: '" << url.data_mime_type() << "', base64=" << url.data_payload_is_base64() << ", payload='" << url.data_payload() << "'";
  109. ByteBuffer data;
  110. if (url.data_payload_is_base64())
  111. data = decode_base64(url.data_payload());
  112. else
  113. data = url.data_payload().to_byte_buffer();
  114. deferred_invoke([data = move(data), success_callback = move(success_callback)](auto&) {
  115. success_callback(data, {});
  116. });
  117. return;
  118. }
  119. if (url.protocol() == "file") {
  120. auto f = Core::File::construct();
  121. f->set_filename(url.path());
  122. if (!f->open(Core::IODevice::OpenMode::ReadOnly)) {
  123. dbg() << "ResourceLoader::load: Error: " << f->error_string();
  124. if (error_callback)
  125. error_callback(f->error_string());
  126. return;
  127. }
  128. auto data = f->read_all();
  129. deferred_invoke([data = move(data), success_callback = move(success_callback)](auto&) {
  130. success_callback(data, {});
  131. });
  132. return;
  133. }
  134. if (url.protocol() == "http" || url.protocol() == "https" || url.protocol() == "gemini") {
  135. HashMap<String, String> headers;
  136. headers.set("User-Agent", m_user_agent);
  137. auto download = protocol_client().start_download(url.to_string(), headers);
  138. if (!download) {
  139. if (error_callback)
  140. error_callback("Failed to initiate load");
  141. return;
  142. }
  143. download->on_finish = [this, success_callback = move(success_callback), error_callback = move(error_callback)](bool success, const ByteBuffer& payload, auto, auto& response_headers, auto status_code) {
  144. --m_pending_loads;
  145. if (on_load_counter_change)
  146. on_load_counter_change();
  147. if (!success) {
  148. if (error_callback)
  149. error_callback("HTTP load failed");
  150. return;
  151. }
  152. if (status_code.has_value() && status_code.value() >= 400 && status_code.value() <= 499) {
  153. if (error_callback)
  154. error_callback(String::format("HTTP error (%u)", status_code.value()));
  155. return;
  156. }
  157. success_callback(ByteBuffer::copy(payload.data(), payload.size()), response_headers);
  158. };
  159. download->on_certificate_requested = []() -> Protocol::Download::CertificateAndKey {
  160. return {};
  161. };
  162. ++m_pending_loads;
  163. if (on_load_counter_change)
  164. on_load_counter_change();
  165. return;
  166. }
  167. if (error_callback)
  168. error_callback(String::format("Protocol not implemented: %s", url.protocol().characters()));
  169. }
  170. bool ResourceLoader::is_port_blocked(int port)
  171. {
  172. int ports[] { 1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42,
  173. 43, 53, 77, 79, 87, 95, 101, 102, 103, 104, 109, 110, 111, 113,
  174. 115, 117, 119, 123, 135, 139, 143, 179, 389, 465, 512, 513, 514,
  175. 515, 526, 530, 531, 532, 540, 556, 563, 587, 601, 636, 993, 995,
  176. 2049, 3659, 4045, 6000, 6379, 6665, 6666, 6667, 6668, 6669, 9000 };
  177. for (auto blocked_port : ports)
  178. if (port == blocked_port)
  179. return true;
  180. return false;
  181. }
  182. }