BodyInit.cpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. /*
  2. * Copyright (c) 2022-2023, Linus Groh <linusg@serenityos.org>
  3. * Copyright (c) 2022-2024, Kenneth Myhra <kennethmyhra@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibJS/Runtime/Completion.h>
  8. #include <LibJS/Runtime/TypedArray.h>
  9. #include <LibWeb/DOMURL/URLSearchParams.h>
  10. #include <LibWeb/Fetch/BodyInit.h>
  11. #include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>
  12. #include <LibWeb/FileAPI/Blob.h>
  13. #include <LibWeb/HTML/FormControlInfrastructure.h>
  14. #include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
  15. #include <LibWeb/Platform/EventLoopPlugin.h>
  16. #include <LibWeb/Streams/AbstractOperations.h>
  17. #include <LibWeb/WebIDL/AbstractOperations.h>
  18. #include <LibWeb/WebIDL/Buffers.h>
  19. #include <LibWeb/WebIDL/ExceptionOr.h>
  20. #include <LibWeb/XHR/FormData.h>
  21. namespace Web::Fetch {
  22. // https://fetch.spec.whatwg.org/#bodyinit-safely-extract
  23. WebIDL::ExceptionOr<Infrastructure::BodyWithType> safely_extract_body(JS::Realm& realm, BodyInitOrReadableBytes const& object)
  24. {
  25. // 1. If object is a ReadableStream object, then:
  26. if (auto const* stream = object.get_pointer<JS::Handle<Streams::ReadableStream>>()) {
  27. // 1. Assert: object is neither disturbed nor locked.
  28. VERIFY(!((*stream)->is_disturbed() || (*stream)->is_locked()));
  29. }
  30. // 2. Return the result of extracting object.
  31. return extract_body(realm, object);
  32. }
  33. // https://fetch.spec.whatwg.org/#concept-bodyinit-extract
  34. WebIDL::ExceptionOr<Infrastructure::BodyWithType> extract_body(JS::Realm& realm, BodyInitOrReadableBytes const& object, bool keepalive)
  35. {
  36. HTML::TemporaryExecutionContext execution_context { Bindings::host_defined_environment_settings_object(realm), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
  37. auto& vm = realm.vm();
  38. // 1. Let stream be null.
  39. JS::GCPtr<Streams::ReadableStream> stream;
  40. // 2. If object is a ReadableStream object, then set stream to object.
  41. if (auto const* stream_handle = object.get_pointer<JS::Handle<Streams::ReadableStream>>()) {
  42. stream = const_cast<Streams::ReadableStream*>(stream_handle->cell());
  43. }
  44. // 3. Otherwise, if object is a Blob object, set stream to the result of running object’s get stream.
  45. else if (auto const* blob_handle = object.get_pointer<JS::Handle<FileAPI::Blob>>()) {
  46. stream = blob_handle->cell()->get_stream();
  47. }
  48. // 4. Otherwise, set stream to a new ReadableStream object, and set up stream with byte reading support.
  49. else {
  50. stream = realm.heap().allocate<Streams::ReadableStream>(realm, realm);
  51. Streams::set_up_readable_stream_controller_with_byte_reading_support(*stream);
  52. }
  53. // 5. Assert: stream is a ReadableStream object.
  54. VERIFY(stream);
  55. // 6. Let action be null.
  56. Function<ByteBuffer()> action;
  57. // 7. Let source be null.
  58. Infrastructure::Body::SourceType source {};
  59. // 8. Let length be null.
  60. Optional<u64> length {};
  61. // 9. Let type be null.
  62. Optional<ByteBuffer> type {};
  63. // 10. Switch on object.
  64. TRY(object.visit(
  65. [&](JS::Handle<FileAPI::Blob> const& blob) -> WebIDL::ExceptionOr<void> {
  66. // Set source to object.
  67. source = blob;
  68. // Set length to object’s size.
  69. length = blob->size();
  70. // If object’s type attribute is not the empty byte sequence, set type to its value.
  71. if (!blob->type().is_empty())
  72. type = MUST(ByteBuffer::copy(blob->type().bytes()));
  73. return {};
  74. },
  75. [&](ReadonlyBytes bytes) -> WebIDL::ExceptionOr<void> {
  76. // Set source to object.
  77. source = MUST(ByteBuffer::copy(bytes));
  78. return {};
  79. },
  80. [&](JS::Handle<WebIDL::BufferSource> const& buffer_source) -> WebIDL::ExceptionOr<void> {
  81. // Set source to a copy of the bytes held by object.
  82. source = MUST(WebIDL::get_buffer_source_copy(*buffer_source->raw_object()));
  83. return {};
  84. },
  85. [&](JS::Handle<XHR::FormData> const& form_data) -> WebIDL::ExceptionOr<void> {
  86. // Set action to this step: run the multipart/form-data encoding algorithm, with object’s entry list and UTF-8.
  87. auto serialized_form_data = MUST(HTML::serialize_to_multipart_form_data(form_data->entry_list()));
  88. // Set source to object.
  89. source = serialized_form_data.serialized_data;
  90. // FIXME: Set length to unclear, see html/6424 for improving this.
  91. // Set type to `multipart/form-data; boundary=`, followed by the multipart/form-data boundary string generated by the multipart/form-data encoding algorithm.
  92. type = MUST(ByteBuffer::copy(MUST(String::formatted("multipart/form-data; boundary={}"sv, serialized_form_data.boundary)).bytes()));
  93. return {};
  94. },
  95. [&](JS::Handle<DOMURL::URLSearchParams> const& url_search_params) -> WebIDL::ExceptionOr<void> {
  96. // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list.
  97. auto search_params_string = url_search_params->to_string();
  98. source = MUST(ByteBuffer::copy(search_params_string.bytes()));
  99. // Set type to `application/x-www-form-urlencoded;charset=UTF-8`.
  100. type = MUST(ByteBuffer::copy("application/x-www-form-urlencoded;charset=UTF-8"sv.bytes()));
  101. return {};
  102. },
  103. [&](String const& scalar_value_string) -> WebIDL::ExceptionOr<void> {
  104. // NOTE: AK::String is always UTF-8.
  105. // Set source to the UTF-8 encoding of object.
  106. source = MUST(ByteBuffer::copy(scalar_value_string.bytes()));
  107. // Set type to `text/plain;charset=UTF-8`.
  108. type = MUST(ByteBuffer::copy("text/plain;charset=UTF-8"sv.bytes()));
  109. return {};
  110. },
  111. [&](JS::Handle<Streams::ReadableStream> const& stream) -> WebIDL::ExceptionOr<void> {
  112. // If keepalive is true, then throw a TypeError.
  113. if (keepalive)
  114. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot extract body from stream when keepalive is set"sv };
  115. // If object is disturbed or locked, then throw a TypeError.
  116. if (stream->is_disturbed() || stream->is_locked())
  117. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot extract body from disturbed or locked stream"sv };
  118. return {};
  119. }));
  120. // 11. If source is a byte sequence, then set action to a step that returns source and length to source’s length.
  121. // For now, do it synchronously.
  122. if (source.has<ByteBuffer>()) {
  123. action = [source = MUST(ByteBuffer::copy(source.get<ByteBuffer>()))]() mutable {
  124. return move(source);
  125. };
  126. length = source.get<ByteBuffer>().size();
  127. }
  128. // 12. If action is non-null, then run these steps in parallel:
  129. if (action) {
  130. Platform::EventLoopPlugin::the().deferred_invoke([&realm, stream, action = move(action)] {
  131. HTML::TemporaryExecutionContext execution_context { Bindings::host_defined_environment_settings_object(realm), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
  132. // 1. Run action.
  133. auto bytes = action();
  134. // Whenever one or more bytes are available and stream is not errored, enqueue the result of creating a
  135. // Uint8Array from the available bytes into stream.
  136. if (!bytes.is_empty() && !stream->is_errored()) {
  137. auto array_buffer = JS::ArrayBuffer::create(stream->realm(), move(bytes));
  138. auto chunk = JS::Uint8Array::create(stream->realm(), array_buffer->byte_length(), *array_buffer);
  139. Streams::readable_stream_enqueue(*stream->controller(), chunk).release_value_but_fixme_should_propagate_errors();
  140. }
  141. // When running action is done, close stream.
  142. stream->close();
  143. });
  144. }
  145. // 13. Let body be a body whose stream is stream, source is source, and length is length.
  146. auto body = Infrastructure::Body::create(vm, *stream, move(source), move(length));
  147. // 14. Return (body, type).
  148. return Infrastructure::BodyWithType { .body = move(body), .type = move(type) };
  149. }
  150. }