Body.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. /*
  2. * Copyright (c) 2022-2023, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/TypeCasts.h>
  7. #include <LibJS/Runtime/ArrayBuffer.h>
  8. #include <LibJS/Runtime/Completion.h>
  9. #include <LibJS/Runtime/Error.h>
  10. #include <LibJS/Runtime/PromiseCapability.h>
  11. #include <LibTextCodec/Decoder.h>
  12. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  13. #include <LibWeb/Bindings/HostDefined.h>
  14. #include <LibWeb/Bindings/MainThreadVM.h>
  15. #include <LibWeb/Fetch/Body.h>
  16. #include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>
  17. #include <LibWeb/FileAPI/Blob.h>
  18. #include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
  19. #include <LibWeb/Infra/JSON.h>
  20. #include <LibWeb/MimeSniff/MimeType.h>
  21. #include <LibWeb/Streams/ReadableStream.h>
  22. #include <LibWeb/WebIDL/Promise.h>
  23. namespace Web::Fetch {
  24. BodyMixin::~BodyMixin() = default;
  25. // https://fetch.spec.whatwg.org/#body-unusable
  26. bool BodyMixin::is_unusable() const
  27. {
  28. // An object including the Body interface mixin is said to be unusable if its body is non-null and its body’s stream is disturbed or locked.
  29. auto const& body = body_impl();
  30. return body && (body->stream()->is_disturbed() || body->stream()->is_locked());
  31. }
  32. // https://fetch.spec.whatwg.org/#dom-body-body
  33. JS::GCPtr<Streams::ReadableStream> BodyMixin::body() const
  34. {
  35. // The body getter steps are to return null if this’s body is null; otherwise this’s body’s stream.
  36. auto const& body = body_impl();
  37. return body ? body->stream().ptr() : nullptr;
  38. }
  39. // https://fetch.spec.whatwg.org/#dom-body-bodyused
  40. bool BodyMixin::body_used() const
  41. {
  42. // The bodyUsed getter steps are to return true if this’s body is non-null and this’s body’s stream is disturbed; otherwise false.
  43. auto const& body = body_impl();
  44. return body && body->stream()->is_disturbed();
  45. }
  46. // https://fetch.spec.whatwg.org/#dom-body-arraybuffer
  47. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::Promise>> BodyMixin::array_buffer() const
  48. {
  49. auto& vm = Bindings::main_thread_vm();
  50. auto& realm = *vm.current_realm();
  51. // The arrayBuffer() method steps are to return the result of running consume body with this and ArrayBuffer.
  52. return consume_body(realm, *this, PackageDataType::ArrayBuffer);
  53. }
  54. // https://fetch.spec.whatwg.org/#dom-body-blob
  55. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::Promise>> BodyMixin::blob() const
  56. {
  57. auto& vm = Bindings::main_thread_vm();
  58. auto& realm = *vm.current_realm();
  59. // The blob() method steps are to return the result of running consume body with this and Blob.
  60. return consume_body(realm, *this, PackageDataType::Blob);
  61. }
  62. // https://fetch.spec.whatwg.org/#dom-body-formdata
  63. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::Promise>> BodyMixin::form_data() const
  64. {
  65. auto& vm = Bindings::main_thread_vm();
  66. auto& realm = *vm.current_realm();
  67. // The formData() method steps are to return the result of running consume body with this and FormData.
  68. return consume_body(realm, *this, PackageDataType::FormData);
  69. }
  70. // https://fetch.spec.whatwg.org/#dom-body-json
  71. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::Promise>> BodyMixin::json() const
  72. {
  73. auto& vm = Bindings::main_thread_vm();
  74. auto& realm = *vm.current_realm();
  75. // The json() method steps are to return the result of running consume body with this and JSON.
  76. return consume_body(realm, *this, PackageDataType::JSON);
  77. }
  78. // https://fetch.spec.whatwg.org/#dom-body-text
  79. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::Promise>> BodyMixin::text() const
  80. {
  81. auto& vm = Bindings::main_thread_vm();
  82. auto& realm = *vm.current_realm();
  83. // The text() method steps are to return the result of running consume body with this and text.
  84. return consume_body(realm, *this, PackageDataType::Text);
  85. }
  86. // https://fetch.spec.whatwg.org/#concept-body-package-data
  87. WebIDL::ExceptionOr<JS::Value> package_data(JS::Realm& realm, ByteBuffer bytes, PackageDataType type, Optional<MimeSniff::MimeType> const& mime_type)
  88. {
  89. auto& vm = realm.vm();
  90. switch (type) {
  91. case PackageDataType::ArrayBuffer:
  92. // Return a new ArrayBuffer whose contents are bytes.
  93. return JS::ArrayBuffer::create(realm, move(bytes));
  94. case PackageDataType::Blob: {
  95. // Return a Blob whose contents are bytes and type attribute is mimeType.
  96. // NOTE: If extracting the mime type returns failure, other browsers set it to an empty string - not sure if that's spec'd.
  97. auto mime_type_string = mime_type.has_value() ? TRY_OR_THROW_OOM(vm, mime_type->serialized()) : String {};
  98. return FileAPI::Blob::create(realm, move(bytes), move(mime_type_string));
  99. }
  100. case PackageDataType::FormData:
  101. // If mimeType’s essence is "multipart/form-data", then:
  102. if (mime_type.has_value() && mime_type->essence() == "multipart/form-data"sv) {
  103. // FIXME: 1. Parse bytes, using the value of the `boundary` parameter from mimeType, per the rules set forth in Returning Values from Forms: multipart/form-data. [RFC7578]
  104. // FIXME: 2. If that fails for some reason, then throw a TypeError.
  105. // FIXME: 3. Return a new FormData object, appending each entry, resulting from the parsing operation, to its entry list.
  106. return JS::js_null();
  107. }
  108. // Otherwise, if mimeType’s essence is "application/x-www-form-urlencoded", then:
  109. else if (mime_type.has_value() && mime_type->essence() == "application/x-www-form-urlencoded"sv) {
  110. // FIXME: 1. Let entries be the result of parsing bytes.
  111. // FIXME: 2. If entries is failure, then throw a TypeError.
  112. // FIXME: 3. Return a new FormData object whose entry list is entries.
  113. return JS::js_null();
  114. }
  115. // Otherwise, throw a TypeError.
  116. else {
  117. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Mime type must be 'multipart/form-data' or 'application/x-www-form-urlencoded'"sv };
  118. }
  119. case PackageDataType::JSON:
  120. // Return the result of running parse JSON from bytes on bytes.
  121. return Infra::parse_json_bytes_to_javascript_value(realm, bytes);
  122. case PackageDataType::Text: {
  123. // Return the result of running UTF-8 decode on bytes.
  124. auto decoder = TextCodec::decoder_for("UTF-8"sv);
  125. VERIFY(decoder.has_value());
  126. auto utf8_text = TRY_OR_THROW_OOM(vm, TextCodec::convert_input_to_utf8_using_given_decoder_unless_there_is_a_byte_order_mark(*decoder, bytes));
  127. return JS::PrimitiveString::create(vm, move(utf8_text));
  128. }
  129. default:
  130. VERIFY_NOT_REACHED();
  131. }
  132. }
  133. // https://fetch.spec.whatwg.org/#concept-body-consume-body
  134. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::Promise>> consume_body(JS::Realm& realm, BodyMixin const& object, PackageDataType type)
  135. {
  136. // 1. If object is unusable, then return a promise rejected with a TypeError.
  137. if (object.is_unusable()) {
  138. WebIDL::SimpleException exception { WebIDL::SimpleExceptionType::TypeError, "Body is unusable"sv };
  139. return WebIDL::create_rejected_promise_from_exception(realm, move(exception));
  140. }
  141. // 2. Let promise be a new promise.
  142. auto promise = WebIDL::create_promise(realm);
  143. // 3. Let errorSteps given error be to reject promise with error.
  144. // NOTE: `promise` and `realm` is protected by JS::SafeFunction.
  145. auto error_steps = [promise, &realm](JS::GCPtr<WebIDL::DOMException> error) {
  146. // AD-HOC: An execution context is required for Promise's reject function.
  147. HTML::TemporaryExecutionContext execution_context { Bindings::host_defined_environment_settings_object(realm) };
  148. WebIDL::reject_promise(realm, promise, error);
  149. };
  150. // 4. Let successSteps given a byte sequence data be to resolve promise with the result of running convertBytesToJSValue
  151. // with data. If that threw an exception, then run errorSteps with that exception.
  152. // NOTE: `promise`, `realm` and `object` is protected by JS::SafeFunction.
  153. // FIXME: Refactor this to the new version of the spec introduced with https://github.com/whatwg/fetch/commit/464326e8eb6a602122c030cd40042480a3c0e265
  154. auto success_steps = [promise, &realm, &object, type](ByteBuffer const& data) {
  155. auto& vm = realm.vm();
  156. // AD-HOC: An execution context is required for Promise's reject function and JSON.parse.
  157. HTML::TemporaryExecutionContext execution_context { Bindings::host_defined_environment_settings_object(realm) };
  158. auto value_or_error = Bindings::throw_dom_exception_if_needed(vm, [&]() -> WebIDL::ExceptionOr<JS::Value> {
  159. return package_data(realm, data, type, TRY_OR_THROW_OOM(vm, object.mime_type_impl()));
  160. });
  161. if (value_or_error.is_error()) {
  162. // We can't call error_steps here without moving it into success_steps, causing a double move when we pause error_steps
  163. // to fully_read, so just reject the promise like error_steps does.
  164. WebIDL::reject_promise(realm, promise, value_or_error.release_error().value().value());
  165. return;
  166. }
  167. WebIDL::resolve_promise(realm, promise, value_or_error.release_value());
  168. };
  169. // 5. If object’s body is null, then run successSteps with an empty byte sequence.
  170. auto const& body = object.body_impl();
  171. if (!body) {
  172. success_steps(ByteBuffer {});
  173. }
  174. // 6. Otherwise, fully read object’s body given successSteps, errorSteps, and object’s relevant global object.
  175. else {
  176. TRY(body->fully_read(realm, move(success_steps), move(error_steps), JS::NonnullGCPtr { HTML::relevant_global_object(object.as_platform_object()) }));
  177. }
  178. // 7. Return promise.
  179. return JS::NonnullGCPtr { verify_cast<JS::Promise>(*promise->promise().ptr()) };
  180. }
  181. }