Methods.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. * Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
  3. * Copyright (c) 2022, Kenneth Myhra <kennethmyhra@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/ByteBuffer.h>
  8. #include <AK/StringView.h>
  9. #include <LibRegex/Regex.h>
  10. #include <LibWeb/Fetch/Infrastructure/HTTP/Methods.h>
  11. #include <LibWeb/Infra/ByteSequences.h>
  12. namespace Web::Fetch::Infrastructure {
  13. // https://fetch.spec.whatwg.org/#concept-method
  14. bool is_method(ReadonlyBytes method)
  15. {
  16. // A method is a byte sequence that matches the method token production.
  17. Regex<ECMA262Parser> regex { R"~~~(^[A-Za-z0-9!#$%&'*+\-.^_`|~]+$)~~~" };
  18. return regex.has_match(StringView { method });
  19. }
  20. // https://fetch.spec.whatwg.org/#cors-safelisted-method
  21. bool is_cors_safelisted_method(ReadonlyBytes method)
  22. {
  23. // A CORS-safelisted method is a method that is `GET`, `HEAD`, or `POST`.
  24. return StringView { method }.is_one_of("GET"sv, "HEAD"sv, "POST"sv);
  25. }
  26. // https://fetch.spec.whatwg.org/#forbidden-method
  27. bool is_forbidden_method(ReadonlyBytes method)
  28. {
  29. // A forbidden method is a method that is a byte-case-insensitive match for `CONNECT`, `TRACE`, or `TRACK`.
  30. return StringView { method }.is_one_of_ignoring_ascii_case("CONNECT"sv, "TRACE"sv, "TRACK"sv);
  31. }
  32. // https://fetch.spec.whatwg.org/#concept-method-normalize
  33. ErrorOr<ByteBuffer> normalize_method(ReadonlyBytes method)
  34. {
  35. // To normalize a method, if it is a byte-case-insensitive match for `DELETE`, `GET`, `HEAD`, `OPTIONS`, `POST`, or `PUT`, byte-uppercase it.
  36. auto bytes = TRY(ByteBuffer::copy(method));
  37. if (StringView { method }.is_one_of_ignoring_ascii_case("DELETE"sv, "GET"sv, "HEAD"sv, "OPTIONS"sv, "POST"sv, "PUT"sv))
  38. Infra::byte_uppercase(bytes);
  39. return bytes;
  40. }
  41. }