Resource.cpp 6.4 KB

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