CVE-2024-21631: Integer Overflow or Wraparound (CWE-190)
value: Vapor is an HTTP web framework for Swift. Prior to version 4.90.0, Vapor's `vapor_urlparser_parse` function uses `uint16_t` indexes when parsing a URI's components, which may cause integer overflows when parsing untrusted inputs. This vulnerability does not affect Vapor directly but could impact applications relying on the URI type for validating user input. The URI type is used in several places in Vapor. A developer may decide to use URI to represent a URL in their application (especially if that URL is then passed to the HTTP Client) and rely on its public properties and methods. However, URI may fail to properly parse a valid (albeit abnormally long) URL, due to string ranges being converted to 16-bit integers. An attacker may use this behavior to trick the application into accepting a URL to an untrusted destination. By padding the port number with zeros, an attacker can cause an integer overflow to occur when the URL authority is parsed and, as a result, spoof the host. Version 4.90.0 contains a patch for this issue. As a workaround, validate user input before parsing as a URI or, if possible, use Foundation's `URL` and `URLComponents` utilities.

CWE description: The product performs a calculation that can
         produce an integer overflow or wraparound when the logic
         assumes that the resulting value will always be larger than
         the original value. This occurs when an integer value is
         incremented to a value that is too large to store in the
         associated representation. When this occurs, the value may
         become a very small or negative number.
CVSS v3 base score: 6.5
Published: 2024-01-03T17:15Z
Repository: https://github.com/vapor/vapor
Language: Swift
Files changed: Package.swift, Package@swift-5.9.swift, Sources/Vapor/HTTP/EndpointCache.swift, Sources/Vapor/HTTP/Headers/HTTPCookies.swift, Sources/Vapor/Response/Response+Body.swift, Sources/Vapor/Utilities/URI.swift, Tests/VaporTests/ClientTests.swift, Tests/VaporTests/RequestTests.swift, Tests/VaporTests/ServerTests.swift, Tests/VaporTests/URITests.swift, Tests/VaporTests/ValidationTests.swift
Commit date: 2024-01-03 16:28:27 +0000
Commit message: Merge pull request from GHSA-r6r4-5pr8-gjcp

* Replace the ancient CVaporURLParser code with use of Foundation's URLComponents

* Fixes for weird macOS behaviors

* Tests fixup

* Add test for extreme-length untrusted input which triggered failures in the old implementation.

* Fix Sendable warnings across multiple Swift versions

* Indirect through URL to get to URLComponents so parsing is consistent on Linux.

