Resource.cpp 6.8 KB

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