Resource.cpp 6.8 KB

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