Resource.cpp 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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<ByteString> encoding_from_content_type(ByteString 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 ByteString mime_type_from_content_type(ByteString 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<ByteString, ByteString, 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 {
  91. auto content_type_options = headers.get("X-Content-Type-Options");
  92. if (content_type_options.value_or("").equals_ignoring_ascii_case("nosniff"sv)) {
  93. m_mime_type = "text/plain";
  94. } else {
  95. m_mime_type = Core::guess_mime_type_based_on_filename(url().serialize_path());
  96. }
  97. }
  98. m_encoding = {};
  99. if (content_type.has_value()) {
  100. auto encoding = encoding_from_content_type(content_type.value());
  101. if (encoding.has_value() && is_valid_encoding(encoding.value())) {
  102. dbgln_if(RESOURCE_DEBUG, "Set encoding '{}' from Content-Type", encoding.value());
  103. m_encoding = encoding.value();
  104. }
  105. }
  106. for_each_client([](auto& client) {
  107. client.resource_did_load();
  108. });
  109. }
  110. void Resource::did_fail(Badge<ResourceLoader>, ByteString const& error, Optional<u32> status_code)
  111. {
  112. m_error = error;
  113. m_status_code = move(status_code);
  114. m_state = State::Failed;
  115. for_each_client([](auto& client) {
  116. client.resource_did_fail();
  117. });
  118. }
  119. void Resource::register_client(Badge<ResourceClient>, ResourceClient& client)
  120. {
  121. VERIFY(!m_clients.contains(&client));
  122. m_clients.set(&client);
  123. }
  124. void Resource::unregister_client(Badge<ResourceClient>, ResourceClient& client)
  125. {
  126. VERIFY(m_clients.contains(&client));
  127. m_clients.remove(&client);
  128. }
  129. void ResourceClient::set_resource(Resource* resource)
  130. {
  131. if (m_resource)
  132. m_resource->unregister_client({}, *this);
  133. m_resource = resource;
  134. if (m_resource) {
  135. VERIFY(resource->type() == client_type());
  136. m_resource->register_client({}, *this);
  137. // For resources that are already loaded, we fire their load/fail callbacks via the event loop.
  138. // This ensures that these callbacks always happen in a consistent way, instead of being invoked
  139. // synchronously in some cases, and asynchronously in others.
  140. if (resource->is_loaded() || resource->is_failed()) {
  141. Platform::EventLoopPlugin::the().deferred_invoke([weak_this = make_weak_ptr(), strong_resource = NonnullRefPtr { *m_resource }] {
  142. if (!weak_this)
  143. return;
  144. if (weak_this->m_resource != strong_resource.ptr())
  145. return;
  146. // Make sure that reused resources also have their load callback fired.
  147. if (weak_this->m_resource->is_loaded()) {
  148. weak_this->resource_did_load();
  149. return;
  150. }
  151. // Make sure that reused resources also have their fail callback fired.
  152. if (weak_this->m_resource->is_failed()) {
  153. weak_this->resource_did_fail();
  154. return;
  155. }
  156. });
  157. }
  158. }
  159. }
  160. ResourceClient::~ResourceClient()
  161. {
  162. if (m_resource)
  163. m_resource->unregister_client({}, *this);
  164. }
  165. }