* A couple more test fixes.
Diff: diff --git a/Package.swift b/Package.swift
index a40b5832a3..e37f839ca2 100644
--- a/Package.swift
+++ b/Package.swift
@@ -64,19 +64,17 @@ let package = Package(
         .package(url: "https://github.com/apple/swift-atomics.git", from: "1.1.0"),
     ],
     targets: [
         // C helpers
         .target(name: "CVaporBcrypt"),
-        .target(name: "CVaporURLParser"),
 
         // Vapor
         .target(name: "Vapor", dependencies: [
             .product(name: "AsyncHTTPClient", package: "async-http-client"),
             .product(name: "AsyncKit", package: "async-kit"),
             .product(name: "Backtrace", package: "swift-backtrace"),
             .target(name: "CVaporBcrypt"),
-            .target(name: "CVaporURLParser"),
             .product(name: "ConsoleKit", package: "console-kit"),
             .product(name: "Logging", package: "swift-log"),
             .product(name: "Metrics", package: "swift-metrics"),
             .product(name: "NIO", package: "swift-nio"),
             .product(name: "NIOConcurrencyHelpers", package: "swift-nio"),
diff --git a/Package@swift-5.9.swift b/Package@swift-5.9.swift
index 4c1016c60f..f8a24e36fb 100644
--- a/Package@swift-5.9.swift
+++ b/Package@swift-5.9.swift
@@ -61,20 +61,18 @@ let package = Package(
         .package(url: "https://github.com/apple/swift-atomics.git", from: "1.1.0"),
     ],
     targets: [
         // C helpers
         .target(name: "CVaporBcrypt"),
-        .target(name: "CVaporURLParser"),
-
+        
         // Vapor
         .target(
             name: "Vapor",
             dependencies: [
                 .product(name: "AsyncHTTPClient", package: "async-http-client"),
                 .product(name: "AsyncKit", package: "async-kit"),
                 .target(name: "CVaporBcrypt"),
-                .target(name: "CVaporURLParser"),
                 .product(name: "ConsoleKit", package: "console-kit"),
                 .product(name: "Logging", package: "swift-log"),
                 .product(name: "Metrics", package: "swift-metrics"),
                 .product(name: "NIO", package: "swift-nio"),
                 .product(name: "NIOConcurrencyHelpers", package: "swift-nio"),
@@ -128,17 +126,23 @@ let package = Package(
                 .copy("Utilities/test.env"),
                 .copy("Utilities/my-secret-env-content"),
                 .copy("Utilities/expired.crt"),
                 .copy("Utilities/expired.key"),
             ],
-            swiftSettings: [.enableExperimentalFeature("StrictConcurrency=complete")]
+            swiftSettings: [
+                .enableUpcomingFeature("BareSlashRegexLiterals"),
+                .enableExperimentalFeature("StrictConcurrency=complete"),
+            ]
         ),
         .testTarget(
             name: "AsyncTests",
             dependencies: [
                 .product(name: "NIOTestUtils", package: "swift-nio"),
                 .target(name: "XCTVapor"),
             ],
-            swiftSettings: [.enableExperimentalFeature("StrictConcurrency=complete")]
+            swiftSettings: [
+                .enableUpcomingFeature("BareSlashRegexLiterals"),
+                .enableExperimentalFeature("StrictConcurrency=complete"),
+            ]
         ),
     ]
 )
diff --git a/Sources/CVaporURLParser/include/urlparser.h b/Sources/CVaporURLParser/include/urlparser.h
deleted file mode 100755
index 1c9f285177..0000000000
--- a/Sources/CVaporURLParser/include/urlparser.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to
- * deal in the Software without restriction, including without limitation the
- * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
- * sell copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
- * IN THE SOFTWARE.
- */
-#ifndef urlparser_h
-#define urlparser_h
-#include <stdint.h>
-#include <stddef.h>
-
-enum vapor_urlparser_fields
-{ UF_SCHEMA           = 0
-    , UF_HOST             = 1
-    , UF_PORT             = 2
-    , UF_PATH             = 3
-    , UF_QUERY            = 4
-    , UF_FRAGMENT         = 5
-    , UF_USERINFO         = 6
-    , UF_MAX              = 7
-};
-
-struct vapor_urlparser_field_data {
-    uint16_t off;               /* Offset into buffer in which field starts */
-    uint16_t len;               /* Length of run in buffer */
-};
-
-/* Result structure for urlparser_parse_url().
- *
- * Callers should index into field_data[] with UF_* values iff field_set
- * has the relevant (1 << UF_*) bit set. As a courtesy to clients (and
- * because we probably have padding left over), we convert any port to
- * a uint16_t.
- */
-struct vapor_urlparser_url {
-    uint16_t field_set;           /* Bitmask of (1 << UF_*) values */
-    uint16_t port;                /* Converted UF_PORT string */
-    struct vapor_urlparser_field_data field_data[UF_MAX];
-};
-
-/* Parse a URL; return nonzero on failure */
-int vapor_urlparser_parse(const char *buf, size_t buflen,
-                          int is_connect,
-                          struct vapor_urlparser_url *u);
-#endif
diff --git a/Sources/CVaporURLParser/urlparser.c b/Sources/CVaporURLParser/urlparser.c
deleted file mode 100755
index 8ba216b881..0000000000
--- a/Sources/CVaporURLParser/urlparser.c
+++ /dev/null
@@ -1,707 +0,0 @@
-/* Copyright Joyent, Inc. and other Node contributors.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to
- * deal in the Software without restriction, including without limitation the
- * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
- * sell copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
- * IN THE SOFTWARE.
- */
-#include "urlparser.h"
-#include <assert.h>
-#include <stddef.h>
-#include <ctype.h>
-#include <string.h>
-#include <limits.h>
-
-#ifndef BIT_AT
-# define BIT_AT(a, i)                                                \
-(!!((unsigned int) (a)[(unsigned int) (i) >> 3] &                  \
-(1 << ((unsigned int) (i) & 7))))
-#endif
-
-/* Tokens as defined by rfc 2616. Also lowercases them.
- *        token       = 1*<any CHAR except CTLs or separators>
- *     separators     = "(" | ")" | "<" | ">" | "@"
- *                    | "," | ";" | ":" | "\" | <">
- *                    | "/" | "[" | "]" | "?" | "="
- *                    | "{" | "}" | SP | HT
- */
-static const char tokens[256] = {
-    /*   0 nul    1 soh    2 stx    3 etx    4 eot    5 enq    6 ack    7 bel  */
-    0,       0,       0,       0,       0,       0,       0,       0,
-    /*   8 bs     9 ht    10 nl    11 vt    12 np    13 cr    14 so    15 si   */
-    0,       0,       0,       0,       0,       0,       0,       0,
-    /*  16 dle   17 dc1   18 dc2   19 dc3   20 dc4   21 nak   22 syn   23 etb */
-    0,       0,       0,       0,       0,       0,       0,       0,
-    /*  24 can   25 em    26 sub   27 esc   28 fs    29 gs    30 rs    31 us  */
-    0,       0,       0,       0,       0,       0,       0,       0,
-    /*  32 sp    33  !    34  "    35  #    36  $    37  %    38  &    39  '  */
-    ' ',     '!',      0,      '#',     '$',     '%',     '&',    '\'',
-    /*  40  (    41  )    42  *    43  +    44  ,    45  -    46  .    47  /  */
-    0,       0,      '*',     '+',      0,      '-',     '.',      0,
-    /*  48  0    49  1    50  2    51  3    52  4    53  5    54  6    55  7  */
-    '0',     '1',     '2',     '3',     '4',     '5',     '6',     '7',
-    /*  56  8    57  9    58  :    59  ;    60  <    61  =    62  >    63  ?  */
-    '8',     '9',      0,       0,       0,       0,       0,       0,
-    /*  64  @    65  A    66  B    67  C    68  D    69  E    70  F    71  G  */
-    0,      'a',     'b',     'c',     'd',     'e',     'f',     'g',
-    /*  72  H    73  I    74  J    75  K    76  L    77  M    78  N    79  O  */
-    'h',     'i',     'j',     'k',     'l',     'm',     'n',     'o',
-    /*  80  P    81  Q    82  R    83  S    84  T    85  U    86  V    87  W  */
-    'p',     'q',     'r',     's',     't',     'u',     'v',     'w',
-    /*  88  X    89  Y    90  Z    91  [    92  \    93  ]    94  ^    95  _  */
-    'x',     'y',     'z',      0,       0,       0,      '^',     '_',
-    /*  96  `    97  a    98  b    99  c   100  d   101  e   102  f   103  g  */
-    '`',     'a',     'b',     'c',     'd',     'e',     'f',     'g',
-    /* 104  h   105  i   106  j   107  k   108  l   109  m   110  n   111  o  */
-    'h',     'i',     'j',     'k',     'l',     'm',     'n',     'o',
-    /* 112  p   113  q   114  r   115  s   116  t   117  u   118  v   119  w  */
-    'p',     'q',     'r',     's',     't',     'u',     'v',     'w',
-    /* 120  x   121  y   122  z   123  {   124  |   125  }   126  ~   127 del */
-    'x',     'y',     'z',      0,      '|',      0,      '~',       0 };
-
-
-static const int8_t unhex[256] =
-{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
-    ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
-    ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
-    , 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1
-    ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
-    ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
-    ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
-    ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
-};
-
-
-#if URLPARSER_STRICT
-# define T(v) 0
-#else
-# define T(v) v
-#endif
-
-
-static const uint8_t normal_url_char[32] = {
-    /*   0 nul    1 soh    2 stx    3 etx    4 eot    5 enq    6 ack    7 bel  */
-    0    |   0    |   0    |   0    |   0    |   0    |   0    |   0,
-    /*   8 bs     9 ht    10 nl    11 vt    12 np    13 cr    14 so    15 si   */
-    0    | T(2)   |   0    |   0    | T(16)  |   0    |   0    |   0,
-    /*  16 dle   17 dc1   18 dc2   19 dc3   20 dc4   21 nak   22 syn   23 etb */
-    0    |   0    |   0    |   0    |   0    |   0    |   0    |   0,
-    /*  24 can   25 em    26 sub   27 esc   28 fs    29 gs    30 rs    31 us  */
-    0    |   0    |   0    |   0    |   0    |   0    |   0    |   0,
-    /*  32 sp    33  !    34  "    35  #    36  $    37  %    38  &    39  '  */
-    0    |   2    |   4    |   0    |   16   |   32   |   64   |  128,
-    /*  40  (    41  )    42  *    43  +    44  ,    45  -    46  .    47  /  */
-    1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
-    /*  48  0    49  1    50  2    51  3    52  4    53  5    54  6    55  7  */
-    1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
-    /*  56  8    57  9    58  :    59  ;    60  <    61  =    62  >    63  ?  */
-    1    |   2    |   4    |   8    |   16   |   32   |   64   |   0,
-    /*  64  @    65  A    66  B    67  C    68  D    69  E    70  F    71  G  */
-    1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
-    /*  72  H    73  I    74  J    75  K    76  L    77  M    78  N    79  O  */
-    1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
-    /*  80  P    81  Q    82  R    83  S    84  T    85  U    86  V    87  W  */
-    1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
-    /*  88  X    89  Y    90  Z    91  [    92  \    93  ]    94  ^    95  _  */
-    1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
-    /*  96  `    97  a    98  b    99  c   100  d   101  e   102  f   103  g  */
-    1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
-    /* 104  h   105  i   106  j   107  k   108  l   109  m   110  n   111  o  */
-    1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
-    /* 112  p   113  q   114  r   115  s   116  t   117  u   118  v   119  w  */
-    1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
-    /* 120  x   121  y   122  z   123  {   124  |   125  }   126  ~   127 del */
-    1    |   2    |   4    |   8    |   16   |   32   |   64   |   0, };
-
-#undef T
-
-enum state
-{ s_dead = 1 /* important that this is > 0 */
-
-    , s_start_req_or_res
-    , s_res_or_resp_H
-    , s_start_res
-    , s_res_H
-    , s_res_HT
-    , s_res_HTT
-    , s_res_HTTP
-    , s_res_http_major
-    , s_res_http_dot
-    , s_res_http_minor
-    , s_res_http_end
-    , s_res_first_status_code
-    , s_res_status_code
-    , s_res_status_start
-    , s_res_status
-    , s_res_line_almost_done
-
-    , s_start_req
-
-    , s_req_method
-    , s_req_spaces_before_url
-    , s_req_schema
-    , s_req_schema_slash
-    , s_req_schema_slash_slash
-    , s_req_server_start
-    , s_req_server
-    , s_req_server_with_at
-    , s_req_path
-    , s_req_query_string_start
-    , s_req_query_string
-    , s_req_fragment_start
-    , s_req_fragment
-    , s_req_http_start
-    , s_req_http_H
-    , s_req_http_HT
-    , s_req_http_HTT
-    , s_req_http_HTTP
-    , s_req_http_I
-    , s_req_http_IC
-    , s_req_http_major
-    , s_req_http_dot
-    , s_req_http_minor
-    , s_req_http_end
-    , s_req_line_almost_done
-
-    , s_header_field_start
-    , s_header_field
-    , s_header_value_discard_ws
-    , s_header_value_discard_ws_almost_done
-    , s_header_value_discard_lws
-    , s_header_value_start
-    , s_header_value
-    , s_header_value_lws
-
-    , s_header_almost_done
-
-    , s_chunk_size_start
-    , s_chunk_size
-    , s_chunk_parameters
-    , s_chunk_size_almost_done
-
-    , s_headers_almost_done
-    , s_headers_done
-
-    /* Important: 's_headers_done' must be the last 'header' state. All
-     * states beyond this must be 'body' states. It is used for overflow
-     * checking. See the PARSING_HEADER() macro.
-     */
-
-    , s_chunk_data
-    , s_chunk_data_almost_done
-    , s_chunk_data_done
-
-    , s_body_identity
-    , s_body_identity_eof
-
-    , s_message_done
-};
-
-enum http_host_state
-{
-    s_http_host_dead = 1
-    , s_http_userinfo_start
-    , s_http_userinfo
-    , s_http_host_start
-    , s_http_host_v6_start
-    , s_http_host
-    , s_http_host_v6
-    , s_http_host_v6_end
-    , s_http_host_v6_zone_start
-    , s_http_host_v6_zone
-    , s_http_host_port_start
-    , s_http_host_port
-};
-
-/* Macros for character classes; depends on strict-mode  */
-#define CR                  '\r'
-#define LF                  '\n'
-#define LOWER(c)            (unsigned char)(c | 0x20)
-#define IS_ALPHA(c)         (LOWER(c) >= 'a' && LOWER(c) <= 'z')
-#define IS_NUM(c)           ((c) >= '0' && (c) <= '9')
-#define IS_ALPHANUM(c)      (IS_ALPHA(c) || IS_NUM(c))
-#define IS_HEX(c)           (IS_NUM(c) || (LOWER(c) >= 'a' && LOWER(c) <= 'f'))
-#define IS_MARK(c)          ((c) == '-' || (c) == '_' || (c) == '.' || \
-(c) == '!' || (c) == '~' || (c) == '*' || (c) == '\'' || (c) == '(' || \
-(c) == ')')
-#define IS_USERINFO_CHAR(c) (IS_ALPHANUM(c) || IS_MARK(c) || (c) == '%' || \
-(c) == ';' || (c) == ':' || (c) == '&' || (c) == '=' || (c) == '+' || \
-(c) == '$' || (c) == ',')
-
-#define STRICT_TOKEN(c)     ((c == ' ') ? 0 : tokens[(unsigned char)c])
-
-#if URLPARSER_STRICT
-#define TOKEN(c)            STRICT_TOKEN(c)
-#define IS_URL_CHAR(c)      (BIT_AT(normal_url_char, (unsigned char)c))
-#define IS_HOST_CHAR(c)     (IS_ALPHANUM(c) || (c) == '.' || (c) == '-')
-#else
-#define TOKEN(c)            tokens[(unsigned char)c]
-#define IS_URL_CHAR(c)                                                         \
-(BIT_AT(normal_url_char, (unsigned char)c) || ((c) & 0x80))
-#define IS_HOST_CHAR(c)                                                        \
-(IS_ALPHANUM(c) || (c) == '.' || (c) == '-' || (c) == '_')
-#endif
-
-/* Our URL parser.
- *
- * This is designed to be shared by urlparser_execute() for URL validation,
- * hence it has a state transition + byte-for-byte interface. In addition, it
- * is meant to be embedded in urlparser_parse_url(), which does the dirty
- * work of turning state transitions URL components for its API.
- *
- * This function should only be invoked with non-space characters. It is
- * assumed that the caller cares about (and can detect) the transition between
- * URL and non-URL states by looking for these.
- */
-static enum state
-parse_url_char(enum state s, const char ch)
-{
-    if (ch == ' ' || ch == '\r' || ch == '\n') {
-        return s_dead;
-    }
-
-#if URLPARSER_STRICT
-    if (ch == '\t' || ch == '\f') {
-        return s_dead;
-    }
-#endif
-
-    switch (s) {
-        case s_req_spaces_before_url:
-        /* Proxied requests are followed by scheme of an absolute URI (alpha).
-         * All methods except CONNECT are followed by '/' or '*'.
-         */
-
-        if (ch == '/' || ch == '*') {
-            return s_req_path;
-        }
-
-        if (IS_ALPHA(ch)) {
-            return s_req_schema;
-        }
-
-        break;
-
-        case s_req_schema:
-        if (IS_ALPHA(ch)) {
-            return s;
-        }
-
-        if (ch == ':') {
-            return s_req_schema_slash;
-        }
-
-        break;
-
-        case s_req_schema_slash:
-        if (ch == '/') {
-            return s_req_schema_slash_slash;
-        }
-
-        break;
-
-        case s_req_schema_slash_slash:
-        if (ch == '/') {
-            return s_req_server_start;
-        }
-
-        break;
-
-        case s_req_server_with_at:
-        if (ch == '@') {
-            return s_dead;
-        }
-
-        /* fall through */
-        case s_req_server_start:
-        case s_req_server:
-        if (ch == '/') {
-            return s_req_path;
-        }
-
-        if (ch == '?') {
-            return s_req_query_string_start;
-        }
-
-        if (ch == '@') {
-            return s_req_server_with_at;
-        }
-
-        if (IS_USERINFO_CHAR(ch) || ch == '[' || ch == ']') {
-            return s_req_server;
-        }
-
-        break;
-
-        case s_req_path:
-        if (IS_URL_CHAR(ch)) {
-            return s;
-        }
-
-        switch (ch) {
-            case '?':
-            return s_req_query_string_start;
-
-            case '#':
-            return s_req_fragment_start;
-        }
-
-        break;
-
-        case s_req_query_string_start:
-        case s_req_query_string:
-        if (IS_URL_CHAR(ch)) {
-            return s_req_query_string;
-        }
-
-        switch (ch) {
-            case '?':
-            /* allow extra '?' in query string */
-            return s_req_query_string;
-
-            case '#':
-            return s_req_fragment_start;
-        }
-
-        break;
-
-        case s_req_fragment_start:
-        if (IS_URL_CHAR(ch)) {
-            return s_req_fragment;
-        }
-
-        switch (ch) {
-            case '?':
-            return s_req_fragment;
-
-            case '#':
-            return s;
-        }
-
-        break;
-
-        case s_req_fragment:
-        if (IS_URL_CHAR(ch)) {
-            return s;
-        }
-
-        switch (ch) {
-            case '?':
-            case '#':
-            return s;
-        }
-
-        break;
-
-        default:
-        break;
-    }
-
-    /* We should never fall out of the switch above unless there's an error */
-    return s_dead;
-}
-
-static enum http_host_state
-http_parse_host_char(enum http_host_state s, const char ch) {
-    switch(s) {
-        case s_http_userinfo:
-        case s_http_userinfo_start:
-        if (ch == '@') {
-            return s_http_host_start;
-        }
-
-        if (IS_USERINFO_CHAR(ch)) {
-            return s_http_userinfo;
-        }
-        break;
-
-        case s_http_host_start:
-        if (ch == '[') {
-            return s_http_host_v6_start;
-        }
-
-        if (IS_HOST_CHAR(ch)) {
-            return s_http_host;
-        }
-
-        break;
-
-        case s_http_host:
-        if (IS_HOST_CHAR(ch)) {
-            return s_http_host;
-        }
-
-        /* fall through */
-        case s_http_host_v6_end:
-        if (ch == ':') {
-            return s_http_host_port_start;
-        }
-
-        break;
-
-        case s_http_host_v6:
-        if (ch == ']') {
-            return s_http_host_v6_end;
-        }
-
-        /* fall through */
-        case s_http_host_v6_start:
-        if (IS_HEX(ch) || ch == ':' || ch == '.') {
-            return s_http_host_v6;
-        }
-
-        if (s == s_http_host_v6 && ch == '%') {
-            return s_http_host_v6_zone_start;
-        }
-        break;
-
-        case s_http_host_v6_zone:
-        if (ch == ']') {
-            return s_http_host_v6_end;
-        }
-
-        /* fall through */
-        case s_http_host_v6_zone_start:
-        /* RFC 6874 Zone ID consists of 1*( unreserved / pct-encoded) */
-        if (IS_ALPHANUM(ch) || ch == '%' || ch == '.' || ch == '-' || ch == '_' ||
-            ch == '~') {
-            return s_http_host_v6_zone;
-        }
-        break;
-
-        case s_http_host_port:
-        case s_http_host_port_start:
-        if (IS_NUM(ch)) {
-            return s_http_host_port;
-        }
-
-        break;
-
-        default:
-        break;
-    }
-    return s_http_host_dead;
-}
-
-static int
-http_parse_host(const char * buf, struct vapor_urlparser_url *u, int found_at) {
-    enum http_host_state s;
-
-    const char *p;
-    size_t buflen = u->field_data[UF_HOST].off + u->field_data[UF_HOST].len;
-
-    assert(u->field_set & (1 << UF_HOST));
-
-    u->field_data[UF_HOST].len = 0;
-
-    s = found_at ? s_http_userinfo_start : s_http_host_start;
-
-    for (p = buf + u->field_data[UF_HOST].off; p < buf + buflen; p++) {
-        enum http_host_state new_s = http_parse_host_char(s, *p);
-
-        if (new_s == s_http_host_dead) {
-            return 1;
-        }
-
-        switch(new_s) {
-            case s_http_host:
-            if (s != s_http_host) {
-                u->field_data[UF_HOST].off = (uint16_t)(p - buf);
-            }
-            u->field_data[UF_HOST].len++;
-            break;
-
-            case s_http_host_v6:
-            if (s != s_http_host_v6) {
-                u->field_data[UF_HOST].off = (uint16_t)(p - buf);
-            }
-            u->field_data[UF_HOST].len++;
-            break;
-
-            case s_http_host_v6_zone_start:
-            case s_http_host_v6_zone:
-            u->field_data[UF_HOST].len++;
-            break;
-
-            case s_http_host_port:
-            if (s != s_http_host_port) {
-                u->field_data[UF_PORT].off = (uint16_t)(p - buf);
-                u->field_data[UF_PORT].len = 0;
-                u->field_set |= (1 << UF_PORT);
-            }
-            u->field_data[UF_PORT].len++;
-            break;
-
-            case s_http_userinfo:
-            if (s != s_http_userinfo) {
-                u->field_data[UF_USERINFO].off = (uint16_t)(p - buf);
-                u->field_data[UF_USERINFO].len = 0;
-                u->field_set |= (1 << UF_USERINFO);
-            }
-            u->field_data[UF_USERINFO].len++;
-            break;
-
-            default:
-            break;
-        }
-        s = new_s;
-    }
-
-    /* Make sure we don't end somewhere unexpected */
-    switch (s) {
-        case s_http_host_start:
-        case s_http_host_v6_start:
-        case s_http_host_v6:
-        case s_http_host_v6_zone_start:
-        case s_http_host_v6_zone:
-        case s_http_host_port_start:
-        case s_http_userinfo:
-        case s_http_userinfo_start:
-        return 1;
-        default:
-        break;
-    }
-
-    return 0;
-}
-
-void
-urlparser_url_init(struct vapor_urlparser_url *u) {
-    memset(u, 0, sizeof(*u));
-}
-
-int
-vapor_urlparser_parse(const char *buf, size_t buflen, int is_connect,
-                      struct vapor_urlparser_url *u)
-{
-    enum state s;
-    const char *p;
-    enum vapor_urlparser_fields uf, old_uf;
-    int found_at = 0;
-
-    if (buflen == 0) {
-        return 1;
-    }
-
-    u->port = u->field_set = 0;
-    s = is_connect ? s_req_server_start : s_req_spaces_before_url;
-    old_uf = UF_MAX;
-
-    for (p = buf; p < buf + buflen; p++) {
-        s = parse_url_char(s, *p);
-
-        /* Figure out the next field that we're operating on */
-        switch (s) {
-            case s_dead:
-            return 1;
-
-            /* Skip delimeters */
-            case s_req_schema_slash:
-            case s_req_schema_slash_slash:
-            case s_req_server_start:
-            case s_req_query_string_start:
-            case s_req_fragment_start:
-            continue;
-
-            case s_req_schema:
-            uf = UF_SCHEMA;
-            break;
-
-            case s_req_server_with_at:
-            found_at = 1;
-
-            /* fall through */
-            case s_req_server:
-            uf = UF_HOST;
-            break;
-
-            case s_req_path:
-            uf = UF_PATH;
-            break;
-
-            case s_req_query_string:
-            uf = UF_QUERY;
-            break;
-
-            case s_req_fragment:
-            uf = UF_FRAGMENT;
-            break;
-
-            default:
-            assert(!"Unexpected state");
-            return 1;
-        }
-
-        /* Nothing's changed; soldier on */
-        if (uf == old_uf) {
-            u->field_data[uf].len++;
-            continue;
-        }
-
-        u->field_data[uf].off = (uint16_t)(p - buf);
-        u->field_data[uf].len = 1;
-
-        u->field_set |= (1 << uf);
-        old_uf = uf;
-    }
-
-    /* host must be present if there is a schema */
-    /* parsing http:///toto will fail */
-    if ((u->field_set & (1 << UF_SCHEMA)) &&
-        (u->field_set & (1 << UF_HOST)) == 0) {
-        return 1;
-    }
-
-    if (u->field_set & (1 << UF_HOST)) {
-        if (http_parse_host(buf, u, found_at) != 0) {
-            return 1;
-        }
-    }
-
-    /* CONNECT requests can only contain "hostname:port" */
-    if (is_connect && u->field_set != ((1 << UF_HOST)|(1 << UF_PORT))) {
-        return 1;
-    }
-
-    if (u->field_set & (1 << UF_PORT)) {
-        uint16_t off;
-        uint16_t len;
-        const char* p;
-        const char* end;
-        unsigned long v;
-
-        off = u->field_data[UF_PORT].off;
-        len = u->field_data[UF_PORT].len;
-        end = buf + off + len;
-
-        /* NOTE: The characters are already validated and are in the [0-9] range */
-        assert(off + len <= buflen && "Port number overflow");
-        v = 0;
-        for (p = buf + off; p < end; p++) {
-            v *= 10;
-            v += *p - '0';
-
-            /* Ports have a max value of 2^16 */
-            if (v > 0xffff) {
-                return 1;
-            }
-        }
-
-        u->port = (uint16_t) v;
-    }
-
-    return 0;
-}
diff --git a/Sources/Vapor/HTTP/EndpointCache.swift b/Sources/Vapor/HTTP/EndpointCache.swift
index 0880ed29a4..5217cb567c 100644
--- a/Sources/Vapor/HTTP/EndpointCache.swift
+++ b/Sources/Vapor/HTTP/EndpointCache.swift
@@ -1,6 +1,10 @@
+#if !canImport(Darwin) && swift(<5.9)
+@preconcurrency import Foundation
+#else
 import Foundation
+#endif
 import NIOConcurrencyHelpers
 import NIOCore
 import Logging
 import NIOHTTP1
 
diff --git a/Sources/Vapor/HTTP/Headers/HTTPCookies.swift b/Sources/Vapor/HTTP/Headers/HTTPCookies.swift
index 6c76be6c66..aca7a28860 100644
--- a/Sources/Vapor/HTTP/Headers/HTTPCookies.swift
+++ b/Sources/Vapor/HTTP/Headers/HTTPCookies.swift
@@ -1,6 +1,10 @@
+#if !canImport(Darwin) && swift(<5.9)
+@preconcurrency import Foundation
+#else
 import Foundation
+#endif
 import NIOHTTP1
 
 extension HTTPHeaders {
     /// Get and set `HTTPCookies` for an HTTP request
     /// This accesses the `"Cookie"` header.
diff --git a/Sources/Vapor/Response/Response+Body.swift b/Sources/Vapor/Response/Response+Body.swift
index 1b99bca13c..d3998491f4 100644
--- a/Sources/Vapor/Response/Response+Body.swift
+++ b/Sources/Vapor/Response/Response+Body.swift
@@ -1,7 +1,11 @@
 @preconcurrency import Dispatch
+#if !canImport(Darwin) && swift(<5.9)
+@preconcurrency import Foundation
+#else
 import Foundation
+#endif
 import NIOCore
 import NIOConcurrencyHelpers
 
 extension Response {
     struct BodyStream: Sendable {
diff --git a/Sources/Vapor/Utilities/URI.swift b/Sources/Vapor/Utilities/URI.swift
index f74d310fe3..42e1b01335 100644
--- a/Sources/Vapor/Utilities/URI.swift
+++ b/Sources/Vapor/Utilities/URI.swift
@@ -1,228 +1,291 @@
-import CVaporURLParser
+#if !canImport(Darwin)
+@preconcurrency import struct Foundation.URLComponents
+#else
+import struct Foundation.URLComponents
+#endif
 
+/// A type for constructing and manipulating (most) Uniform Resource Indicators.
+///
+/// > Warning: This is **NOT** the same as Foundation's [`URL`] type!
+///
+/// Can be used to both parse strings containing well-formed URIs and to generate such strings from
+/// a set of individual URI components.
+///
+/// Use of this type is (gently, for now) discouraged. Consider using Foundation's [`URL`] and/or
+/// [`URLComponents`] types instead. See below for details.
+///
+/// ## URI is for URLs, not URIs
+///
+/// Thanks to both backwards compatibility requirements and name collision concerns, this type, despite
+/// its name, does not actually represent a generic Uniform Resource Identifier as defined by [RFC 3986].
+/// In particular, the underlying implementation is currently based on Foundation's [`URLComponents`] type,
+/// whose semantics are inconsistent between different methods; in addition, its behavior has differed
+/// drastically between the macOS and Linux implementations for most of its existence, and continues to do
+/// so in Swift 5.9. This is not expected to be remedied until the [`swift-foundation`] package reaches a
+/// 1.0 release, which as of this writing will not for quite some time yet). In short, instances of `URI`
+/// may not always behave as expected according to either the spec or what Foundation does.
+///
+/// [RFC 3986]: https://datatracker.ietf.org/doc/html/rfc3986
+/// [`swift-foundation`]: https://github.com/apple/swift-foundation
+/// [`URL`]: https://developer.apple.com/documentation/foundation/url
+/// [`URLComponents`]: https://developer.apple.com/documentation/foundation/urlcomponents
 public struct URI: Sendable, ExpressibleByStringInterpolation, CustomStringConvertible {
-    /// A URI's scheme.
-    public struct Scheme: Sendable, ExpressibleByStringInterpolation {
-        /// HTTP
-        public static let http: Self = "http"
-        
-        /// HTTPS
-        public static let https: Self = "https"
-        
-        /// HTTP over Unix Domain Socket Paths. The socket path should be encoded as the host in the URI, making sure to encode any special characters:
-        /// ```
-        /// host.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
-        /// ```
-        /// Do note that URI's initializer will encode the host in this way if you use `init(scheme:host:port:path:query:fragment:)`.
-        public static let httpUnixDomainSocket: Self = "http+unix"
-        
-        /// HTTPS over Unix Domain Socket Paths. The socket path should be encoded as the host in the URI, making sure to encode any special characters:
-        /// ```
-        /// host.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
-        /// ```
-        /// Do note that URI's initializer will encode the host in this way if you use `init(scheme:host:port:path:query:fragment:)`.
-        public static let httpsUnixDomainSocket: Self = "https+unix"
-        
-        public let value: String?
-        
-        public init(stringLiteral value: String) {
-            self.value = value
-        }
-        
-        public init(_ value: String? = nil) {
-            self.value = value
-        }
-    }
+    private var components: URLComponents?
     
-    public var string: String
-
     public init(string: String = "/") {
-        self.string = string
+        self.components = URL(string: string).flatMap { .init(url: $0, resolvingAgainstBaseURL: true) }
     }
 
     public var description: String {
-        return self.string
+        self.string
     }
 
     public init(
         scheme: String?,
+        userinfo: String?,
         host: String? = nil,
         port: Int? = nil,
         path: String,
         query: String? = nil,
         fragment: String? = nil
     ) {
         self.init(
             scheme: Scheme(scheme),
+            userinfo: userinfo,
             host: host,
             port: port,
             path: path,
             query: query,
             fragment: fragment
         )
     }
+
+    public init(scheme: String?, host: String? = nil, port: Int? = nil, path: String, query: String? = nil, fragment: String? = nil) {
+        self.init(scheme: scheme, userinfo: nil, host: host, port: port, path: path, query: query, fragment: fragment)
+    }
+    
+    public init(scheme: Scheme = .init(), host: String? = nil, port: Int? = nil, path: String, query: String? = nil, fragment: String? = nil) {
+        self.init(scheme: scheme, userinfo: nil, host: host, port: port, path: path, query: query, fragment: fragment)
+    }
     
+    /// Construct a ``URI`` from various subcomponents.
+    ///
+    /// Percent encoding is added to each component (if necessary) automatically. There is currently no
+    /// way to change this behavior; use `URLComponents` instead if this is insufficient.
+    ///
+    /// > Warning: For backwards compatibility reasons, if the `path` component is specified in isolation
+    /// > (e.g. all other components are `nil`), the path is parsed as if by the ``init(string:)`` initializer.
+    ///
+    /// > Important: If the `path` does not begin with a `/`, one is prepended. This occurs even if the path
+    /// > is specified in isolation (as described above).
     public init(
-        scheme: Scheme = Scheme(),
+        scheme: Scheme = .init(),
+        userinfo: String?,
         host: String? = nil,
         port: Int? = nil,
         path: String,
         query: String? = nil,
         fragment: String? = nil
     ) {
-        var string = ""
-        if let scheme = scheme.value {
-            string += scheme + "://"
-        }
-        if let host = host?.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) {
-            string += host
-        }
-        if let port = port {
-            string += ":" + port.description
-        }
-        if path.hasPrefix("/") {
-            string += path
+        let path = path.first == "/" ? path : "/\(path)"
+        var components: URLComponents!
+        
+        if scheme.value == nil, userinfo == nil, host == nil, port == nil, query == nil, fragment == nil {
+            // If only a path is given, treat it as a string to parse. (This behavior is awful, but must be kept for compatibility.)
+            components = URL(string: path).flatMap { .init(url: $0, resolvingAgainstBaseURL: true) }
         } else {
-            string += "/" + path
-        }
-        if let query = query {
-            string += "?" + query
+            // N.B.: We perform percent encoding manually and unconditionally on each non-nil component because the
+            // behavior of URLComponents is completely different on Linux than on macOS for inputs which are already
+            // fully or partially percent-encoded, as well as inputs which contain invalid characters (especially
+            // for the host component). This is the only way to provide consistent behavior (and to avoid various
+            // fatalError()s in URLComponents on Linux).
+            components = .init()
+            components.scheme = scheme.value?.addingPercentEncoding(withAllowedCharacters: .urlSchemeAllowed)
+            if let host {
+                if let creds = userinfo?.split(separator: ":", maxSplits: 1, omittingEmptySubsequences: false), !creds[0].isEmpty {
+                    components.percentEncodedUser = creds[0].addingPercentEncoding(withAllowedCharacters: .urlUserAllowed)
+                    if creds.count > 1, !creds[1].isEmpty {
+                        components.percentEncodedPassword = creds[1].addingPercentEncoding(withAllowedCharacters: .urlPasswordAllowed)
+                    }
+                }
+                // TODO: Use the `encodedHost` polyfill
+                #if canImport(Darwin)
+                if #available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) {
+                    components.encodedHost = host.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
+                } else {
+                    components.percentEncodedHost = host.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
+                }
+                #else
+                components.percentEncodedHost = host.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
+                #endif
+                components.port = port
+            } else {
+                // TODO: Should this be enforced?
+                // assert(userinfo == nil, "Can't provide userinfo without an authority (hostname)")
+                // assert(port == nil, "Can't provide userinfo without an authority (hostname)")
+            }
+            components.percentEncodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlCorrectPathAllowed) ?? "/"
+            components.percentEncodedQuery = query?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
+            components.percentEncodedFragment = fragment?.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)
         }
-        if let fragment = fragment {
-            string += "#" + fragment
-        }
-        self.string = string
+        self.components = components
     }
 
     public init(stringLiteral value: String) {
         self.init(string: value)
     }
 
-    private enum Component {
-        case scheme, host, port, path, query, fragment, userinfo
-    }
-
     public var scheme: String? {
-        get {
-            return self.parse(.scheme)
-        }
+        get { self.components?.scheme }
+        set { self.components?.scheme = newValue }
+    }
+    
+    public var userinfo: String? {
+        get { self.components?.user.map { "\($0)\(self.components?.password.map { ":\($0)" } ?? "")" } }
         set {
-            self = .init(
-                scheme: newValue,
-                host: self.host,
-                port: self.port,
-                path: self.path,
-                query: self.query,
-                fragment: self.fragment
-            )
+            if let userinfoData = newValue?.split(separator: ":", maxSplits: 1, omittingEmptySubsequences: false) {
+                self.components?.user = .init(userinfoData[0])
+                self.components?.password = userinfoData.count > 1 ? .init(userinfoData[1]) : nil
+            } else {
+                self.components?.user = nil
+            }
         }
     }
 
     public var host: String? {
-        get {
-            return self.parse(.host)
-        }
-        set {
-            self = .init(
-                scheme: self.scheme,
-                host: newValue,
-                port: self.port,
-                path: self.path,
-                query: self.query,
-                fragment: self.fragment
-            )
-        }
+        get { self.components?.host }
+        set { self.components?.host = newValue }
     }
 
     public var port: Int? {
-        get {
-            return self.parse(.port).flatMap(Int.init)
-        }
-        set {
-            self = .init(
-                scheme: self.scheme,
-                host: self.host,
-                port: newValue,
-                path: self.path,
-                query: self.query,
-                fragment: self.fragment
-            )
-        }
+        get { self.components?.port }
+        set { self.components?.port = newValue }
     }
 
     public var path: String {
-        get {
-            return self.parse(.path) ?? ""
-        }
-        set {
-            self = .init(
-                scheme: self.scheme,
-                host: self.host,
-                port: self.port,
-                path: newValue,
-                query: self.query,
-                fragment: self.fragment
-            )
-        }
+        get { self.components?.path ?? "/" }
+        set { self.components?.path = newValue }
     }
 
     public var query: String? {
-        get {
-            return self.parse(.query)
-        }
-        set {
-            self = .init(
-                scheme: self.scheme,
-                host: self.host,
-                port: self.port,
-                path: self.path,
-                query: newValue,
-                fragment: self.fragment
-            )
-        }
+        get { self.components?.query }
+        set { self.components?.query = newValue }
     }
 
     public var fragment: String? {
-        get {
-            return self.parse(.fragment)
-        }
-        set {
-            self = .init(
-                scheme: self.scheme,
-                host: self.host,
-                port: self.port,
-                path: self.path,
-                query: self.query,
-                fragment: newValue
-            )
-        }
+        get { self.components?.fragment }
+        set { self.components?.fragment = newValue }
     }
 
-    private func parse(_ component: Component) -> String? {
-        var url = vapor_urlparser_url()
-        vapor_urlparser_parse(self.string, self.string.count, 0, &url)
-        let data: vapor_urlparser_field_data
-        switch component {
-        case .scheme:
-            data = url.field_data.0
-        case .host:
-            data = url.field_data.1
-        case .port:
-            data = url.field_data.2
-        case .path:
-            data = url.field_data.3
-        case .query:
-            data = url.field_data.4
-        case .fragment:
-            data = url.field_data.5
-        case .userinfo:
-            data = url.field_data.6
-        }
-        if data.len == 0 {
-            return nil
-        }
-        let start = self.string.index(self.string.startIndex, offsetBy: numericCast(data.off))
-        let end = self.string.index(start, offsetBy: numericCast(data.len))
-        return String(self.string[start..<end])
+    public var string: String {
+        #if canImport(Darwin)
+        self.components?.string ?? ""
+        #else
+        // On Linux, URLComponents incorrectly treats `;` as *not* allowed in the path component.
+        self.components?.string?.replacingOccurrences(of: "%3B", with: ";") ?? ""
+        #endif
+    }
+    
+}
+
+extension URI {
+    /// A URI scheme, as defined by [RFC 3986 § 3.1] and [RFC 7595].
+    ///
+    /// [RFC 3986 § 3.1]: https://datatracker.ietf.org/doc/html/rfc3986#section-3.1
+    /// [RGC 7595]: https://datatracker.ietf.org/doc/html/rfc7595
+    public struct Scheme {
+        /// The string representation of the scheme.
+        public let value: String?
+        
+        /// Designated initializer.
+        ///
+        /// - Parameter value: The string representation for the desired scheme.
+        public init(_ value: String? = nil) { self.value = value }
+
+        // MARK: - "Well-known" schemes
+        
+        /// HyperText Transfer Protocol (HTTP)
+        ///
+        /// > Registration: [RFC 9110 § 4.2.1](https://www.rfc-editor.org/rfc/rfc9110.html#section-4.2.1)
+        public static let http: Self = "http"
+        
+        /// Secure HyperText Transfer Protocol (HTTPS)
+        ///
+        /// > Registration: [RFC 9110 § 4.2.2](https://www.rfc-editor.org/rfc/rfc9110.html#section-4.2.2)
+        public static let https: Self = "https"
+        
+        /// HyperText Transfer Protocol (HTTP) over Unix Domain Sockets.
+        ///
+        /// The socket path must be given as the URI's "host" component, appropriately percent-encoded. The
+        /// ``URI/init(scheme:userinfo:host:port:path:query:fragment:)`` initializer adds such encoding
+        /// automatically. To manually apply the correct encoding, use:
+        ///
+        /// ```swift
+        /// socketPath.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
+        /// ```
+        /// 
+        /// > Registration: None (non-standard)
+        public static let httpUnixDomainSocket: Self = "http+unix"
+        
+        /// Secure HyperText Transfer Protocol (HTTPS) over Unix Domain Sockets.
+        ///
+        /// The socket path must be given as the URI's "host" component, appropriately percent-encoded. The
+        /// ``URI/init(scheme:userinfo:host:port:path:query:fragment:)`` initializer adds such encoding
+        /// automatically. To manually apply the correct encoding, use:
+        ///
+        /// ```swift
+        /// socketPath.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
+        /// ```
+        ///
+        /// > Note: The primary use case for this scheme is for local communication with servers (most
+        /// > often database servers) which require TLS client certificate authentication. In most other
+        /// > situations, the added encryption is unnecessary and will just slow things down.
+        /// >
+        /// > (Well, unless your security concerns include other processes spying on your server's
+        /// > communications when using UNIX sockets. But since doing that would require having already
+        /// > compromised the host kernel ("It rather involved being on the other side of this airtight
+        /// > hatchway."), it seems fairly safe to say such a concern would be moot.)
+        ///
+        /// > Registration: None (non-standard)
+        public static let httpsUnixDomainSocket: Self = "https+unix"
+        
+        // MARK: End of "well-known" schemes -
+    }
+}
+
+extension URI.Scheme: ExpressibleByStringInterpolation {
+    // See `ExpressibleByStringInterpolation.init(stringLiteral:)`.
+    public init(stringLiteral value: String) { self.init(value) }
+}
+
+extension URI.Scheme: CustomStringConvertible {
+    // See `CustomStringConvertible.description`.
+    public var description: String { self.value ?? "" }
+}
+
+extension URI.Scheme: Sendable {}
+
+extension CharacterSet {
+    /// The set of characters allowed in a URI scheme, as per [RFC 3986 § 3.1].
+    ///
+    /// [RFC 3986 § 3.1]: https://datatracker.ietf.org/doc/html/rfc3986#section-3.1
+    fileprivate static var urlSchemeAllowed: Self {
+        // Intersect the alphanumeric set plus additional characters with the host-allowed set to ensure
+        // we get only ASCII codepoints in the result.
+        Self.urlHostAllowed.intersection(Self.alphanumerics.union(.init(charactersIn: "+-.")))
+    }
+    
+    /// The set of characters allowed in a URI path, as per [RFC 3986 § 3.3].
+    ///
+    /// > Note: This is identical to the built-in `urlPathAllowed` on macOS; on Linux it adds the missing
+    /// > semicolon character to the set.
+    ///
+    /// [RFC 3986 § 3.3]: https://datatracker.ietf.org/doc/html/rfc3986#section-3.3
+    fileprivate static var urlCorrectPathAllowed: Self {
+        #if canImport(Darwin)
+        .urlPathAllowed
+        #else
+        .urlPathAllowed.union(.init(charactersIn: ";"))
+        #endif
     }
 }
diff --git a/Tests/VaporTests/ClientTests.swift b/Tests/VaporTests/ClientTests.swift
index 03f4fa815d..9d90a9b558 100644
--- a/Tests/VaporTests/ClientTests.swift
+++ b/Tests/VaporTests/ClientTests.swift
@@ -1,20 +1,18 @@
-#if os(Linux)
-@preconcurrency import Foundation
-#else
-import Foundation
+#if !canImport(Darwin)
+@preconcurrency import Dispatch
 #endif
+import Foundation
 import XCTest
 import Vapor
 import NIOCore
 import Logging
 import AsyncHTTPClient
 import NIOEmbedded
 import NIOConcurrencyHelpers
 
 final class ClientTests: XCTestCase {
-    
     var remoteAppPort: Int!
     var remoteApp: Application!
     
     override func setUp() async throws {
         remoteApp = Application(.testing)
diff --git a/Tests/VaporTests/RequestTests.swift b/Tests/VaporTests/RequestTests.swift
index 4df2884ce1..0499fb4cae 100644
--- a/Tests/VaporTests/RequestTests.swift
+++ b/Tests/VaporTests/RequestTests.swift
@@ -141,111 +141,10 @@ final class RequestTests: XCTestCase {
         try app.testable(method: .running(port: 0)).test(.GET, "remote") { res in
             XCTAssertContains(res.body.string, "IP")
         }
     }
 
-    func testURI() throws {
-        do {
-            var uri = URI(string: "http://vapor.codes/foo?bar=baz#qux")
-            XCTAssertEqual(uri.scheme, "http")
-            XCTAssertEqual(uri.host, "vapor.codes")
-            XCTAssertEqual(uri.path, "/foo")
-            XCTAssertEqual(uri.query, "bar=baz")
-            XCTAssertEqual(uri.fragment, "qux")
-            uri.query = "bar=baz&test=1"
-            XCTAssertEqual(uri.string, "http://vapor.codes/foo?bar=baz&test=1#qux")
-            uri.query = nil
-            XCTAssertEqual(uri.string, "http://vapor.codes/foo#qux")
-        }
-        do {
-            let uri = URI(string: "/foo/bar/baz")
-            XCTAssertEqual(uri.path, "/foo/bar/baz")
-        }
-        do {
-            let uri = URI(string: "ws://echo.websocket.org/")
-            XCTAssertEqual(uri.scheme, "ws")
-            XCTAssertEqual(uri.host, "echo.websocket.org")
-            XCTAssertEqual(uri.path, "/")
-        }
-        do {
-            let uri = URI(string: "http://foo")
-            XCTAssertEqual(uri.scheme, "http")
-            XCTAssertEqual(uri.host, "foo")
-            XCTAssertEqual(uri.path, "")
-        }
-        do {
-            let uri = URI(string: "foo")
-            XCTAssertEqual(uri.scheme, "foo")
-            XCTAssertEqual(uri.host, nil)
-            XCTAssertEqual(uri.path, "")
-        }
-        do {
-            let uri: URI = "/foo/bar/baz"
-            XCTAssertEqual(uri.path, "/foo/bar/baz")
-        }
-        do {
-            let foo = "foo"
-            let uri: URI = "/\(foo)/bar/baz"
-            XCTAssertEqual(uri.path, "/foo/bar/baz")
-        }
-        do {
-            let uri = URI(scheme: "foo", host: "host", port: 1, path: "test", query: "query", fragment: "fragment")
-            XCTAssertEqual(uri.string, "foo://host:1/test?query#fragment")
-        }
-        do {
-            let bar = "bar"
-            let uri = URI(scheme: "foo\(bar)", host: "host", port: 1, path: "test", query: "query", fragment: "fragment")
-            XCTAssertEqual(uri.string, "foobar://host:1/test?query#fragment")
-        }
-        do {
-            let uri = URI(scheme: "foo", host: "host", port: 1, path: "/test", query: "query", fragment: "fragment")
-            XCTAssertEqual(uri.string, "foo://host:1/test?query#fragment")
-        }
-        do {
-            let scheme = "foo"
-            let uri = URI(scheme: scheme, host: "host", port: 1, path: "test", query: "query", fragment: "fragment")
-            XCTAssertEqual(uri.string, "foo://host:1/test?query#fragment")
-        }
-        do {
-            let scheme: String? = "foo"
-            let uri = URI(scheme: scheme, host: "host", port: 1, path: "test", query: "query", fragment: "fragment")
-            XCTAssertEqual(uri.string, "foo://host:1/test?query#fragment")
-        }
-        do {
-            let uri = URI(scheme: .http, host: "host", port: 1, path: "test", query: "query", fragment: "fragment")
-            XCTAssertEqual(uri.string, "http://host:1/test?query#fragment")
-        }
-        do {
-            let uri = URI(scheme: nil, host: "host", port: 1, path: "test", query: "query", fragment: "fragment")
-            XCTAssertEqual(uri.string, "host:1/test?query#fragment")
-        }
-        do {
-            let uri = URI(scheme: URI.Scheme(), host: "host", port: 1, path: "test", query: "query", fragment: "fragment")
-            XCTAssertEqual(uri.string, "host:1/test?query#fragment")
-        }
-        do {
-            let uri = URI(host: "host", port: 1, path: "test", query: "query", fragment: "fragment")
-            XCTAssertEqual(uri.string, "host:1/test?query#fragment")
-        }
-        do {
-            let uri = URI(scheme: .httpUnixDomainSocket, host: "/path", path: "test", query: "query", fragment: "fragment")
-            XCTAssertEqual(uri.string, "http+unix://%2Fpath/test?query#fragment")
-        }
-        do {
-            let uri = URI(scheme: .httpUnixDomainSocket, host: "/path", path: "test", fragment: "fragment")
-            XCTAssertEqual(uri.string, "http+unix://%2Fpath/test#fragment")
-        }
-        do {
-            let uri = URI(scheme: .httpUnixDomainSocket, host: "/path", path: "test")
-            XCTAssertEqual(uri.string, "http+unix://%2Fpath/test")
-        }
-        do {
-            let uri = URI()
-            XCTAssertEqual(uri.string, "/")
-        }
-    }
-    
     func testRedirect() throws {
         let app = Application(.testing)
         defer { app.shutdown() }
         
         app.http.client.configuration.redirectConfiguration = .disallow
diff --git a/Tests/VaporTests/ServerTests.swift b/Tests/VaporTests/ServerTests.swift
index 0d987a9769..997c5cabc4 100644
--- a/Tests/VaporTests/ServerTests.swift
+++ b/Tests/VaporTests/ServerTests.swift
@@ -1,10 +1,9 @@
-#if os(Linux)
-@preconcurrency import Foundation
-#else
-import Foundation
+#if !canImport(Darwin)
+@preconcurrency import Dispatch
 #endif
+import Foundation
 import Vapor
 import XCTest
 import AsyncHTTPClient
 import NIOCore
 import NIOPosix
diff --git a/Tests/VaporTests/URITests.swift b/Tests/VaporTests/URITests.swift
new file mode 100644
index 0000000000..712713f7a2
--- /dev/null
+++ b/Tests/VaporTests/URITests.swift
@@ -0,0 +1,345 @@
+import XCTVapor
+import XCTest
+import Vapor
+import NIOCore
+import Algorithms
+
+extension RangeReplaceableCollection where Self.SubSequence == Substring, Self: StringProtocol {
+    #if compiler(>=5.9)
+    #if hasFeature(BareSlashRegexLiterals)
+    private static var percentEncodingPattern: Regex<Substring> { /(?:%\p{AHex}{2})+/ }
+    #else
+    private static var percentEncodingPattern: Regex<Substring> { try! Regex("(?:%\\p{AHex}{2})+") }
+    #endif
+    #else
+    private static var percentEncodingPattern: Regex<Substring> { try! Regex("(?:%\\p{AHex}{2})+") }
+    #endif
+    
+    /// Foundation's `String.removingPercentEncoding` property is very unforgiving; `nil` is returned
+    /// for any kind of failure whatsoever. This is just a version that gracefully ignores invalid
+    /// sequences whenever possible (which is almost always).
+    var safelyUrlDecoded: Self {
+        self.replacing(
+            Self.percentEncodingPattern,
+            with: { Self(decoding: $0.0.split(separator: "%").map { .init($0, radix: 16)! }, as: UTF8.self) }
+        )
+    }
+}
+
+func XCTAssertURIComponents(
+       scheme: @autoclosure () throws -> URI.Scheme?,
+     userinfo: @autoclosure () throws -> String? = nil,
+         host: @autoclosure () throws -> String? = nil,
+         port: @autoclosure () throws -> Int?    = nil,
+         path: @autoclosure () throws -> String,
+        query: @autoclosure () throws -> String? = nil,
+     fragment: @autoclosure () throws -> String? = nil,
+     generate expected: @autoclosure () throws -> String,
+    _ message: @autoclosure () -> String = "", file: StaticString = #filePath, line: UInt = #line
+) {
+    XCTAssertURIComponents(
+        scheme: try scheme()?.value,
+        userinfo: try userinfo(),
+        host: try host(),
+        port: try port(),
+        path: try path(),
+        query: try query(),
+        fragment: try fragment(),
+        generate: try expected(),
+        message(), file: file, line: line
+    )
+}
+
+func XCTAssertURIComponents(
+       scheme: @autoclosure () throws -> String? = nil,
+     userinfo: @autoclosure () throws -> String? = nil,
+         host: @autoclosure () throws -> String? = nil,
+         port: @autoclosure () throws -> Int?    = nil,
+         path: @autoclosure () throws -> String,
+        query: @autoclosure () throws -> String? = nil,
+     fragment: @autoclosure () throws -> String? = nil,
+     generate expected: @autoclosure () throws -> String,
+    _ message: @autoclosure () -> String = "", file: StaticString = #filePath, line: UInt = #line
+) {
+    do {
+        let scheme = try scheme(), userinfo = try userinfo(), host = try host(), port = try port(),
+            path = try path(), query = try query(), fragment = try fragment()
+        let uri = URI(scheme: scheme, userinfo: userinfo, host: host, port: port, path: path, query: query, fragment: fragment)
+        
+        // All components should be identical to their input counterparts, sans percent encoding.
+        XCTAssertEqual(uri.scheme,   scheme?.safelyUrlDecoded,   "(scheme) \(message())", file: file, line: line)
+        XCTAssertEqual(uri.userinfo, userinfo?.safelyUrlDecoded, "(userinfo) \(message())", file: file, line: line)
+        XCTAssertEqual(uri.host,     host?.safelyUrlDecoded,     "(host) \(message())", file: file, line: line)
+        XCTAssertEqual(uri.port,     port,                       "(port) \(message())", file: file, line: line)
+        XCTAssertEqual(uri.path,     "/\(path.safelyUrlDecoded.trimmingPrefix("/"))", "(path) \(message())", file: file, line: line)
+        XCTAssertEqual(uri.query,    query?.safelyUrlDecoded,    "(query) \(message())", file: file, line: line)
+        XCTAssertEqual(uri.fragment, fragment?.safelyUrlDecoded, "(fragment) \(message())", file: file, line: line)
+        
+        // The URI's generated string should match the expected input.
+        XCTAssertEqual(uri.string,   try expected(),             "(string) \(message())", file: file, line: line)
+    } catch {
+        XCTAssertEqual(try { throw error }(), false,             message(), file: file, line: line)
+    }
+}
+
+func XCTAssertURIString(
+     _ string: @autoclosure () throws -> String,
+     hasScheme scheme:     @autoclosure () throws -> String? = nil,
+     hasUserinfo userinfo: @autoclosure () throws -> String? = nil,
+     hasHost host:         @autoclosure () throws -> String? = "",
+     hasPort port:         @autoclosure () throws -> Int?    = nil,
+     hasPath path:         @autoclosure () throws -> String,
+     hasQuery query:       @autoclosure () throws -> String? = nil,
+     hasFragment fragment: @autoclosure () throws -> String? = nil,
+     hasEqualString exact: @autoclosure () throws -> Bool = true,
+    _ message: @autoclosure () -> String = "", file: StaticString = #filePath, line: UInt = #line
+) {
+    do {
+        let string = try string()
+        let uri = URI(string: string)
+
+        // Each component should match its expected value.
+        XCTAssertEqual(uri.scheme,   try scheme()?.safelyUrlDecoded,   "(scheme) \(message())", file: file, line: line)
+        XCTAssertEqual(uri.userinfo, try userinfo()?.safelyUrlDecoded, "(userinfo) \(message())", file: file, line: line)
+        XCTAssertEqual(uri.host,     try host()?.safelyUrlDecoded,     "(host) \(message())", file: file, line: line)
+        XCTAssertEqual(uri.port,     try port(),                       "(port) \(message())", file: file, line: line)
+        XCTAssertEqual(uri.path,     try path().safelyUrlDecoded,      "(path) \(message())", file: file, line: line)
+        XCTAssertEqual(uri.query,    try query()?.safelyUrlDecoded,    "(query) \(message())", file: file, line: line)
+        XCTAssertEqual(uri.fragment, try fragment()?.safelyUrlDecoded, "(fragment) \(message())", file: file, line: line)
+        
+        // The URI's generated string should come out identical to the input string, unless explicitly stated otherwise.
+        if try exact() {
+            XCTAssertEqual(uri.string,   string,                       "(string) \(message())", file: file, line: line)
+        }
+    } catch {
+        XCTAssertEqual(try { throw error }(), false,                   message(), file: file, line: line)
+    }
+}
+
+final class URITests: XCTestCase {
+    func testBasicConstruction() {
+        XCTAssertURIString(
+            "https://user:pass@vapor.codes:1234/foo?bar=baz#qux",
+            hasScheme: "https",
+            hasUserinfo: "user:pass",
+            hasHost: "vapor.codes",
+            hasPort: 1234,
+            hasPath: "/foo",
+            hasQuery: "bar=baz",
+            hasFragment: "qux"
+        )
+        XCTAssertURIComponents(
+            scheme: "https",
+            userinfo: "user:pass",
+            host: "vapor.codes",
+            port: 1234,
+            path: "/foo",
+            query: "bar=baz",
+            fragment: "qux",
+            generate: "https://user:pass@vapor.codes:1234/foo?bar=baz#qux"
+        )
+
+        XCTAssertURIString("wss://echo.websocket.org/", hasScheme: "wss", hasHost: "echo.websocket.org", hasPath: "/")
+        XCTAssertURIComponents(scheme: "wss", host: "echo.websocket.org", path: "/", generate: "wss://echo.websocket.org/")
+    }
+    
+    func testMutation() {
+        var uri = URI(string: "https://user:pass@vapor.codes:1234/foo?bar=baz#qux")
+    
+        // Mutate query
+        uri.query = "bar=baz&test=1"
+        XCTAssertEqual(uri.string, "https://user:pass@vapor.codes:1234/foo?bar=baz&test=1#qux")
+
+        // Remove query
+        uri.query = nil
+        XCTAssertEqual(uri.string, "https://user:pass@vapor.codes:1234/foo#qux")
+    }
+    
+    func testPathStrings() {
+        // Absolute path string
+        let uri = URI(string: "/foo/bar/baz")
+        XCTAssertEqual(uri.path, "/foo/bar/baz")
+    }
+    
+    func testNonAbsolutePath() {
+        let uri = URI(string: "foo")
+
+        // N.B.: This test previously asserted that the _scheme_ of the resulting URI was `foo`. This was
+        // a semantically incorrect parse (per RFC 3986) and should have been considered a bug; hence it
+        // is not considered source-breaking to have fixed it.
+        XCTAssertEqual(uri.scheme, nil)
+        XCTAssertEqual(uri.host, nil)
+        XCTAssertEqual(uri.path, "foo")
+    }
+    
+    func testStringInterpolation() {
+        let foo = "foo"
+        XCTAssertEqual(("/\(foo)/bar/baz" as URI).path, "/foo/bar/baz")
+
+        let bar = "bar"
+        let uri = URI(scheme: "foo\(bar)", host: "host", port: 1, path: "test", query: "query", fragment: "fragment")
+        XCTAssertEqual(uri.string, "foobar://host:1/test?query#fragment")
+    }
+    
+    func testVariousSchemesAndWeirdHosts() {
+        // N.B.: This test previously asserted that the resulting string did _not_ start with the `//` "authority"
+        // prefix. Again, according to RFC 3986, this was always semantically incorrect.
+        XCTAssertURIComponents(
+            host: "host", port: 1, path: "test", query: "query", fragment: "fragment",
+            generate: "//host:1/test?query#fragment"
+        )
+        XCTAssertURIComponents(
+            scheme: .httpUnixDomainSocket, host: "/path", path: "test",
+            generate: "http+unix://%2Fpath/test"
+        )
+        XCTAssertURIComponents(
+            scheme: .httpUnixDomainSocket, host: "/path", path: "test", fragment: "fragment",
+            generate: "http+unix://%2Fpath/test#fragment"
+        )
+        XCTAssertURIComponents(
+            scheme: .httpUnixDomainSocket, host: "/path", path: "test", query: "query", fragment: "fragment",
+            generate: "http+unix://%2Fpath/test?query#fragment"
+        )
+    }
+    
+    func testDefaultInitializer() {
+        let uri = URI.init()
+        XCTAssertEqual(uri.string, "/")
+    }
+    
+    func testOverlongURIParsing() {
+        let zeros = String(repeating: "0", count: 65_512)
+        let untrustedInput = "[https://vapor.codes.somewhere-else.test:](https://vapor.codes.somewhere-else.test/\(zeros)443)[\(zeros)](https://vapor.codes.somewhere-else.test/\(zeros)443)[443](https://vapor.codes.somewhere-else.test/\(zeros)443)"
+    
+        XCTAssertURIString(untrustedInput, hasHost: nil, hasPath: untrustedInput, hasEqualString: false)
+    }
+    
+    func testUrlParsingVectors() {
+        XCTAssertURIString("file:///usr/local/bin", hasScheme: "file", hasPath: "/usr/local/bin")
+        XCTAssertURIString("file:/usr/local/bin", hasScheme: "file", hasHost: nil, hasPath: "/usr/local/bin")
+        XCTAssertURIString("file://localhost/usr/local/bin", hasScheme: "file", hasHost: "localhost", hasPath: "/usr/local/bin")
+        XCTAssertURIString("file://usr/local/bin", hasScheme: "file", hasHost: "usr", hasPath: "/local/bin")
+        XCTAssertURIString("/usr/local/bin", hasHost: nil, hasPath: "/usr/local/bin")
+        XCTAssertURIString("file://localhost/usr/local/bin/", hasScheme: "file", hasHost: "localhost", hasPath: "/usr/local/bin/")
+        XCTAssertURIString("file://localhost/", hasScheme: "file", hasHost: "localhost", hasPath: "/")
+        XCTAssertURIString("file:///", hasScheme: "file", hasPath: "/")
+        XCTAssertURIString("file:/", hasScheme: "file", hasHost: nil, hasPath: "/")
+        XCTAssertURIString("file:///Volumes", hasScheme: "file", hasPath: "/Volumes")
+        XCTAssertURIString("file:///Users/darin", hasScheme: "file", hasPath: "/Users/darin")
+        XCTAssertURIString("file:/", hasScheme: "file", hasHost: nil, hasPath: "/")
+        XCTAssertURIString("file:///.", hasScheme: "file", hasPath: "/.")
+        XCTAssertURIString("file:///./.", hasScheme: "file", hasPath: "/./.")
+        XCTAssertURIString("file:///.///.", hasScheme: "file", hasPath: "/.///.")
+        XCTAssertURIString("file:///a/..", hasScheme: "file", hasPath: "/a/..")
+        XCTAssertURIString("file:///a/b/..", hasScheme: "file", hasPath: "/a/b/..")
+        XCTAssertURIString("file:///a/b//..", hasScheme: "file", hasPath: "/a/b//..")
+        XCTAssertURIString("file:///./a/b/..", hasScheme: "file", hasPath: "/./a/b/..")
+        XCTAssertURIString("file:///a/./b/..", hasScheme: "file", hasPath: "/a/./b/..")
+        XCTAssertURIString("file:///a/b/./..", hasScheme: "file", hasPath: "/a/b/./..")
+        XCTAssertURIString("file:///a///b//..", hasScheme: "file", hasPath: "/a///b//..")
+        XCTAssertURIString("file:///a/b/../..", hasScheme: "file", hasPath: "/a/b/../..")
+        XCTAssertURIString("file:///a/b/c/../..", hasScheme: "file", hasPath: "/a/b/c/../..")
+        XCTAssertURIString("file:///a/../b/..", hasScheme: "file", hasPath: "/a/../b/..")
+        XCTAssertURIString("file:///a/../b/../c", hasScheme: "file", hasPath: "/a/../b/../c")
+        XCTAssertURIString("file:///a/../b/../c", hasScheme: "file", hasPath: "/a/../b/../c")
+        XCTAssertURIString("ftp://ftp.gnu.org/", hasScheme: "ftp", hasHost: "ftp.gnu.org", hasPath: "/")
+        XCTAssertURIString("ftp://ftp.gnu.org/pub/gnu", hasScheme: "ftp", hasHost: "ftp.gnu.org", hasPath: "/pub/gnu")
+        XCTAssertURIString("ftp://luser@ftp.gnu.org/pub/gnu",
+            hasScheme: "ftp", hasUserinfo: "luser", hasHost: "ftp.gnu.org", hasPath: "/pub/gnu"
+        )
+        XCTAssertURIString("ftp://@ftp.gnu.org/pub/gnu", hasScheme: "ftp", hasUserinfo: "", hasHost: "ftp.gnu.org", hasPath: "/pub/gnu")
+        XCTAssertURIString("ftp://luser:password@ftp.gnu.org/pub/gnu",
+            hasScheme: "ftp", hasUserinfo: "luser:password", hasHost: "ftp.gnu.org", hasPath: "/pub/gnu"
+        )
+        XCTAssertURIString("ftp://:password@ftp.gnu.org/pub/gnu",
+            hasScheme: "ftp", hasUserinfo: ":password", hasHost: "ftp.gnu.org", hasPath: "/pub/gnu"
+        )
+        XCTAssertURIString("ftp://ftp.gnu.org:72/pub/gnu", hasScheme: "ftp", hasHost: "ftp.gnu.org", hasPort: 72, hasPath: "/pub/gnu")
+        XCTAssertURIString("ftp://:72/pub/gnu", hasScheme: "ftp", hasHost: "", hasPort: 72, hasPath: "/pub/gnu")
+        XCTAssertURIString("http://localhost/usr/local/bin/", hasScheme: "http", hasHost: "localhost", hasPath: "/usr/local/bin/")
+        XCTAssertURIString("http://localhost/", hasScheme: "http", hasHost: "localhost", hasPath: "/")
+        XCTAssertURIString("http://www.apple.com/", hasScheme: "http", hasHost: "www.apple.com", hasPath: "/")
+        XCTAssertURIString("http://www.apple.com/dir", hasScheme: "http", hasHost: "www.apple.com", hasPath: "/dir")
+        XCTAssertURIString("http://www.apple.com/dir/", hasScheme: "http", hasHost: "www.apple.com", hasPath: "/dir/")
+        XCTAssertURIString("http://darin:nothin@www.apple.com:42/dir/",
+            hasScheme: "http", hasUserinfo: "darin:nothin", hasHost: "www.apple.com", hasPort: 42, hasPath: "/dir/"
+        )
+        XCTAssertURIString("http:/", hasScheme: "http", hasHost: nil, hasPath: "/")
+        XCTAssertURIString("http://www.apple.com/query?email=darin@apple.com",
+            hasScheme: "http", hasHost: "www.apple.com", hasPath: "/query", hasQuery: "email=darin@apple.com"
+        )
+        XCTAssertURIString("HTTP://WWW.ZOO.COM/", hasScheme: "HTTP", hasHost: "WWW.ZOO.COM", hasPath: "/")
+        XCTAssertURIString("HTTP://WWW.ZOO.COM/ED", hasScheme: "HTTP", hasHost: "WWW.ZOO.COM", hasPath: "/ED")
+        XCTAssertURIString("http://groups.google.com/groups?as_uauthors=joe@blow.com&as_scoring=d&hl=en",
+            hasScheme: "http", hasHost: "groups.google.com", hasPath: "/groups", hasQuery: "as_uauthors=joe@blow.com&as_scoring=d&hl=en"
+        )
+        XCTAssertURIString("http://my.site.com/some/page.html#fragment",
+            hasScheme: "http", hasHost: "my.site.com", hasPath: "/some/page.html", hasFragment: "fragment"
+        )
+        XCTAssertURIString("scheme://user:pass@host:1/path/path2/file.html;params?query#fragment",
+            hasScheme: "scheme", hasUserinfo: "user:pass", hasHost: "host", hasPort: 1, hasPath: "/path/path2/file.html;params",
+            hasQuery: "query", hasFragment: "fragment"
+        )
+        XCTAssertURIString("http://test.com/a%20space", hasScheme: "http", hasHost: "test.com", hasPath: "/a space")
+        XCTAssertURIString("http://test.com/aBrace%7B", hasScheme: "http", hasHost: "test.com", hasPath: "/aBrace{")
+        XCTAssertURIString("http://test.com/aJ%4a", hasScheme: "http", hasHost: "test.com", hasPath: "/aJJ")
+        XCTAssertURIString("file:///%3F", hasScheme: "file", hasPath: "/?")
+        XCTAssertURIString("file:///%78", hasScheme: "file", hasPath: "/x")
+        XCTAssertURIString("file:///?", hasScheme: "file", hasPath: "/", hasQuery: "")
+        XCTAssertURIString("file:///&", hasScheme: "file", hasPath: "/&")
+        XCTAssertURIString("file:///x", hasScheme: "file", hasPath: "/x")
+        XCTAssertURIString("http:///%3F", hasScheme: "http", hasPath: "/?")
+        XCTAssertURIString("http:///%78", hasScheme: "http", hasPath: "/x")
+        XCTAssertURIString("http:///?", hasScheme: "http", hasPath: "/", hasQuery: "")
+        XCTAssertURIString("http:///&", hasScheme: "http", hasPath: "/&")
+        XCTAssertURIString("http:///x", hasScheme: "http", hasPath: "/x")
+        XCTAssertURIString("glorb:///%3F", hasScheme: "glorb", hasPath: "/?")
+        XCTAssertURIString("glorb:///%78", hasScheme: "glorb", hasPath: "/x")
+        XCTAssertURIString("glorb:///?", hasScheme: "glorb", hasPath: "/", hasQuery: "")
+        XCTAssertURIString("glorb:///&", hasScheme: "glorb", hasPath: "/&")
+        XCTAssertURIString("glorb:///x", hasScheme: "glorb", hasPath: "/x")
+        XCTAssertURIString("uahsfcncvuhrtgvnahr", hasHost: nil, hasPath: "uahsfcncvuhrtgvnahr")
+        XCTAssertURIString("http://[fe80::20a:27ff:feae:8b9e]/", hasScheme: "http", hasHost: "[fe80::20a:27ff:feae:8b9e]", hasPath: "/")
+        XCTAssertURIString("http://[fe80::20a:27ff:feae:8b9e%25en0]/", hasScheme: "http", hasHost: "[fe80::20a:27ff:feae:8b9e%en0]", hasPath: "/")
+        XCTAssertURIString("http://host.com/foo/bar/../index.html", hasScheme: "http", hasHost: "host.com", hasPath: "/foo/bar/../index.html")
+        XCTAssertURIString("http://host.com/foo/bar/./index.html", hasScheme: "http", hasHost: "host.com", hasPath: "/foo/bar/./index.html")
+        XCTAssertURIString("http:/cgi-bin/Count.cgi?ft=0", hasScheme: "http", hasHost: nil, hasPath: "/cgi-bin/Count.cgi", hasQuery: "ft=0")
+        XCTAssertURIString("file://///", hasScheme: "file", hasPath: "///")
+        XCTAssertURIString("file:/Volumes", hasScheme: "file", hasHost: nil, hasPath: "/Volumes")
+        XCTAssertURIString("/Volumes", hasHost: nil, hasPath: "/Volumes")
+        XCTAssertURIString(".", hasHost: nil, hasPath: ".")
+        XCTAssertURIString("./a", hasHost: nil, hasPath: "./a")
+        XCTAssertURIString("../a", hasHost: nil, hasPath: "../a")
+        XCTAssertURIString("../../a", hasHost: nil, hasPath: "../../a")
+        XCTAssertURIString("/", hasHost: nil, hasPath: "/")
+        XCTAssertURIString("http://a/b/c/./g", hasScheme: "http", hasHost: "a", hasPath: "/b/c/./g")
+        XCTAssertURIString("http://a/b/c/.", hasScheme: "http", hasHost: "a", hasPath: "/b/c/.")
+        XCTAssertURIString("http://a/b/c/./", hasScheme: "http", hasHost: "a", hasPath: "/b/c/./")
+        XCTAssertURIString("http://a/b/c/..", hasScheme: "http", hasHost: "a", hasPath: "/b/c/..")
+        XCTAssertURIString("http://a/b/c/../", hasScheme: "http", hasHost: "a", hasPath: "/b/c/../")
+        XCTAssertURIString("http://a/b/c/../g", hasScheme: "http", hasHost: "a", hasPath: "/b/c/../g")
+        XCTAssertURIString("http://a/b/c/../..", hasScheme: "http", hasHost: "a", hasPath: "/b/c/../..")
+        XCTAssertURIString("http://a/b/c/../../", hasScheme: "http", hasHost: "a", hasPath: "/b/c/../../")
+        XCTAssertURIString("http://a/b/c/../../g", hasScheme: "http", hasHost: "a", hasPath: "/b/c/../../g")
+        XCTAssertURIString("http://a/b/c/../../../g", hasScheme: "http", hasHost: "a", hasPath: "/b/c/../../../g")
+        XCTAssertURIString("http://a/b/c/../../../../g", hasScheme: "http", hasHost: "a", hasPath: "/b/c/../../../../g")
+        XCTAssertURIString("http://a/b/c/./g", hasScheme: "http", hasHost: "a", hasPath: "/b/c/./g")
+        XCTAssertURIString("http://a/b/c/../g", hasScheme: "http", hasHost: "a", hasPath: "/b/c/../g")
+        XCTAssertURIString("http://a/b/c/g.", hasScheme: "http", hasHost: "a", hasPath: "/b/c/g.")
+        XCTAssertURIString("http://a/b/c/.g", hasScheme: "http", hasHost: "a", hasPath: "/b/c/.g")
+        XCTAssertURIString("http://a/b/c/g..", hasScheme: "http", hasHost: "a", hasPath: "/b/c/g..")
+        XCTAssertURIString("http://a/b/c/..g", hasScheme: "http", hasHost: "a", hasPath: "/b/c/..g")
+        XCTAssertURIString("http://a/b/c/./../g", hasScheme: "http", hasHost: "a", hasPath: "/b/c/./../g")
+        XCTAssertURIString("http://a/b/c/./g/.", hasScheme: "http", hasHost: "a", hasPath: "/b/c/./g/.")
+        XCTAssertURIString("http://a/b/c/g/./h", hasScheme: "http", hasHost: "a", hasPath: "/b/c/g/./h")
+        XCTAssertURIString("http://a/b/c/g/../h", hasScheme: "http", hasHost: "a", hasPath: "/b/c/g/../h")
+        XCTAssertURIString("http://a/b/c/g;x=1/./y", hasScheme: "http", hasHost: "a", hasPath: "/b/c/g;x=1/./y")
+        XCTAssertURIString("http://a/b/c/g;x=1/../y", hasScheme: "http", hasHost: "a", hasPath: "/b/c/g;x=1/../y")
+        XCTAssertURIString("http://a/b/c/g?y/./x", hasScheme: "http", hasHost: "a", hasPath: "/b/c/g", hasQuery: "y/./x")
+        XCTAssertURIString("http://a/b/c/g?y/../x", hasScheme: "http", hasHost: "a", hasPath: "/b/c/g", hasQuery: "y/../x")
+        XCTAssertURIString("http://a/b/c/g#s/./x", hasScheme: "http", hasHost: "a", hasPath: "/b/c/g", hasFragment: "s/./x")
+        XCTAssertURIString("http://a/b/c/g#s/../x", hasScheme: "http", hasHost: "a", hasPath: "/b/c/g", hasFragment: "s/../x")
+        XCTAssertURIString("http://a/../../x", hasScheme: "http", hasHost: "a", hasPath: "/../../x")
+        XCTAssertURIString("http://a/..///../x", hasScheme: "http", hasHost: "a", hasPath: "/..///../x")
+    }
+}
diff --git a/Tests/VaporTests/ValidationTests.swift b/Tests/VaporTests/ValidationTests.swift
index b0d09b7fe8..3491cf0f35 100644
--- a/Tests/VaporTests/ValidationTests.swift
+++ b/Tests/VaporTests/ValidationTests.swift
@@ -159,14 +159,16 @@ class ValidationTests: XCTestCase {
             "email": "ß@tanner.xyz"
         }
         """
         XCTAssertNoThrow(try Email.validate(json: valid))
         
-        let validURL: URI = "https://tanner.xyz/email?email=ß@tanner.xyz"
+        // N.B.: These two checks previously asserted against a URI containing the unencoded `ß` character.
+        // Such a URI is semantically incorrect (per RFC 3986) and should have been considered a bug.
+        let validURL: URI = "https://tanner.xyz/email?email=%C3%9F@tanner.xyz" // ß
         XCTAssertNoThrow(try Email.validate(query: validURL))
         
-        let validURL2: URI = "https://tanner.xyz/email?email=me@ßanner.xyz"
+        let validURL2: URI = "https://tanner.xyz/email?email=me@%C3%9Fanner.xyz"
         XCTAssertNoThrow(try Email.validate(query: validURL2))
         
         let invalidUser = """
         {
             "email": "me@tanner@.xyz",

Vulnerable code:         .target(name: "CVaporURLParser"),
            .target(name: "CVaporURLParser"),
        .target(name: "CVaporURLParser"),

                .target(name: "CVaporURLParser"),
            swiftSettings: [.enableExperimentalFeature("StrictConcurrency=complete")]
            swiftSettings: [.enableExperimentalFeature("StrictConcurrency=complete")]
/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */
#ifndef urlparser_h
#define urlparser_h
#include <stdint.h>
#include <stddef.h>

enum vapor_urlparser_fields
{ UF_SCHEMA           = 0
    , UF_HOST             = 1
    , UF_PORT             = 2
    , UF_PATH             = 3
    , UF_QUERY            = 4
    , UF_FRAGMENT         = 5
    , UF_USERINFO         = 6
    , UF_MAX              = 7
};

struct vapor_urlparser_field_data {
    uint16_t off;               /* Offset into buffer in which field starts */
    uint16_t len;               /* Length of run in buffer */
};

/* Result structure for urlparser_parse_url().
 *
 * Callers should index into field_data[] with UF_* values iff field_set
 * has the relevant (1 << UF_*) bit set. As a courtesy to clients (and
 * because we probably have padding left over), we convert any port to
 * a uint16_t.
 */
struct vapor_urlparser_url {
    uint16_t field_set;           /* Bitmask of (1 << UF_*) values */
    uint16_t port;                /* Converted UF_PORT string */
    struct vapor_urlparser_field_data field_data[UF_MAX];
};

/* Parse a URL; return nonzero on failure */
int vapor_urlparser_parse(const char *buf, size_t buflen,
                          int is_connect,
                          struct vapor_urlparser_url *u);
#endif
/* Copyright Joyent, Inc. and other Node contributors.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */
#include "urlparser.h"
#include <assert.h>
#include <stddef.h>
#include <ctype.h>
#include <string.h>
#include <limits.h>

#ifndef BIT_AT
# define BIT_AT(a, i)                                                \
(!!((unsigned int) (a)[(unsigned int) (i) >> 3] &                  \
(1 << ((unsigned int) (i) & 7))))
#endif

/* Tokens as defined by rfc 2616. Also lowercases them.
 *        token       = 1*<any CHAR except CTLs or separators>
 *     separators     = "(" | ")" | "<" | ">" | "@"
 *                    | "," | ";" | ":" | "\" | <">
 *                    | "/" | "[" | "]" | "?" | "="
 *                    | "{" | "}" | SP | HT
 */
static const char tokens[256] = {
    /*   0 nul    1 soh    2 stx    3 etx    4 eot    5 enq    6 ack    7 bel  */
    0,       0,       0,       0,       0,       0,       0,       0,
    /*   8 bs     9 ht    10 nl    11 vt    12 np    13 cr    14 so    15 si   */
    0,       0,       0,       0,       0,       0,       0,       0,
    /*  16 dle   17 dc1   18 dc2   19 dc3   20 dc4   21 nak   22 syn   23 etb */
    0,       0,       0,       0,       0,       0,       0,       0,
    /*  24 can   25 em    26 sub   27 esc   28 fs    29 gs    30 rs    31 us  */
    0,       0,       0,       0,       0,       0,       0,       0,
    /*  32 sp    33  !    34  "    35  #    36  $    37  %    38  &    39  '  */
    ' ',     '!',      0,      '#',     '$',     '%',     '&',    '\'',
    /*  40  (    41  )    42  *    43  +    44  ,    45  -    46  .    47  /  */
    0,       0,      '*',     '+',      0,      '-',     '.',      0,
    /*  48  0    49  1    50  2    51  3    52  4    53  5    54  6    55  7  */
    '0',     '1',     '2',     '3',     '4',     '5',     '6',     '7',
    /*  56  8    57  9    58  :    59  ;    60  <    61  =    62  >    63  ?  */
    '8',     '9',      0,       0,       0,       0,       0,       0,
    /*  64  @    65  A    66  B    67  C    68  D    69  E    70  F    71  G  */
    0,      'a',     'b',     'c',     'd',     'e',     'f',     'g',
    /*  72  H    73  I    74  J    75  K    76  L    77  M    78  N    79  O  */
    'h',     'i',     'j',     'k',     'l',     'm',     'n',     'o',
    /*  80  P    81  Q    82  R    83  S    84  T    85  U    86  V    87  W  */
    'p',     'q',     'r',     's',     't',     'u',     'v',     'w',
    /*  88  X    89  Y    90  Z    91  [    92  \    93  ]    94  ^    95  _  */
    'x',     'y',     'z',      0,       0,       0,      '^',     '_',
    /*  96  `    97  a    98  b    99  c   100  d   101  e   102  f   103  g  */
    '`',     'a',     'b',     'c',     'd',     'e',     'f',     'g',
    /* 104  h   105  i   106  j   107  k   108  l   109  m   110  n   111  o  */
    'h',     'i',     'j',     'k',     'l',     'm',     'n',     'o',
    /* 112  p   113  q   114  r   115  s   116  t   117  u   118  v   119  w  */
    'p',     'q',     'r',     's',     't',     'u',     'v',     'w',
    /* 120  x   121  y   122  z   123  {   124  |   125  }   126  ~   127 del */
    'x',     'y',     'z',      0,      '|',      0,      '~',       0 };


static const int8_t unhex[256] =
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
    ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
    ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
    , 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1
    ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
    ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
    ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
    ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
};


#if URLPARSER_STRICT
# define T(v) 0
#else
# define T(v) v
#endif


static const uint8_t normal_url_char[32] = {
    /*   0 nul    1 soh    2 stx    3 etx    4 eot    5 enq    6 ack    7 bel  */
    0    |   0    |   0    |   0    |   0    |   0    |   0    |   0,
    /*   8 bs     9 ht    10 nl    11 vt    12 np    13 cr    14 so    15 si   */
    0    | T(2)   |   0    |   0    | T(16)  |   0    |   0    |   0,
    /*  16 dle   17 dc1   18 dc2   19 dc3   20 dc4   21 nak   22 syn   23 etb */
    0    |   0    |   0    |   0    |   0    |   0    |   0    |   0,
    /*  24 can   25 em    26 sub   27 esc   28 fs    29 gs    30 rs    31 us  */
    0    |   0    |   0    |   0    |   0    |   0    |   0    |   0,
    /*  32 sp    33  !    34  "    35  #    36  $    37  %    38  &    39  '  */
    0    |   2    |   4    |   0    |   16   |   32   |   64   |  128,
    /*  40  (    41  )    42  *    43  +    44  ,    45  -    46  .    47  /  */
    1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
    /*  48  0    49  1    50  2    51  3    52  4    53  5    54  6    55  7  */
    1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
    /*  56  8    57  9    58  :    59  ;    60  <    61  =    62  >    63  ?  */
    1    |   2    |   4    |   8    |   16   |   32   |   64   |   0,
    /*  64  @    65  A    66  B    67  C    68  D    69  E    70  F    71  G  */
    1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
    /*  72  H    73  I    74  J    75  K    76  L    77  M    78  N    79  O  */
    1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
    /*  80  P    81  Q    82  R    83  S    84  T    85  U    86  V    87  W  */
    1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
    /*  88  X    89  Y    90  Z    91  [    92  \    93  ]    94  ^    95  _  */
    1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
    /*  96  `    97  a    98  b    99  c   100  d   101  e   102  f   103  g  */
    1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
    /* 104  h   105  i   106  j   107  k   108  l   109  m   110  n   111  o  */
    1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
    /* 112  p   113  q   114  r   115  s   116  t   117  u   118  v   119  w  */
    1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
    /* 120  x   121  y   122  z   123  {   124  |   125  }   126  ~   127 del */
    1    |   2    |   4    |   8    |   16   |   32   |   64   |   0, };

#undef T

enum state
{ s_dead = 1 /* important that this is > 0 */

    , s_start_req_or_res
    , s_res_or_resp_H
    , s_start_res
    , s_res_H
    , s_res_HT
    , s_res_HTT
    , s_res_HTTP
    , s_res_http_major
    , s_res_http_dot
    , s_res_http_minor
    , s_res_http_end
    , s_res_first_status_code
    , s_res_status_code
    , s_res_status_start
    , s_res_status
    , s_res_line_almost_done

    , s_start_req

    , s_req_method
    , s_req_spaces_before_url
    , s_req_schema
    , s_req_schema_slash
    , s_req_schema_slash_slash
    , s_req_server_start
    , s_req_server
    , s_req_server_with_at
    , s_req_path
    , s_req_query_string_start
    , s_req_query_string
    , s_req_fragment_start
    , s_req_fragment
    , s_req_http_start
    , s_req_http_H
    , s_req_http_HT
    , s_req_http_HTT
    , s_req_http_HTTP
    , s_req_http_I
    , s_req_http_IC
    , s_req_http_major
    , s_req_http_dot
    , s_req_http_minor
    , s_req_http_end
    , s_req_line_almost_done

    , s_header_field_start
    , s_header_field
    , s_header_value_discard_ws
    , s_header_value_discard_ws_almost_done
    , s_header_value_discard_lws
    , s_header_value_start
    , s_header_value
    , s_header_value_lws

    , s_header_almost_done

    , s_chunk_size_start
    , s_chunk_size
    , s_chunk_parameters
    , s_chunk_size_almost_done

    , s_headers_almost_done
    , s_headers_done

    /* Important: 's_headers_done' must be the last 'header' state. All
     * states beyond this must be 'body' states. It is used for overflow
     * checking. See the PARSING_HEADER() macro.
     */

    , s_chunk_data
    , s_chunk_data_almost_done
    , s_chunk_data_done

    , s_body_identity
    , s_body_identity_eof

    , s_message_done
};

enum http_host_state
{
    s_http_host_dead = 1
    , s_http_userinfo_start
    , s_http_userinfo
    , s_http_host_start
    , s_http_host_v6_start
    , s_http_host
    , s_http_host_v6
    , s_http_host_v6_end
    , s_http_host_v6_zone_start
    , s_http_host_v6_zone
    , s_http_host_port_start
    , s_http_host_port
};

/* Macros for character classes; depends on strict-mode  */
#define CR                  '\r'
#define LF                  '\n'
#define LOWER(c)            (unsigned char)(c | 0x20)
#define IS_ALPHA(c)         (LOWER(c) >= 'a' && LOWER(c) <= 'z')
#define IS_NUM(c)           ((c) >= '0' && (c) <= '9')
#define IS_ALPHANUM(c)      (IS_ALPHA(c) || IS_NUM(c))
#define IS_HEX(c)           (IS_NUM(c) || (LOWER(c) >= 'a' && LOWER(c) <= 'f'))
#define IS_MARK(c)          ((c) == '-' || (c) == '_' || (c) == '.' || \
(c) == '!' || (c) == '~' || (c) == '*' || (c) == '\'' || (c) == '(' || \
(c) == ')')
#define IS_USERINFO_CHAR(c) (IS_ALPHANUM(c) || IS_MARK(c) || (c) == '%' || \
(c) == ';' || (c) == ':' || (c) == '&' || (c) == '=' || (c) == '+' || \
(c) == '$' || (c) == ',')

#define STRICT_TOKEN(c)     ((c == ' ') ? 0 : tokens[(unsigned char)c])

#if URLPARSER_STRICT
#define TOKEN(c)            STRICT_TOKEN(c)
#define IS_URL_CHAR(c)      (BIT_AT(normal_url_char, (unsigned char)c))
#define IS_HOST_CHAR(c)     (IS_ALPHANUM(c) || (c) == '.' || (c) == '-')
#else
#define TOKEN(c)            tokens[(unsigned char)c]
#define IS_URL_CHAR(c)                                                         \
(BIT_AT(normal_url_char, (unsigned char)c) || ((c) & 0x80))
#define IS_HOST_CHAR(c)                                                        \
(IS_ALPHANUM(c) || (c) == '.' || (c) == '-' || (c) == '_')
#endif

/* Our URL parser.
 *
 * This is designed to be shared by urlparser_execute() for URL validation,
 * hence it has a state transition + byte-for-byte interface. In addition, it
 * is meant to be embedded in urlparser_parse_url(), which does the dirty
 * work of turning state transitions URL components for its API.
 *
 * This function should only be invoked with non-space characters. It is
 * assumed that the caller cares about (and can detect) the transition between
 * URL and non-URL states by looking for these.
 */
static enum state
parse_url_char(enum state s, const char ch)
{
    if (ch == ' ' || ch == '\r' || ch == '\n') {
        return s_dead;
    }

#if URLPARSER_STRICT
    if (ch == '\t' || ch == '\f') {
        return s_dead;
    }
#endif

    switch (s) {
        case s_req_spaces_before_url:
        /* Proxied requests are followed by scheme of an absolute URI (alpha).
         * All methods except CONNECT are followed by '/' or '*'.
         */

        if (ch == '/' || ch == '*') {
            return s_req_path;
        }

        if (IS_ALPHA(ch)) {
            return s_req_schema;
        }

        break;

        case s_req_schema:
        if (IS_ALPHA(ch)) {
            return s;
        }

        if (ch == ':') {
            return s_req_schema_slash;
        }

        break;

        case s_req_schema_slash:
        if (ch == '/') {
            return s_req_schema_slash_slash;
        }

        break;

        case s_req_schema_slash_slash:
        if (ch == '/') {
            return s_req_server_start;
        }

        break;

        case s_req_server_with_at:
        if (ch == '@') {
            return s_dead;
        }

        /* fall through */
        case s_req_server_start:
        case s_req_server:
        if (ch == '/') {
            return s_req_path;
        }

        if (ch == '?') {
            return s_req_query_string_start;
        }

        if (ch == '@') {
            return s_req_server_with_at;
        }

        if (IS_USERINFO_CHAR(ch) || ch == '[' || ch == ']') {
            return s_req_server;
        }

        break;

        case s_req_path:
        if (IS_URL_CHAR(ch)) {
            return s;
        }

        switch (ch) {
            case '?':
            return s_req_query_string_start;

            case '#':
            return s_req_fragment_start;
        }

        break;

        case s_req_query_string_start:
        case s_req_query_string:
        if (IS_URL_CHAR(ch)) {
            return s_req_query_string;
        }

        switch (ch) {
            case '?':
            /* allow extra '?' in query string */
            return s_req_query_string;

            case '#':
            return s_req_fragment_start;
        }

        break;

        case s_req_fragment_start:
        if (IS_URL_CHAR(ch)) {
            return s_req_fragment;
        }

        switch (ch) {
            case '?':
            return s_req_fragment;

            case '#':
            return s;
        }

        break;

        case s_req_fragment:
        if (IS_URL_CHAR(ch)) {
            return s;
        }

        switch (ch) {
            case '?':
            case '#':
            return s;
        }

        break;

        default:
        break;
    }

    /* We should never fall out of the switch above unless there's an error */
    return s_dead;
}

static enum http_host_state
http_parse_host_char(enum http_host_state s, const char ch) {
    switch(s) {
        case s_http_userinfo:
        case s_http_userinfo_start:
        if (ch == '@') {
            return s_http_host_start;
        }

        if (IS_USERINFO_CHAR(ch)) {
            return s_http_userinfo;
        }
        break;

        case s_http_host_start:
        if (ch == '[') {
            return s_http_host_v6_start;
        }

        if (IS_HOST_CHAR(ch)) {
            return s_http_host;
        }

        break;

        case s_http_host:
        if (IS_HOST_CHAR(ch)) {
            return s_http_host;
        }

        /* fall through */
        case s_http_host_v6_end:
        if (ch == ':') {
            return s_http_host_port_start;
        }

        break;

        case s_http_host_v6:
        if (ch == ']') {
            return s_http_host_v6_end;
        }

        /* fall through */
        case s_http_host_v6_start:
        if (IS_HEX(ch) || ch == ':' || ch == '.') {
            return s_http_host_v6;
        }

        if (s == s_http_host_v6 && ch == '%') {
            return s_http_host_v6_zone_start;
        }
        break;

        case s_http_host_v6_zone:
        if (ch == ']') {
            return s_http_host_v6_end;
        }

        /* fall through */
        case s_http_host_v6_zone_start:
        /* RFC 6874 Zone ID consists of 1*( unreserved / pct-encoded) */
        if (IS_ALPHANUM(ch) || ch == '%' || ch == '.' || ch == '-' || ch == '_' ||
            ch == '~') {
            return s_http_host_v6_zone;
        }
        break;

        case s_http_host_port:
        case s_http_host_port_start:
        if (IS_NUM(ch)) {
            return s_http_host_port;
        }

        break;

        default:
        break;
    }
    return s_http_host_dead;
}

static int
http_parse_host(const char * buf, struct vapor_urlparser_url *u, int found_at) {
    enum http_host_state s;

    const char *p;
    size_t buflen = u->field_data[UF_HOST].off + u->field_data[UF_HOST].len;

    assert(u->field_set & (1 << UF_HOST));

    u->field_data[UF_HOST].len = 0;

    s = found_at ? s_http_userinfo_start : s_http_host_start;

    for (p = buf + u->field_data[UF_HOST].off; p < buf + buflen; p++) {
        enum http_host_state new_s = http_parse_host_char(s, *p);

        if (new_s == s_http_host_dead) {
            return 1;
        }

        switch(new_s) {
            case s_http_host:
            if (s != s_http_host) {
                u->field_data[UF_HOST].off = (uint16_t)(p - buf);
            }
            u->field_data[UF_HOST].len++;
            break;

            case s_http_host_v6:
            if (s != s_http_host_v6) {
                u->field_data[UF_HOST].off = (uint16_t)(p - buf);
            }
            u->field_data[UF_HOST].len++;
            break;

            case s_http_host_v6_zone_start:
            case s_http_host_v6_zone:
            u->field_data[UF_HOST].len++;
            break;

            case s_http_host_port:
            if (s != s_http_host_port) {
                u->field_data[UF_PORT].off = (uint16_t)(p - buf);
                u->field_data[UF_PORT].len = 0;
                u->field_set |= (1 << UF_PORT);
            }
            u->field_data[UF_PORT].len++;
            break;

            case s_http_userinfo:
            if (s != s_http_userinfo) {
                u->field_data[UF_USERINFO].off = (uint16_t)(p - buf);
                u->field_data[UF_USERINFO].len = 0;
                u->field_set |= (1 << UF_USERINFO);
            }
            u->field_data[UF_USERINFO].len++;
            break;

            default:
            break;
        }
        s = new_s;
    }

    /* Make sure we don't end somewhere unexpected */
    switch (s) {
        case s_http_host_start:
        case s_http_host_v6_start:
        case s_http_host_v6:
        case s_http_host_v6_zone_start:
        case s_http_host_v6_zone:
        case s_http_host_port_start:
        case s_http_userinfo:
        case s_http_userinfo_start:
        return 1;
        default:
        break;
    }

    return 0;
}

void
urlparser_url_init(struct vapor_urlparser_url *u) {
    memset(u, 0, sizeof(*u));
}

int
vapor_urlparser_parse(const char *buf, size_t buflen, int is_connect,
                      struct vapor_urlparser_url *u)
{
    enum state s;
    const char *p;
    enum vapor_urlparser_fields uf, old_uf;
    int found_at = 0;

    if (buflen == 0) {
        return 1;
    }

    u->port = u->field_set = 0;
    s = is_connect ? s_req_server_start : s_req_spaces_before_url;
    old_uf = UF_MAX;

    for (p = buf; p < buf + buflen; p++) {
        s = parse_url_char(s, *p);

        /* Figure out the next field that we're operating on */
        switch (s) {
            case s_dead:
            return 1;

            /* Skip delimeters */
            case s_req_schema_slash:
            case s_req_schema_slash_slash:
            case s_req_server_start:
            case s_req_query_string_start:
            case s_req_fragment_start:
            continue;

            case s_req_schema:
            uf = UF_SCHEMA;
            break;

            case s_req_server_with_at:
            found_at = 1;

            /* fall through */
            case s_req_server:
            uf = UF_HOST;
            break;

            case s_req_path:
            uf = UF_PATH;
            break;

            case s_req_query_string:
            uf = UF_QUERY;
            break;

            case s_req_fragment:
            uf = UF_FRAGMENT;
            break;

            default:
            assert(!"Unexpected state");
            return 1;
        }

        /* Nothing's changed; soldier on */
        if (uf == old_uf) {
            u->field_data[uf].len++;
            continue;
        }

        u->field_data[uf].off = (uint16_t)(p - buf);
        u->field_data[uf].len = 1;

        u->field_set |= (1 << uf);
        old_uf = uf;
    }

    /* host must be present if there is a schema */
    /* parsing http:///toto will fail */
    if ((u->field_set & (1 << UF_SCHEMA)) &&
        (u->field_set & (1 << UF_HOST)) == 0) {
        return 1;
    }

    if (u->field_set & (1 << UF_HOST)) {
        if (http_parse_host(buf, u, found_at) != 0) {
            return 1;
        }
    }

    /* CONNECT requests can only contain "hostname:port" */
    if (is_connect && u->field_set != ((1 << UF_HOST)|(1 << UF_PORT))) {
        return 1;
    }

    if (u->field_set & (1 << UF_PORT)) {
        uint16_t off;
        uint16_t len;
        const char* p;
        const char* end;
        unsigned long v;

        off = u->field_data[UF_PORT].off;
        len = u->field_data[UF_PORT].len;
        end = buf + off + len;

        /* NOTE: The characters are already validated and are in the [0-9] range */
        assert(off + len <= buflen && "Port number overflow");
        v = 0;
        for (p = buf + off; p < end; p++) {
            v *= 10;
            v += *p - '0';

            /* Ports have a max value of 2^16 */
            if (v > 0xffff) {
                return 1;
            }
        }

        u->port = (uint16_t) v;
    }

    return 0;
}
import CVaporURLParser
    /// A URI's scheme.
    public struct Scheme: Sendable, ExpressibleByStringInterpolation {
        /// HTTP
        public static let http: Self = "http"
        
        /// HTTPS
        public static let https: Self = "https"
        
        /// HTTP over Unix Domain Socket Paths. The socket path should be encoded as the host in the URI, making sure to encode any special characters:
        /// ```
        /// host.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
        /// ```
        /// Do note that URI's initializer will encode the host in this way if you use `init(scheme:host:port:path:query:fragment:)`.
        public static let httpUnixDomainSocket: Self = "http+unix"
        
        /// HTTPS over Unix Domain Socket Paths. The socket path should be encoded as the host in the URI, making sure to encode any special characters:
        /// ```
        /// host.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
        /// ```
        /// Do note that URI's initializer will encode the host in this way if you use `init(scheme:host:port:path:query:fragment:)`.
        public static let httpsUnixDomainSocket: Self = "https+unix"
        
        public let value: String?
        
        public init(stringLiteral value: String) {
            self.value = value
        }
        
        public init(_ value: String? = nil) {
            self.value = value
        }
    }
    public var string: String

        self.string = string
        return self.string
        scheme: Scheme = Scheme(),
        var string = ""
        if let scheme = scheme.value {
            string += scheme + "://"
        }
        if let host = host?.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) {
            string += host
        }
        if let port = port {
            string += ":" + port.description
        }
        if path.hasPrefix("/") {
            string += path
            string += "/" + path
        }
        if let query = query {
            string += "?" + query
        if let fragment = fragment {
            string += "#" + fragment
        }
        self.string = string
    private enum Component {
        case scheme, host, port, path, query, fragment, userinfo
    }

        get {
            return self.parse(.scheme)
        }
            self = .init(
                scheme: newValue,
                host: self.host,
                port: self.port,
                path: self.path,
                query: self.query,
                fragment: self.fragment
            )
        get {
            return self.parse(.host)
        }
        set {
            self = .init(
                scheme: self.scheme,
                host: newValue,
                port: self.port,
                path: self.path,
                query: self.query,
                fragment: self.fragment
            )
        }
        get {
            return self.parse(.port).flatMap(Int.init)
        }
        set {
            self = .init(
                scheme: self.scheme,
                host: self.host,
                port: newValue,
                path: self.path,
                query: self.query,
                fragment: self.fragment
            )
        }
        get {
            return self.parse(.path) ?? ""
        }
        set {
            self = .init(
                scheme: self.scheme,
                host: self.host,
                port: self.port,
                path: newValue,
                query: self.query,
                fragment: self.fragment
            )
        }
        get {
            return self.parse(.query)
        }
        set {
            self = .init(
                scheme: self.scheme,
                host: self.host,
                port: self.port,
                path: self.path,
                query: newValue,
                fragment: self.fragment
            )
        }
        get {
            return self.parse(.fragment)
        }
        set {
            self = .init(
                scheme: self.scheme,
                host: self.host,
                port: self.port,
                path: self.path,
                query: self.query,
                fragment: newValue
            )
        }
    private func parse(_ component: Component) -> String? {
        var url = vapor_urlparser_url()
        vapor_urlparser_parse(self.string, self.string.count, 0, &url)
        let data: vapor_urlparser_field_data
        switch component {
        case .scheme:
            data = url.field_data.0
        case .host:
            data = url.field_data.1
        case .port:
            data = url.field_data.2
        case .path:
            data = url.field_data.3
        case .query:
            data = url.field_data.4
        case .fragment:
            data = url.field_data.5
        case .userinfo:
            data = url.field_data.6
        }
        if data.len == 0 {
            return nil
        }
        let start = self.string.index(self.string.startIndex, offsetBy: numericCast(data.off))
        let end = self.string.index(start, offsetBy: numericCast(data.len))
        return String(self.string[start..<end])
#if os(Linux)
@preconcurrency import Foundation
#else
import Foundation
    
    func testURI() throws {
        do {
            var uri = URI(string: "http://vapor.codes/foo?bar=baz#qux")
            XCTAssertEqual(uri.scheme, "http")
            XCTAssertEqual(uri.host, "vapor.codes")
            XCTAssertEqual(uri.path, "/foo")
            XCTAssertEqual(uri.query, "bar=baz")
            XCTAssertEqual(uri.fragment, "qux")
            uri.query = "bar=baz&test=1"
            XCTAssertEqual(uri.string, "http://vapor.codes/foo?bar=baz&test=1#qux")
            uri.query = nil
            XCTAssertEqual(uri.string, "http://vapor.codes/foo#qux")
        }
        do {
            let uri = URI(string: "/foo/bar/baz")
            XCTAssertEqual(uri.path, "/foo/bar/baz")
        }
        do {
            let uri = URI(string: "ws://echo.websocket.org/")
            XCTAssertEqual(uri.scheme, "ws")
            XCTAssertEqual(uri.host, "echo.websocket.org")
            XCTAssertEqual(uri.path, "/")
        }
        do {
            let uri = URI(string: "http://foo")
            XCTAssertEqual(uri.scheme, "http")
            XCTAssertEqual(uri.host, "foo")
            XCTAssertEqual(uri.path, "")
        }
        do {
            let uri = URI(string: "foo")
            XCTAssertEqual(uri.scheme, "foo")
            XCTAssertEqual(uri.host, nil)
            XCTAssertEqual(uri.path, "")
        }
        do {
            let uri: URI = "/foo/bar/baz"
            XCTAssertEqual(uri.path, "/foo/bar/baz")
        }
        do {
            let foo = "foo"
            let uri: URI = "/\(foo)/bar/baz"
            XCTAssertEqual(uri.path, "/foo/bar/baz")
        }
        do {
            let uri = URI(scheme: "foo", host: "host", port: 1, path: "test", query: "query", fragment: "fragment")
            XCTAssertEqual(uri.string, "foo://host:1/test?query#fragment")
        }
        do {
            let bar = "bar"
            let uri = URI(scheme: "foo\(bar)", host: "host", port: 1, path: "test", query: "query", fragment: "fragment")
            XCTAssertEqual(uri.string, "foobar://host:1/test?query#fragment")
        }
        do {
            let uri = URI(scheme: "foo", host: "host", port: 1, path: "/test", query: "query", fragment: "fragment")
            XCTAssertEqual(uri.string, "foo://host:1/test?query#fragment")
        }
        do {
            let scheme = "foo"
            let uri = URI(scheme: scheme, host: "host", port: 1, path: "test", query: "query", fragment: "fragment")
            XCTAssertEqual(uri.string, "foo://host:1/test?query#fragment")
        }
        do {
            let scheme: String? = "foo"
            let uri = URI(scheme: scheme, host: "host", port: 1, path: "test", query: "query", fragment: "fragment")
            XCTAssertEqual(uri.string, "foo://host:1/test?query#fragment")
        }
        do {
            let uri = URI(scheme: .http, host: "host", port: 1, path: "test", query: "query", fragment: "fragment")
            XCTAssertEqual(uri.string, "http://host:1/test?query#fragment")
        }
        do {
            let uri = URI(scheme: nil, host: "host", port: 1, path: "test", query: "query", fragment: "fragment")
            XCTAssertEqual(uri.string, "host:1/test?query#fragment")
        }
        do {
            let uri = URI(scheme: URI.Scheme(), host: "host", port: 1, path: "test", query: "query", fragment: "fragment")
            XCTAssertEqual(uri.string, "host:1/test?query#fragment")
        }
        do {
            let uri = URI(host: "host", port: 1, path: "test", query: "query", fragment: "fragment")
            XCTAssertEqual(uri.string, "host:1/test?query#fragment")
        }
        do {
            let uri = URI(scheme: .httpUnixDomainSocket, host: "/path", path: "test", query: "query", fragment: "fragment")
            XCTAssertEqual(uri.string, "http+unix://%2Fpath/test?query#fragment")
        }
        do {
            let uri = URI(scheme: .httpUnixDomainSocket, host: "/path", path: "test", fragment: "fragment")
            XCTAssertEqual(uri.string, "http+unix://%2Fpath/test#fragment")
        }
        do {
            let uri = URI(scheme: .httpUnixDomainSocket, host: "/path", path: "test")
            XCTAssertEqual(uri.string, "http+unix://%2Fpath/test")
        }
        do {
            let uri = URI()
            XCTAssertEqual(uri.string, "/")
        }
    }
    
#if os(Linux)
@preconcurrency import Foundation
#else
import Foundation
        let validURL: URI = "https://tanner.xyz/email?email=ß@tanner.xyz"
        let validURL2: URI = "https://tanner.xyz/email?email=me@ßanner.xyz"
Fixed code:         
            swiftSettings: [
                .enableUpcomingFeature("BareSlashRegexLiterals"),
                .enableExperimentalFeature("StrictConcurrency=complete"),
            ]
            swiftSettings: [
                .enableUpcomingFeature("BareSlashRegexLiterals"),
                .enableExperimentalFeature("StrictConcurrency=complete"),
            ]
#if !canImport(Darwin) && swift(<5.9)
@preconcurrency import Foundation
#else
#endif
#if !canImport(Darwin) && swift(<5.9)
@preconcurrency import Foundation
#else
#endif
#if !canImport(Darwin) && swift(<5.9)
@preconcurrency import Foundation
#else
#endif
#if !canImport(Darwin)
@preconcurrency import struct Foundation.URLComponents
#else
import struct Foundation.URLComponents
#endif
/// A type for constructing and manipulating (most) Uniform Resource Indicators.
///
/// > Warning: This is **NOT** the same as Foundation's [`URL`] type!
///
/// Can be used to both parse strings containing well-formed URIs and to generate such strings from
/// a set of individual URI components.
///
/// Use of this type is (gently, for now) discouraged. Consider using Foundation's [`URL`] and/or
/// [`URLComponents`] types instead. See below for details.
///
/// ## URI is for URLs, not URIs
///
/// Thanks to both backwards compatibility requirements and name collision concerns, this type, despite
/// its name, does not actually represent a generic Uniform Resource Identifier as defined by [RFC 3986].
/// In particular, the underlying implementation is currently based on Foundation's [`URLComponents`] type,
/// whose semantics are inconsistent between different methods; in addition, its behavior has differed
/// drastically between the macOS and Linux implementations for most of its existence, and continues to do
/// so in Swift 5.9. This is not expected to be remedied until the [`swift-foundation`] package reaches a
/// 1.0 release, which as of this writing will not for quite some time yet). In short, instances of `URI`
/// may not always behave as expected according to either the spec or what Foundation does.
///
/// [RFC 3986]: https://datatracker.ietf.org/doc/html/rfc3986
/// [`swift-foundation`]: https://github.com/apple/swift-foundation
/// [`URL`]: https://developer.apple.com/documentation/foundation/url
/// [`URLComponents`]: https://developer.apple.com/documentation/foundation/urlcomponents
    private var components: URLComponents?
        self.components = URL(string: string).flatMap { .init(url: $0, resolvingAgainstBaseURL: true) }
        self.string
        userinfo: String?,
            userinfo: userinfo,

    public init(scheme: String?, host: String? = nil, port: Int? = nil, path: String, query: String? = nil, fragment: String? = nil) {
        self.init(scheme: scheme, userinfo: nil, host: host, port: port, path: path, query: query, fragment: fragment)
    }
    
    public init(scheme: Scheme = .init(), host: String? = nil, port: Int? = nil, path: String, query: String? = nil, fragment: String? = nil) {
        self.init(scheme: scheme, userinfo: nil, host: host, port: port, path: path, query: query, fragment: fragment)
    }
    /// Construct a ``URI`` from various subcomponents.
    ///
    /// Percent encoding is added to each component (if necessary) automatically. There is currently no
    /// way to change this behavior; use `URLComponents` instead if this is insufficient.
    ///
    /// > Warning: For backwards compatibility reasons, if the `path` component is specified in isolation
    /// > (e.g. all other components are `nil`), the path is parsed as if by the ``init(string:)`` initializer.
    ///
    /// > Important: If the `path` does not begin with a `/`, one is prepended. This occurs even if the path
    /// > is specified in isolation (as described above).
        scheme: Scheme = .init(),
        userinfo: String?,
        let path = path.first == "/" ? path : "/\(path)"
        var components: URLComponents!
        
        if scheme.value == nil, userinfo == nil, host == nil, port == nil, query == nil, fragment == nil {
            // If only a path is given, treat it as a string to parse. (This behavior is awful, but must be kept for compatibility.)
            components = URL(string: path).flatMap { .init(url: $0, resolvingAgainstBaseURL: true) }
            // N.B.: We perform percent encoding manually and unconditionally on each non-nil component because the
            // behavior of URLComponents is completely different on Linux than on macOS for inputs which are already
            // fully or partially percent-encoded, as well as inputs which contain invalid characters (especially
            // for the host component). This is the only way to provide consistent behavior (and to avoid various
            // fatalError()s in URLComponents on Linux).
            components = .init()
            components.scheme = scheme.value?.addingPercentEncoding(withAllowedCharacters: .urlSchemeAllowed)
            if let host {
                if let creds = userinfo?.split(separator: ":", maxSplits: 1, omittingEmptySubsequences: false), !creds[0].isEmpty {
                    components.percentEncodedUser = creds[0].addingPercentEncoding(withAllowedCharacters: .urlUserAllowed)
                    if creds.count > 1, !creds[1].isEmpty {
                        components.percentEncodedPassword = creds[1].addingPercentEncoding(withAllowedCharacters: .urlPasswordAllowed)
                    }
                }
                // TODO: Use the `encodedHost` polyfill
                #if canImport(Darwin)
                if #available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) {
                    components.encodedHost = host.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
                } else {
                    components.percentEncodedHost = host.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
                }
                #else
                components.percentEncodedHost = host.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
                #endif
                components.port = port
            } else {
                // TODO: Should this be enforced?
                // assert(userinfo == nil, "Can't provide userinfo without an authority (hostname)")
                // assert(port == nil, "Can't provide userinfo without an authority (hostname)")
            }
            components.percentEncodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlCorrectPathAllowed) ?? "/"
            components.percentEncodedQuery = query?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
            components.percentEncodedFragment = fragment?.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)
        self.components = components
        get { self.components?.scheme }
        set { self.components?.scheme = newValue }
    }
    
    public var userinfo: String? {
        get { self.components?.user.map { "\($0)\(self.components?.password.map { ":\($0)" } ?? "")" } }
            if let userinfoData = newValue?.split(separator: ":", maxSplits: 1, omittingEmptySubsequences: false) {
                self.components?.user = .init(userinfoData[0])
                self.components?.password = userinfoData.count > 1 ? .init(userinfoData[1]) : nil
            } else {
                self.components?.user = nil
            }
        get { self.components?.host }
        set { self.components?.host = newValue }
        get { self.components?.port }
        set { self.components?.port = newValue }
        get { self.components?.path ?? "/" }
        set { self.components?.path = newValue }
        get { self.components?.query }
        set { self.components?.query = newValue }
        get { self.components?.fragment }
        set { self.components?.fragment = newValue }
    public var string: String {
        #if canImport(Darwin)
        self.components?.string ?? ""
        #else
        // On Linux, URLComponents incorrectly treats `;` as *not* allowed in the path component.
        self.components?.string?.replacingOccurrences(of: "%3B", with: ";") ?? ""
        #endif
    }
    
}

extension URI {
    /// A URI scheme, as defined by [RFC 3986 § 3.1] and [RFC 7595].
    ///
    /// [RFC 3986 § 3.1]: https://datatracker.ietf.org/doc/html/rfc3986#section-3.1
    /// [RGC 7595]: https://datatracker.ietf.org/doc/html/rfc7595
    public struct Scheme {
        /// The string representation of the scheme.
        public let value: String?
        
        /// Designated initializer.
        ///
        /// - Parameter value: The string representation for the desired scheme.
        public init(_ value: String? = nil) { self.value = value }

        // MARK: - "Well-known" schemes
        
        /// HyperText Transfer Protocol (HTTP)
        ///
        /// > Registration: [RFC 9110 § 4.2.1](https://www.rfc-editor.org/rfc/rfc9110.html#section-4.2.1)
        public static let http: Self = "http"
        
        /// Secure HyperText Transfer Protocol (HTTPS)
        ///
        /// > Registration: [RFC 9110 § 4.2.2](https://www.rfc-editor.org/rfc/rfc9110.html#section-4.2.2)
        public static let https: Self = "https"
        
        /// HyperText Transfer Protocol (HTTP) over Unix Domain Sockets.
        ///
        /// The socket path must be given as the URI's "host" component, appropriately percent-encoded. The
        /// ``URI/init(scheme:userinfo:host:port:path:query:fragment:)`` initializer adds such encoding
        /// automatically. To manually apply the correct encoding, use:
        ///
        /// ```swift
        /// socketPath.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
        /// ```
        /// 
        /// > Registration: None (non-standard)
        public static let httpUnixDomainSocket: Self = "http+unix"
        
        /// Secure HyperText Transfer Protocol (HTTPS) over Unix Domain Sockets.
        ///
        /// The socket path must be given as the URI's "host" component, appropriately percent-encoded. The
        /// ``URI/init(scheme:userinfo:host:port:path:query:fragment:)`` initializer adds such encoding
        /// automatically. To manually apply the correct encoding, use:
        ///
        /// ```swift
        /// socketPath.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
        /// ```
        ///
        /// > Note: The primary use case for this scheme is for local communication with servers (most
        /// > often database servers) which require TLS client certificate authentication. In most other
        /// > situations, the added encryption is unnecessary and will just slow things down.
        /// >
        /// > (Well, unless your security concerns include other processes spying on your server's
        /// > communications when using UNIX sockets. But since doing that would require having already
        /// > compromised the host kernel ("It rather involved being on the other side of this airtight
        /// > hatchway."), it seems fairly safe to say such a concern would be moot.)
        ///
        /// > Registration: None (non-standard)
        public static let httpsUnixDomainSocket: Self = "https+unix"
        
        // MARK: End of "well-known" schemes -
    }
}

extension URI.Scheme: ExpressibleByStringInterpolation {
    // See `ExpressibleByStringInterpolation.init(stringLiteral:)`.
    public init(stringLiteral value: String) { self.init(value) }
}

extension URI.Scheme: CustomStringConvertible {
    // See `CustomStringConvertible.description`.
    public var description: String { self.value ?? "" }
}

extension URI.Scheme: Sendable {}

extension CharacterSet {
    /// The set of characters allowed in a URI scheme, as per [RFC 3986 § 3.1].
    ///
    /// [RFC 3986 § 3.1]: https://datatracker.ietf.org/doc/html/rfc3986#section-3.1
    fileprivate static var urlSchemeAllowed: Self {
        // Intersect the alphanumeric set plus additional characters with the host-allowed set to ensure
        // we get only ASCII codepoints in the result.
        Self.urlHostAllowed.intersection(Self.alphanumerics.union(.init(charactersIn: "+-.")))
    }
    
    /// The set of characters allowed in a URI path, as per [RFC 3986 § 3.3].
    ///
    /// > Note: This is identical to the built-in `urlPathAllowed` on macOS; on Linux it adds the missing
    /// > semicolon character to the set.
    ///
    /// [RFC 3986 § 3.3]: https://datatracker.ietf.org/doc/html/rfc3986#section-3.3
    fileprivate static var urlCorrectPathAllowed: Self {
        #if canImport(Darwin)
        .urlPathAllowed
        #else
        .urlPathAllowed.union(.init(charactersIn: ";"))
        #endif
#if !canImport(Darwin)
@preconcurrency import Dispatch
import Foundation
#if !canImport(Darwin)
@preconcurrency import Dispatch
import Foundation
import XCTVapor
import XCTest
import Vapor
import NIOCore
import Algorithms

extension RangeReplaceableCollection where Self.SubSequence == Substring, Self: StringProtocol {
    #if compiler(>=5.9)
    #if hasFeature(BareSlashRegexLiterals)
    private static var percentEncodingPattern: Regex<Substring> { /(?:%\p{AHex}{2})+/ }
    #else
    private static var percentEncodingPattern: Regex<Substring> { try! Regex("(?:%\\p{AHex}{2})+") }
    #endif
    #else
    private static var percentEncodingPattern: Regex<Substring> { try! Regex("(?:%\\p{AHex}{2})+") }
    #endif
    
    /// Foundation's `String.removingPercentEncoding` property is very unforgiving; `nil` is returned
    /// for any kind of failure whatsoever. This is just a version that gracefully ignores invalid
    /// sequences whenever possible (which is almost always).
    var safelyUrlDecoded: Self {
        self.replacing(
            Self.percentEncodingPattern,
            with: { Self(decoding: $0.0.split(separator: "%").map { .init($0, radix: 16)! }, as: UTF8.self) }
        )
    }
}

func XCTAssertURIComponents(
       scheme: @autoclosure () throws -> URI.Scheme?,
     userinfo: @autoclosure () throws -> String? = nil,
         host: @autoclosure () throws -> String? = nil,
         port: @autoclosure () throws -> Int?    = nil,
         path: @autoclosure () throws -> String,
        query: @autoclosure () throws -> String? = nil,
     fragment: @autoclosure () throws -> String? = nil,
     generate expected: @autoclosure () throws -> String,
    _ message: @autoclosure () -> String = "", file: StaticString = #filePath, line: UInt = #line
) {
    XCTAssertURIComponents(
        scheme: try scheme()?.value,
        userinfo: try userinfo(),
        host: try host(),
        port: try port(),
        path: try path(),
        query: try query(),
        fragment: try fragment(),
        generate: try expected(),
        message(), file: file, line: line
    )
}

func XCTAssertURIComponents(
       scheme: @autoclosure () throws -> String? = nil,
     userinfo: @autoclosure () throws -> String? = nil,
         host: @autoclosure () throws -> String? = nil,
         port: @autoclosure () throws -> Int?    = nil,
         path: @autoclosure () throws -> String,
        query: @autoclosure () throws -> String? = nil,
     fragment: @autoclosure () throws -> String? = nil,
     generate expected: @autoclosure () throws -> String,
    _ message: @autoclosure () -> String = "", file: StaticString = #filePath, line: UInt = #line
) {
    do {
        let scheme = try scheme(), userinfo = try userinfo(), host = try host(), port = try port(),
            path = try path(), query = try query(), fragment = try fragment()
        let uri = URI(scheme: scheme, userinfo: userinfo, host: host, port: port, path: path, query: query, fragment: fragment)
        
        // All components should be identical to their input counterparts, sans percent encoding.
        XCTAssertEqual(uri.scheme,   scheme?.safelyUrlDecoded,   "(scheme) \(message())", file: file, line: line)
        XCTAssertEqual(uri.userinfo, userinfo?.safelyUrlDecoded, "(userinfo) \(message())", file: file, line: line)
        XCTAssertEqual(uri.host,     host?.safelyUrlDecoded,     "(host) \(message())", file: file, line: line)
        XCTAssertEqual(uri.port,     port,                       "(port) \(message())", file: file, line: line)
        XCTAssertEqual(uri.path,     "/\(path.safelyUrlDecoded.trimmingPrefix("/"))", "(path) \(message())", file: file, line: line)
        XCTAssertEqual(uri.query,    query?.safelyUrlDecoded,    "(query) \(message())", file: file, line: line)
        XCTAssertEqual(uri.fragment, fragment?.safelyUrlDecoded, "(fragment) \(message())", file: file, line: line)
        
        // The URI's generated string should match the expected input.
        XCTAssertEqual(uri.string,   try expected(),             "(string) \(message())", file: file, line: line)
    } catch {
        XCTAssertEqual(try { throw error }(), false,             message(), file: file, line: line)
    }
}

func XCTAssertURIString(
     _ string: @autoclosure () throws -> String,
     hasScheme scheme:     @autoclosure () throws -> String? = nil,
     hasUserinfo userinfo: @autoclosure () throws -> String? = nil,
     hasHost host:         @autoclosure () throws -> String? = "",
     hasPort port:         @autoclosure () throws -> Int?    = nil,
     hasPath path:         @autoclosure () throws -> String,
     hasQuery query:       @autoclosure () throws -> String? = nil,
     hasFragment fragment: @autoclosure () throws -> String? = nil,
     hasEqualString exact: @autoclosure () throws -> Bool = true,
    _ message: @autoclosure () -> String = "", file: StaticString = #filePath, line: UInt = #line
) {
    do {
        let string = try string()
        let uri = URI(string: string)

        // Each component should match its expected value.
        XCTAssertEqual(uri.scheme,   try scheme()?.safelyUrlDecoded,   "(scheme) \(message())", file: file, line: line)
        XCTAssertEqual(uri.userinfo, try userinfo()?.safelyUrlDecoded, "(userinfo) \(message())", file: file, line: line)
        XCTAssertEqual(uri.host,     try host()?.safelyUrlDecoded,     "(host) \(message())", file: file, line: line)
        XCTAssertEqual(uri.port,     try port(),                       "(port) \(message())", file: file, line: line)
        XCTAssertEqual(uri.path,     try path().safelyUrlDecoded,      "(path) \(message())", file: file, line: line)
        XCTAssertEqual(uri.query,    try query()?.safelyUrlDecoded,    "(query) \(message())", file: file, line: line)
        XCTAssertEqual(uri.fragment, try fragment()?.safelyUrlDecoded, "(fragment) \(message())", file: file, line: line)
        
        // The URI's generated string should come out identical to the input string, unless explicitly stated otherwise.
        if try exact() {
            XCTAssertEqual(uri.string,   string,                       "(string) \(message())", file: file, line: line)
        }
    } catch {
        XCTAssertEqual(try { throw error }(), false,                   message(), file: file, line: line)
    }
}

final class URITests: XCTestCase {
    func testBasicConstruction() {
        XCTAssertURIString(
            "https://user:pass@vapor.codes:1234/foo?bar=baz#qux",
            hasScheme: "https",
            hasUserinfo: "user:pass",
            hasHost: "vapor.codes",
            hasPort: 1234,
            hasPath: "/foo",
            hasQuery: "bar=baz",
            hasFragment: "qux"
        )
        XCTAssertURIComponents(
            scheme: "https",
            userinfo: "user:pass",
            host: "vapor.codes",
            port: 1234,
            path: "/foo",
            query: "bar=baz",
            fragment: "qux",
            generate: "https://user:pass@vapor.codes:1234/foo?bar=baz#qux"
        )

        XCTAssertURIString("wss://echo.websocket.org/", hasScheme: "wss", hasHost: "echo.websocket.org", hasPath: "/")
        XCTAssertURIComponents(scheme: "wss", host: "echo.websocket.org", path: "/", generate: "wss://echo.websocket.org/")
    }
    
    func testMutation() {
        var uri = URI(string: "https://user:pass@vapor.codes:1234/foo?bar=baz#qux")
    
        // Mutate query
        uri.query = "bar=baz&test=1"
        XCTAssertEqual(uri.string, "https://user:pass@vapor.codes:1234/foo?bar=baz&test=1#qux")

        // Remove query
        uri.query = nil
        XCTAssertEqual(uri.string, "https://user:pass@vapor.codes:1234/foo#qux")
    }
    
    func testPathStrings() {
        // Absolute path string
        let uri = URI(string: "/foo/bar/baz")
        XCTAssertEqual(uri.path, "/foo/bar/baz")
    }
    
    func testNonAbsolutePath() {
        let uri = URI(string: "foo")

        // N.B.: This test previously asserted that the _scheme_ of the resulting URI was `foo`. This was
        // a semantically incorrect parse (per RFC 3986) and should have been considered a bug; hence it
        // is not considered source-breaking to have fixed it.
        XCTAssertEqual(uri.scheme, nil)
        XCTAssertEqual(uri.host, nil)
        XCTAssertEqual(uri.path, "foo")
    }
    
    func testStringInterpolation() {
        let foo = "foo"
        XCTAssertEqual(("/\(foo)/bar/baz" as URI).path, "/foo/bar/baz")

        let bar = "bar"
        let uri = URI(scheme: "foo\(bar)", host: "host", port: 1, path: "test", query: "query", fragment: "fragment")
        XCTAssertEqual(uri.string, "foobar://host:1/test?query#fragment")
    }
    
    func testVariousSchemesAndWeirdHosts() {
        // N.B.: This test previously asserted that the resulting string did _not_ start with the `//` "authority"
        // prefix. Again, according to RFC 3986, this was always semantically incorrect.
        XCTAssertURIComponents(
            host: "host", port: 1, path: "test", query: "query", fragment: "fragment",
            generate: "//host:1/test?query#fragment"
        )
        XCTAssertURIComponents(
            scheme: .httpUnixDomainSocket, host: "/path", path: "test",
            generate: "http+unix://%2Fpath/test"
        )
        XCTAssertURIComponents(
            scheme: .httpUnixDomainSocket, host: "/path", path: "test", fragment: "fragment",
            generate: "http+unix://%2Fpath/test#fragment"
        )
        XCTAssertURIComponents(
            scheme: .httpUnixDomainSocket, host: "/path", path: "test", query: "query", fragment: "fragment",
            generate: "http+unix://%2Fpath/test?query#fragment"
        )
    }
    
    func testDefaultInitializer() {
        let uri = URI.init()
        XCTAssertEqual(uri.string, "/")
    }
    
    func testOverlongURIParsing() {
        let zeros = String(repeating: "0", count: 65_512)
        let untrustedInput = "[https://vapor.codes.somewhere-else.test:](https://vapor.codes.somewhere-else.test/\(zeros)443)[\(zeros)](https://vapor.codes.somewhere-else.test/\(zeros)443)[443](https://vapor.codes.somewhere-else.test/\(zeros)443)"
    
        XCTAssertURIString(untrustedInput, hasHost: nil, hasPath: untrustedInput, hasEqualString: false)
    }
    
    func testUrlParsingVectors() {
        XCTAssertURIString("file:///usr/local/bin", hasScheme: "file", hasPath: "/usr/local/bin")
        XCTAssertURIString("file:/usr/local/bin", hasScheme: "file", hasHost: nil, hasPath: "/usr/local/bin")
        XCTAssertURIString("file://localhost/usr/local/bin", hasScheme: "file", hasHost: "localhost", hasPath: "/usr/local/bin")
        XCTAssertURIString("file://usr/local/bin", hasScheme: "file", hasHost: "usr", hasPath: "/local/bin")
        XCTAssertURIString("/usr/local/bin", hasHost: nil, hasPath: "/usr/local/bin")
        XCTAssertURIString("file://localhost/usr/local/bin/", hasScheme: "file", hasHost: "localhost", hasPath: "/usr/local/bin/")
        XCTAssertURIString("file://localhost/", hasScheme: "file", hasHost: "localhost", hasPath: "/")
        XCTAssertURIString("file:///", hasScheme: "file", hasPath: "/")
        XCTAssertURIString("file:/", hasScheme: "file", hasHost: nil, hasPath: "/")
        XCTAssertURIString("file:///Volumes", hasScheme: "file", hasPath: "/Volumes")
        XCTAssertURIString("file:///Users/darin", hasScheme: "file", hasPath: "/Users/darin")
        XCTAssertURIString("file:/", hasScheme: "file", hasHost: nil, hasPath: "/")
        XCTAssertURIString("file:///.", hasScheme: "file", hasPath: "/.")
        XCTAssertURIString("file:///./.", hasScheme: "file", hasPath: "/./.")
        XCTAssertURIString("file:///.///.", hasScheme: "file", hasPath: "/.///.")
        XCTAssertURIString("file:///a/..", hasScheme: "file", hasPath: "/a/..")
        XCTAssertURIString("file:///a/b/..", hasScheme: "file", hasPath: "/a/b/..")
        XCTAssertURIString("file:///a/b//..", hasScheme: "file", hasPath: "/a/b//..")
        XCTAssertURIString("file:///./a/b/..", hasScheme: "file", hasPath: "/./a/b/..")
        XCTAssertURIString("file:///a/./b/..", hasScheme: "file", hasPath: "/a/./b/..")
        XCTAssertURIString("file:///a/b/./..", hasScheme: "file", hasPath: "/a/b/./..")
        XCTAssertURIString("file:///a///b//..", hasScheme: "file", hasPath: "/a///b//..")
        XCTAssertURIString("file:///a/b/../..", hasScheme: "file", hasPath: "/a/b/../..")
        XCTAssertURIString("file:///a/b/c/../..", hasScheme: "file", hasPath: "/a/b/c/../..")
        XCTAssertURIString("file:///a/../b/..", hasScheme: "file", hasPath: "/a/../b/..")
        XCTAssertURIString("file:///a/../b/../c", hasScheme: "file", hasPath: "/a/../b/../c")
        XCTAssertURIString("file:///a/../b/../c", hasScheme: "file", hasPath: "/a/../b/../c")
        XCTAssertURIString("ftp://ftp.gnu.org/", hasScheme: "ftp", hasHost: "ftp.gnu.org", hasPath: "/")
        XCTAssertURIString("ftp://ftp.gnu.org/pub/gnu", hasScheme: "ftp", hasHost: "ftp.gnu.org", hasPath: "/pub/gnu")
        XCTAssertURIString("ftp://luser@ftp.gnu.org/pub/gnu",
            hasScheme: "ftp", hasUserinfo: "luser", hasHost: "ftp.gnu.org", hasPath: "/pub/gnu"
        )
        XCTAssertURIString("ftp://@ftp.gnu.org/pub/gnu", hasScheme: "ftp", hasUserinfo: "", hasHost: "ftp.gnu.org", hasPath: "/pub/gnu")
        XCTAssertURIString("ftp://luser:password@ftp.gnu.org/pub/gnu",
            hasScheme: "ftp", hasUserinfo: "luser:password", hasHost: "ftp.gnu.org", hasPath: "/pub/gnu"
        )
        XCTAssertURIString("ftp://:password@ftp.gnu.org/pub/gnu",
            hasScheme: "ftp", hasUserinfo: ":password", hasHost: "ftp.gnu.org", hasPath: "/pub/gnu"
        )
        XCTAssertURIString("ftp://ftp.gnu.org:72/pub/gnu", hasScheme: "ftp", hasHost: "ftp.gnu.org", hasPort: 72, hasPath: "/pub/gnu")
        XCTAssertURIString("ftp://:72/pub/gnu", hasScheme: "ftp", hasHost: "", hasPort: 72, hasPath: "/pub/gnu")
        XCTAssertURIString("http://localhost/usr/local/bin/", hasScheme: "http", hasHost: "localhost", hasPath: "/usr/local/bin/")
        XCTAssertURIString("http://localhost/", hasScheme: "http", hasHost: "localhost", hasPath: "/")
        XCTAssertURIString("http://www.apple.com/", hasScheme: "http", hasHost: "www.apple.com", hasPath: "/")
        XCTAssertURIString("http://www.apple.com/dir", hasScheme: "http", hasHost: "www.apple.com", hasPath: "/dir")
        XCTAssertURIString("http://www.apple.com/dir/", hasScheme: "http", hasHost: "www.apple.com", hasPath: "/dir/")
        XCTAssertURIString("http://darin:nothin@www.apple.com:42/dir/",
            hasScheme: "http", hasUserinfo: "darin:nothin", hasHost: "www.apple.com", hasPort: 42, hasPath: "/dir/"
        )
        XCTAssertURIString("http:/", hasScheme: "http", hasHost: nil, hasPath: "/")
        XCTAssertURIString("http://www.apple.com/query?email=darin@apple.com",
            hasScheme: "http", hasHost: "www.apple.com", hasPath: "/query", hasQuery: "email=darin@apple.com"
        )
        XCTAssertURIString("HTTP://WWW.ZOO.COM/", hasScheme: "HTTP", hasHost: "WWW.ZOO.COM", hasPath: "/")
        XCTAssertURIString("HTTP://WWW.ZOO.COM/ED", hasScheme: "HTTP", hasHost: "WWW.ZOO.COM", hasPath: "/ED")
        XCTAssertURIString("http://groups.google.com/groups?as_uauthors=joe@blow.com&as_scoring=d&hl=en",
            hasScheme: "http", hasHost: "groups.google.com", hasPath: "/groups", hasQuery: "as_uauthors=joe@blow.com&as_scoring=d&hl=en"
        )
        XCTAssertURIString("http://my.site.com/some/page.html#fragment",
            hasScheme: "http", hasHost: "my.site.com", hasPath: "/some/page.html", hasFragment: "fragment"
        )
        XCTAssertURIString("scheme://user:pass@host:1/path/path2/file.html;params?query#fragment",
            hasScheme: "scheme", hasUserinfo: "user:pass", hasHost: "host", hasPort: 1, hasPath: "/path/path2/file.html;params",
            hasQuery: "query", hasFragment: "fragment"
        )
        XCTAssertURIString("http://test.com/a%20space", hasScheme: "http", hasHost: "test.com", hasPath: "/a space")
        XCTAssertURIString("http://test.com/aBrace%7B", hasScheme: "http", hasHost: "test.com", hasPath: "/aBrace{")
        XCTAssertURIString("http://test.com/aJ%4a", hasScheme: "http", hasHost: "test.com", hasPath: "/aJJ")
        XCTAssertURIString("file:///%3F", hasScheme: "file", hasPath: "/?")
        XCTAssertURIString("file:///%78", hasScheme: "file", hasPath: "/x")
        XCTAssertURIString("file:///?", hasScheme: "file", hasPath: "/", hasQuery: "")
        XCTAssertURIString("file:///&", hasScheme: "file", hasPath: "/&")
        XCTAssertURIString("file:///x", hasScheme: "file", hasPath: "/x")
        XCTAssertURIString("http:///%3F", hasScheme: "http", hasPath: "/?")
        XCTAssertURIString("http:///%78", hasScheme: "http", hasPath: "/x")
        XCTAssertURIString("http:///?", hasScheme: "http", hasPath: "/", hasQuery: "")
        XCTAssertURIString("http:///&", hasScheme: "http", hasPath: "/&")
        XCTAssertURIString("http:///x", hasScheme: "http", hasPath: "/x")
        XCTAssertURIString("glorb:///%3F", hasScheme: "glorb", hasPath: "/?")
        XCTAssertURIString("glorb:///%78", hasScheme: "glorb", hasPath: "/x")
        XCTAssertURIString("glorb:///?", hasScheme: "glorb", hasPath: "/", hasQuery: "")
        XCTAssertURIString("glorb:///&", hasScheme: "glorb", hasPath: "/&")
        XCTAssertURIString("glorb:///x", hasScheme: "glorb", hasPath: "/x")
        XCTAssertURIString("uahsfcncvuhrtgvnahr", hasHost: nil, hasPath: "uahsfcncvuhrtgvnahr")
        XCTAssertURIString("http://[fe80::20a:27ff:feae:8b9e]/", hasScheme: "http", hasHost: "[fe80::20a:27ff:feae:8b9e]", hasPath: "/")
        XCTAssertURIString("http://[fe80::20a:27ff:feae:8b9e%25en0]/", hasScheme: "http", hasHost: "[fe80::20a:27ff:feae:8b9e%en0]", hasPath: "/")
        XCTAssertURIString("http://host.com/foo/bar/../index.html", hasScheme: "http", hasHost: "host.com", hasPath: "/foo/bar/../index.html")
        XCTAssertURIString("http://host.com/foo/bar/./index.html", hasScheme: "http", hasHost: "host.com", hasPath: "/foo/bar/./index.html")
        XCTAssertURIString("http:/cgi-bin/Count.cgi?ft=0", hasScheme: "http", hasHost: nil, hasPath: "/cgi-bin/Count.cgi", hasQuery: "ft=0")
        XCTAssertURIString("file://///", hasScheme: "file", hasPath: "///")
        XCTAssertURIString("file:/Volumes", hasScheme: "file", hasHost: nil, hasPath: "/Volumes")
        XCTAssertURIString("/Volumes", hasHost: nil, hasPath: "/Volumes")
        XCTAssertURIString(".", hasHost: nil, hasPath: ".")
        XCTAssertURIString("./a", hasHost: nil, hasPath: "./a")
        XCTAssertURIString("../a", hasHost: nil, hasPath: "../a")
        XCTAssertURIString("../../a", hasHost: nil, hasPath: "../../a")
        XCTAssertURIString("/", hasHost: nil, hasPath: "/")
        XCTAssertURIString("http://a/b/c/./g", hasScheme: "http", hasHost: "a", hasPath: "/b/c/./g")
        XCTAssertURIString("http://a/b/c/.", hasScheme: "http", hasHost: "a", hasPath: "/b/c/.")
        XCTAssertURIString("http://a/b/c/./", hasScheme: "http", hasHost: "a", hasPath: "/b/c/./")
        XCTAssertURIString("http://a/b/c/..", hasScheme: "http", hasHost: "a", hasPath: "/b/c/..")
        XCTAssertURIString("http://a/b/c/../", hasScheme: "http", hasHost: "a", hasPath: "/b/c/../")
        XCTAssertURIString("http://a/b/c/../g", hasScheme: "http", hasHost: "a", hasPath: "/b/c/../g")
        XCTAssertURIString("http://a/b/c/../..", hasScheme: "http", hasHost: "a", hasPath: "/b/c/../..")
        XCTAssertURIString("http://a/b/c/../../", hasScheme: "http", hasHost: "a", hasPath: "/b/c/../../")
        XCTAssertURIString("http://a/b/c/../../g", hasScheme: "http", hasHost: "a", hasPath: "/b/c/../../g")
        XCTAssertURIString("http://a/b/c/../../../g", hasScheme: "http", hasHost: "a", hasPath: "/b/c/../../../g")
        XCTAssertURIString("http://a/b/c/../../../../g", hasScheme: "http", hasHost: "a", hasPath: "/b/c/../../../../g")
        XCTAssertURIString("http://a/b/c/./g", hasScheme: "http", hasHost: "a", hasPath: "/b/c/./g")
        XCTAssertURIString("http://a/b/c/../g", hasScheme: "http", hasHost: "a", hasPath: "/b/c/../g")
        XCTAssertURIString("http://a/b/c/g.", hasScheme: "http", hasHost: "a", hasPath: "/b/c/g.")
        XCTAssertURIString("http://a/b/c/.g", hasScheme: "http", hasHost: "a", hasPath: "/b/c/.g")
        XCTAssertURIString("http://a/b/c/g..", hasScheme: "http", hasHost: "a", hasPath: "/b/c/g..")
        XCTAssertURIString("http://a/b/c/..g", hasScheme: "http", hasHost: "a", hasPath: "/b/c/..g")
        XCTAssertURIString("http://a/b/c/./../g", hasScheme: "http", hasHost: "a", hasPath: "/b/c/./../g")
        XCTAssertURIString("http://a/b/c/./g/.", hasScheme: "http", hasHost: "a", hasPath: "/b/c/./g/.")
        XCTAssertURIString("http://a/b/c/g/./h", hasScheme: "http", hasHost: "a", hasPath: "/b/c/g/./h")
        XCTAssertURIString("http://a/b/c/g/../h", hasScheme: "http", hasHost: "a", hasPath: "/b/c/g/../h")
        XCTAssertURIString("http://a/b/c/g;x=1/./y", hasScheme: "http", hasHost: "a", hasPath: "/b/c/g;x=1/./y")
        XCTAssertURIString("http://a/b/c/g;x=1/../y", hasScheme: "http", hasHost: "a", hasPath: "/b/c/g;x=1/../y")
        XCTAssertURIString("http://a/b/c/g?y/./x", hasScheme: "http", hasHost: "a", hasPath: "/b/c/g", hasQuery: "y/./x")
        XCTAssertURIString("http://a/b/c/g?y/../x", hasScheme: "http", hasHost: "a", hasPath: "/b/c/g", hasQuery: "y/../x")
        XCTAssertURIString("http://a/b/c/g#s/./x", hasScheme: "http", hasHost: "a", hasPath: "/b/c/g", hasFragment: "s/./x")
        XCTAssertURIString("http://a/b/c/g#s/../x", hasScheme: "http", hasHost: "a", hasPath: "/b/c/g", hasFragment: "s/../x")
        XCTAssertURIString("http://a/../../x", hasScheme: "http", hasHost: "a", hasPath: "/../../x")
        XCTAssertURIString("http://a/..///../x", hasScheme: "http", hasHost: "a", hasPath: "/..///../x")
    }
}
        // N.B.: These two checks previously asserted against a URI containing the unencoded `ß` character.
        // Such a URI is semantically incorrect (per RFC 3986) and should have been considered a bug.
        let validURL: URI = "https://tanner.xyz/email?email=%C3%9F@tanner.xyz" // ß
        let validURL2: URI = "https://tanner.xyz/email?email=me@%C3%9Fanner.xyz"