Resource.cpp 6.0 KB

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