Resource.cpp 5.9 KB

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