Resource.cpp 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <AK/Function.h>
  8. #include <LibCore/MimeData.h>
  9. #include <LibTextCodec/Decoder.h>
  10. #include <LibWeb/HTML/HTMLImageElement.h>
  11. #include <LibWeb/Loader/ImageResource.h>
  12. #include <LibWeb/Loader/Resource.h>
  13. #include <LibWeb/Loader/ResourceLoader.h>
  14. #include <LibWeb/Platform/EventLoopPlugin.h>
  15. namespace Web {
  16. NonnullRefPtr<Resource> Resource::create(Badge<ResourceLoader>, Type type, LoadRequest const& request)
  17. {
  18. if (type == Type::Image)
  19. return adopt_ref(*new ImageResource(request));
  20. return adopt_ref(*new Resource(type, request));
  21. }
  22. Resource::Resource(Type type, LoadRequest const& request)
  23. : m_request(request)
  24. , m_type(type)
  25. {
  26. }
  27. Resource::Resource(Type type, Resource& resource)
  28. : m_request(resource.m_request)
  29. , m_encoded_data(move(resource.m_encoded_data))
  30. , m_type(type)
  31. , m_loaded(resource.m_loaded)
  32. , m_failed(resource.m_failed)
  33. , m_error(move(resource.m_error))
  34. , m_encoding(move(resource.m_encoding))
  35. , m_mime_type(move(resource.m_mime_type))
  36. , m_response_headers(move(resource.m_response_headers))
  37. , m_status_code(move(resource.m_status_code))
  38. {
  39. ResourceLoader::the().evict_from_cache(m_request);
  40. }
  41. Resource::~Resource() = default;
  42. void Resource::for_each_client(Function<void(ResourceClient&)> callback)
  43. {
  44. Vector<WeakPtr<ResourceClient>, 16> clients_copy;
  45. clients_copy.ensure_capacity(m_clients.size());
  46. for (auto* client : m_clients)
  47. clients_copy.append(client->make_weak_ptr());
  48. for (auto client : clients_copy) {
  49. if (client)
  50. callback(*client);
  51. }
  52. }
  53. static Optional<DeprecatedString> encoding_from_content_type(DeprecatedString const& content_type)
  54. {
  55. auto offset = content_type.find("charset="sv);
  56. if (offset.has_value()) {
  57. auto encoding = content_type.substring(offset.value() + 8, content_type.length() - offset.value() - 8).to_lowercase();
  58. if (encoding.length() >= 2 && encoding.starts_with('"') && encoding.ends_with('"'))
  59. return encoding.substring(1, encoding.length() - 2);
  60. if (encoding.length() >= 2 && encoding.starts_with('\'') && encoding.ends_with('\''))
  61. return encoding.substring(1, encoding.length() - 2);
  62. return encoding;
  63. }
  64. return {};
  65. }
  66. static DeprecatedString mime_type_from_content_type(DeprecatedString const& content_type)
  67. {
  68. auto offset = content_type.find(';');
  69. if (offset.has_value())
  70. return content_type.substring(0, offset.value()).to_lowercase();
  71. return content_type;
  72. }
  73. static bool is_valid_encoding(StringView encoding)
  74. {
  75. return TextCodec::decoder_for(encoding).has_value();
  76. }
  77. void Resource::did_load(Badge<ResourceLoader>, ReadonlyBytes data, HashMap<DeprecatedString, DeprecatedString, CaseInsensitiveStringTraits> const& headers, Optional<u32> status_code)
  78. {
  79. VERIFY(!m_loaded);
  80. // FIXME: Handle OOM failure.
  81. m_encoded_data = ByteBuffer::copy(data).release_value_but_fixme_should_propagate_errors();
  82. m_response_headers = headers;
  83. m_status_code = move(status_code);
  84. m_loaded = true;
  85. auto content_type = headers.get("Content-Type");
  86. if (content_type.has_value()) {
  87. dbgln_if(RESOURCE_DEBUG, "Content-Type header: '{}'", content_type.value());
  88. m_mime_type = mime_type_from_content_type(content_type.value());
  89. // FIXME: "The Quite OK Image Format" doesn't have an official mime type yet,
  90. // and servers like nginx will send a generic octet-stream mime type instead.
  91. // Let's use image/x-qoi for now, which is also what our Core::MimeData uses & would guess.
  92. if (m_mime_type == "application/octet-stream" && url().serialize_path().ends_with(".qoi"sv))
  93. m_mime_type = "image/x-qoi";
  94. } else if (url().scheme() == "data" && !url().data_mime_type().is_empty()) {
  95. dbgln_if(RESOURCE_DEBUG, "This is a data URL with mime-type _{}_", url().data_mime_type());
  96. m_mime_type = url().data_mime_type();
  97. } else {
  98. auto content_type_options = headers.get("X-Content-Type-Options");
  99. if (content_type_options.value_or("").equals_ignoring_ascii_case("nosniff"sv)) {
  100. m_mime_type = "text/plain";
  101. } else {
  102. m_mime_type = Core::guess_mime_type_based_on_filename(url().serialize_path());
  103. }
  104. }
  105. m_encoding = {};
  106. if (content_type.has_value()) {
  107. auto encoding = encoding_from_content_type(content_type.value());
  108. if (encoding.has_value() && is_valid_encoding(encoding.value())) {
  109. dbgln_if(RESOURCE_DEBUG, "Set encoding '{}' from Content-Type", encoding.value());
  110. m_encoding = encoding.value();
  111. }
  112. }
  113. for_each_client([](auto& client) {
  114. client.resource_did_load();
  115. });
  116. }
  117. void Resource::did_fail(Badge<ResourceLoader>, DeprecatedString const& error, Optional<u32> status_code)
  118. {
  119. m_error = error;
  120. m_status_code = move(status_code);
  121. m_failed = true;
  122. for_each_client([](auto& client) {
  123. client.resource_did_fail();
  124. });
  125. }
  126. void Resource::register_client(Badge<ResourceClient>, ResourceClient& client)
  127. {
  128. VERIFY(!m_clients.contains(&client));
  129. m_clients.set(&client);
  130. }
  131. void Resource::unregister_client(Badge<ResourceClient>, ResourceClient& client)
  132. {
  133. VERIFY(m_clients.contains(&client));
  134. m_clients.remove(&client);
  135. }
  136. void ResourceClient::set_resource(Resource* resource)
  137. {
  138. if (m_resource)
  139. m_resource->unregister_client({}, *this);
  140. m_resource = resource;
  141. if (m_resource) {
  142. VERIFY(resource->type() == client_type());
  143. m_resource->register_client({}, *this);
  144. // For resources that are already loaded, we fire their load/fail callbacks via the event loop.
  145. // This ensures that these callbacks always happen in a consistent way, instead of being invoked
  146. // synchronously in some cases, and asynchronously in others.
  147. if (resource->is_loaded() || resource->is_failed()) {
  148. Platform::EventLoopPlugin::the().deferred_invoke([weak_this = make_weak_ptr(), strong_resource = NonnullRefPtr { *m_resource }] {
  149. if (!weak_this)
  150. return;
  151. if (weak_this->m_resource != strong_resource.ptr())
  152. return;
  153. // Make sure that reused resources also have their load callback fired.
  154. if (weak_this->m_resource->is_loaded()) {
  155. weak_this->resource_did_load();
  156. return;
  157. }
  158. // Make sure that reused resources also have their fail callback fired.
  159. if (weak_this->m_resource->is_failed()) {
  160. weak_this->resource_did_fail();
  161. return;
  162. }
  163. });
  164. }
  165. }
  166. }
  167. ResourceClient::~ResourceClient()
  168. {
  169. if (m_resource)
  170. m_resource->unregister_client({}, *this);
  171. }
  172. }