Response.cpp 13 KB

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