Response.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. /*
  2. * Copyright (c) 2022-2023, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/URLParser.h>
  7. #include <LibJS/Runtime/Completion.h>
  8. #include <LibWeb/Bindings/Intrinsics.h>
  9. #include <LibWeb/Bindings/MainThreadVM.h>
  10. #include <LibWeb/Fetch/Enums.h>
  11. #include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>
  12. #include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>
  13. #include <LibWeb/Fetch/Infrastructure/HTTP/Statuses.h>
  14. #include <LibWeb/Fetch/Response.h>
  15. #include <LibWeb/HTML/Scripting/Environments.h>
  16. #include <LibWeb/Infra/JSON.h>
  17. namespace Web::Fetch {
  18. Response::Response(JS::Realm& realm, JS::NonnullGCPtr<Infrastructure::Response> response)
  19. : PlatformObject(realm)
  20. , m_response(response)
  21. {
  22. }
  23. Response::~Response() = default;
  24. JS::ThrowCompletionOr<void> Response::initialize(JS::Realm& realm)
  25. {
  26. MUST_OR_THROW_OOM(Base::initialize(realm));
  27. set_prototype(&Bindings::ensure_web_prototype<Bindings::ResponsePrototype>(realm, "Response"));
  28. return {};
  29. }
  30. void Response::visit_edges(Cell::Visitor& visitor)
  31. {
  32. Base::visit_edges(visitor);
  33. visitor.visit(m_response);
  34. visitor.visit(m_headers);
  35. }
  36. // https://fetch.spec.whatwg.org/#concept-body-mime-type
  37. // https://fetch.spec.whatwg.org/#ref-for-concept-header-extract-mime-type%E2%91%A7
  38. ErrorOr<Optional<MimeSniff::MimeType>> Response::mime_type_impl() const
  39. {
  40. // Objects including the Body interface mixin need to define an associated MIME type algorithm which takes no arguments and returns failure or a MIME type.
  41. // A Response object’s MIME type is to return the result of extracting a MIME type from its response’s header list.
  42. return m_response->header_list()->extract_mime_type();
  43. }
  44. // https://fetch.spec.whatwg.org/#concept-body-body
  45. // https://fetch.spec.whatwg.org/#ref-for-concept-body-body%E2%91%A8
  46. Optional<Infrastructure::Body const&> Response::body_impl() const
  47. {
  48. // Objects including the Body interface mixin have an associated body (null or a body).
  49. // A Response object’s body is its response’s body.
  50. return m_response->body().has_value()
  51. ? m_response->body().value()
  52. : Optional<Infrastructure::Body const&> {};
  53. }
  54. // https://fetch.spec.whatwg.org/#concept-body-body
  55. // https://fetch.spec.whatwg.org/#ref-for-concept-body-body%E2%91%A8
  56. Optional<Infrastructure::Body&> Response::body_impl()
  57. {
  58. // Objects including the Body interface mixin have an associated body (null or a body).
  59. // A Response object’s body is its response’s body.
  60. return m_response->body().has_value()
  61. ? m_response->body().value()
  62. : Optional<Infrastructure::Body&> {};
  63. }
  64. // https://fetch.spec.whatwg.org/#response-create
  65. WebIDL::ExceptionOr<JS::NonnullGCPtr<Response>> Response::create(JS::Realm& realm, JS::NonnullGCPtr<Infrastructure::Response> response, Headers::Guard guard)
  66. {
  67. // 1. Let responseObject be a new Response object with realm.
  68. // 2. Set responseObject’s response to response.
  69. auto response_object = MUST_OR_THROW_OOM(realm.heap().allocate<Response>(realm, realm, response));
  70. // 3. Set responseObject’s headers to a new Headers object with realm, whose headers list is response’s headers list and guard is guard.
  71. response_object->m_headers = MUST_OR_THROW_OOM(realm.heap().allocate<Headers>(realm, realm, response->header_list()));
  72. response_object->m_headers->set_guard(guard);
  73. // 4. Return responseObject.
  74. return response_object;
  75. }
  76. // https://fetch.spec.whatwg.org/#initialize-a-response
  77. WebIDL::ExceptionOr<void> Response::initialize_response(ResponseInit const& init, Optional<Infrastructure::BodyWithType> const& body)
  78. {
  79. auto& vm = this->vm();
  80. // 1. If init["status"] is not in the range 200 to 599, inclusive, then throw a RangeError.
  81. if (init.status < 200 || init.status > 599)
  82. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Status must be in range 200-599"sv };
  83. // FIXME: 2. If init["statusText"] does not match the reason-phrase token production, then throw a TypeError.
  84. // 3. Set response’s response’s status to init["status"].
  85. m_response->set_status(init.status);
  86. // 4. Set response’s response’s status message to init["statusText"].
  87. m_response->set_status_message(TRY_OR_THROW_OOM(vm, ByteBuffer::copy(init.status_text.bytes())));
  88. // 5. If init["headers"] exists, then fill response’s headers with init["headers"].
  89. if (init.headers.has_value())
  90. TRY(m_headers->fill(*init.headers));
  91. // 6. If body was given, then:
  92. if (body.has_value()) {
  93. // 1. If response’s status is a null body status, then throw a TypeError.
  94. if (Infrastructure::is_null_body_status(m_response->status()))
  95. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Response with null body status cannot have a body"sv };
  96. // 2. Set response’s body to body’s body.
  97. m_response->set_body(body->body);
  98. // 3. If body’s type is non-null and response’s header list does not contain `Content-Type`, then append (`Content-Type`, body’s type) to response’s header list.
  99. if (body->type.has_value() && m_response->header_list()->contains("Content-Type"sv.bytes())) {
  100. auto header = Infrastructure::Header {
  101. .name = MUST(ByteBuffer::copy("Content-Type"sv.bytes())),
  102. .value = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(body->type->span())),
  103. };
  104. TRY_OR_THROW_OOM(vm, m_response->header_list()->append(move(header)));
  105. }
  106. }
  107. return {};
  108. }
  109. // https://fetch.spec.whatwg.org/#dom-response
  110. WebIDL::ExceptionOr<JS::NonnullGCPtr<Response>> Response::construct_impl(JS::Realm& realm, Optional<BodyInit> const& body, ResponseInit const& init)
  111. {
  112. auto& vm = realm.vm();
  113. // Referred to as 'this' in the spec.
  114. auto response_object = MUST_OR_THROW_OOM(realm.heap().allocate<Response>(realm, realm, Infrastructure::Response::create(vm)));
  115. // 1. Set this’s response to a new response.
  116. // NOTE: This is done at the beginning as the 'this' value Response object
  117. // cannot exist with a null Infrastructure::Response.
  118. // 2. Set this’s headers to a new Headers object with this’s relevant Realm, whose header list is this’s response’s header list and guard is "response".
  119. response_object->m_headers = MUST_OR_THROW_OOM(realm.heap().allocate<Headers>(realm, realm, response_object->response()->header_list()));
  120. response_object->m_headers->set_guard(Headers::Guard::Response);
  121. // 3. Let bodyWithType be null.
  122. Optional<Infrastructure::BodyWithType> body_with_type;
  123. // 4. If body is non-null, then set bodyWithType to the result of extracting body.
  124. if (body.has_value())
  125. body_with_type = TRY(extract_body(realm, *body));
  126. // 5. Perform initialize a response given this, init, and bodyWithType.
  127. TRY(response_object->initialize_response(init, body_with_type));
  128. return response_object;
  129. }
  130. // https://fetch.spec.whatwg.org/#dom-response-error
  131. WebIDL::ExceptionOr<JS::NonnullGCPtr<Response>> Response::error(JS::VM& vm)
  132. {
  133. // The static error() method steps are to return the result of creating a Response object, given a new network error, "immutable", and this’s relevant Realm.
  134. // FIXME: How can we reliably get 'this', i.e. the object the function was called on, in IDL-defined functions?
  135. return Response::create(*vm.current_realm(), Infrastructure::Response::network_error(vm, "Response created via `Response.error()`"sv), Headers::Guard::Immutable);
  136. }
  137. // https://fetch.spec.whatwg.org/#dom-response-redirect
  138. WebIDL::ExceptionOr<JS::NonnullGCPtr<Response>> Response::redirect(JS::VM& vm, String const& url, u16 status)
  139. {
  140. auto& realm = *vm.current_realm();
  141. // 1. Let parsedURL be the result of parsing url with current settings object’s API base URL.
  142. auto api_base_url = HTML::current_settings_object().api_base_url();
  143. auto parsed_url = URLParser::parse(url, api_base_url);
  144. // 2. If parsedURL is failure, then throw a TypeError.
  145. if (!parsed_url.is_valid())
  146. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Redirect URL is not valid"sv };
  147. // 3. If status is not a redirect status, then throw a RangeError.
  148. if (!Infrastructure::is_redirect_status(status))
  149. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Status must be one of 301, 302, 303, 307, or 308"sv };
  150. // 4. Let responseObject be the result of creating a Response object, given a new response, "immutable", and this’s relevant Realm.
  151. // FIXME: How can we reliably get 'this', i.e. the object the function was called on, in IDL-defined functions?
  152. auto response_object = TRY(Response::create(realm, Infrastructure::Response::create(vm), Headers::Guard::Immutable));
  153. // 5. Set responseObject’s response’s status to status.
  154. response_object->response()->set_status(status);
  155. // 6. Let value be parsedURL, serialized and isomorphic encoded.
  156. auto value = parsed_url.serialize();
  157. // 7. Append (`Location`, value) to responseObject’s response’s header list.
  158. auto header = TRY_OR_THROW_OOM(vm, Infrastructure::Header::from_string_pair("Location"sv, value));
  159. TRY_OR_THROW_OOM(vm, response_object->response()->header_list()->append(move(header)));
  160. // 8. Return responseObject.
  161. return response_object;
  162. }
  163. // https://fetch.spec.whatwg.org/#dom-response-json
  164. WebIDL::ExceptionOr<JS::NonnullGCPtr<Response>> Response::json(JS::VM& vm, JS::Value data, ResponseInit const& init)
  165. {
  166. auto& realm = *vm.current_realm();
  167. // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data.
  168. auto bytes = TRY(Infra::serialize_javascript_value_to_json_bytes(vm, data));
  169. // 2. Let body be the result of extracting bytes.
  170. auto [body, _] = TRY(extract_body(realm, { bytes.bytes() }));
  171. // 3. Let responseObject be the result of creating a Response object, given a new response, "response", and this’s relevant Realm.
  172. // FIXME: How can we reliably get 'this', i.e. the object the function was called on, in IDL-defined functions?
  173. auto response_object = TRY(Response::create(realm, Infrastructure::Response::create(vm), Headers::Guard::Response));
  174. // 4. Perform initialize a response given responseObject, init, and (body, "application/json").
  175. auto body_with_type = Infrastructure::BodyWithType {
  176. .body = move(body),
  177. .type = TRY_OR_THROW_OOM(vm, ByteBuffer::copy("application/json"sv.bytes()))
  178. };
  179. TRY(response_object->initialize_response(init, move(body_with_type)));
  180. // 5. Return responseObject.
  181. return response_object;
  182. }
  183. // https://fetch.spec.whatwg.org/#dom-response-type
  184. Bindings::ResponseType Response::type() const
  185. {
  186. // The type getter steps are to return this’s response’s type.
  187. return to_bindings_enum(m_response->type());
  188. }
  189. // https://fetch.spec.whatwg.org/#dom-response-url
  190. WebIDL::ExceptionOr<String> Response::url() const
  191. {
  192. auto& vm = this->vm();
  193. // The url getter steps are to return the empty string if this’s response’s URL is null; otherwise this’s response’s URL, serialized with exclude fragment set to true.
  194. return !m_response->url().has_value()
  195. ? String {}
  196. : TRY_OR_THROW_OOM(vm, String::from_deprecated_string(m_response->url()->serialize(AK::URL::ExcludeFragment::Yes)));
  197. }
  198. // https://fetch.spec.whatwg.org/#dom-response-redirected
  199. bool Response::redirected() const
  200. {
  201. // The redirected getter steps are to return true if this’s response’s URL list has more than one item; otherwise false.
  202. return m_response->url_list().size() > 1;
  203. }
  204. // https://fetch.spec.whatwg.org/#dom-response-status
  205. u16 Response::status() const
  206. {
  207. // The status getter steps are to return this’s response’s status.
  208. return m_response->status();
  209. }
  210. // https://fetch.spec.whatwg.org/#dom-response-ok
  211. bool Response::ok() const
  212. {
  213. // The ok getter steps are to return true if this’s response’s status is an ok status; otherwise false.
  214. return Infrastructure::is_ok_status(m_response->status());
  215. }
  216. // https://fetch.spec.whatwg.org/#dom-response-statustext
  217. WebIDL::ExceptionOr<String> Response::status_text() const
  218. {
  219. auto& vm = this->vm();
  220. // The statusText getter steps are to return this’s response’s status message.
  221. return TRY_OR_THROW_OOM(vm, String::from_utf8(m_response->status_message()));
  222. }
  223. // https://fetch.spec.whatwg.org/#dom-response-headers
  224. JS::NonnullGCPtr<Headers> Response::headers() const
  225. {
  226. // The headers getter steps are to return this’s headers.
  227. return *m_headers;
  228. }
  229. // https://fetch.spec.whatwg.org/#dom-response-clone
  230. WebIDL::ExceptionOr<JS::NonnullGCPtr<Response>> Response::clone() const
  231. {
  232. auto& realm = this->realm();
  233. // 1. If this is unusable, then throw a TypeError.
  234. if (is_unusable())
  235. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Response is unusable"sv };
  236. // 2. Let clonedResponse be the result of cloning this’s response.
  237. auto cloned_response = TRY(m_response->clone(realm));
  238. // 3. Return the result of creating a Response object, given clonedResponse, this’s headers’s guard, and this’s relevant Realm.
  239. return TRY(Response::create(HTML::relevant_realm(*this), cloned_response, m_headers->guard()));
  240. }
  241. }