Source file src/net/url/url.go

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  //go:generate go run gen_encoding_table.go
     6  
     7  // Package url parses URLs and implements query escaping.
     8  //
     9  // See RFC 3986. This package generally follows RFC 3986, except where
    10  // it deviates for compatibility reasons.
    11  // RFC 6874 followed for IPv6 zone literals.
    12  package url
    13  
    14  // When sending changes, first  search old issues for history on decisions.
    15  // Unit tests should also contain references to issue numbers with details.
    16  
    17  import (
    18  	"bytes"
    19  	"errors"
    20  	"fmt"
    21  	"internal/godebug"
    22  	"net/netip"
    23  	"path"
    24  	"slices"
    25  	"strconv"
    26  	"strings"
    27  	_ "unsafe" // for linkname
    28  )
    29  
    30  var urlstrictcolons = godebug.New("urlstrictcolons")
    31  
    32  // Error reports an error and the operation and URL that caused it.
    33  type Error struct {
    34  	Op  string
    35  	URL string
    36  	Err error
    37  }
    38  
    39  func (e *Error) Unwrap() error { return e.Err }
    40  func (e *Error) Error() string { return fmt.Sprintf("%s %q: %s", e.Op, e.URL, e.Err) }
    41  
    42  func (e *Error) Timeout() bool {
    43  	t, ok := e.Err.(interface {
    44  		Timeout() bool
    45  	})
    46  	return ok && t.Timeout()
    47  }
    48  
    49  func (e *Error) Temporary() bool {
    50  	t, ok := e.Err.(interface {
    51  		Temporary() bool
    52  	})
    53  	return ok && t.Temporary()
    54  }
    55  
    56  const upperhex = "0123456789ABCDEF"
    57  
    58  func ishex(c byte) bool {
    59  	return table[c]&hexChar != 0
    60  }
    61  
    62  // Precondition: ishex(c) is true.
    63  func unhex(c byte) byte {
    64  	return 9*(c>>6) + (c & 15)
    65  }
    66  
    67  type EscapeError string
    68  
    69  func (e EscapeError) Error() string {
    70  	return "invalid URL escape " + strconv.Quote(string(e))
    71  }
    72  
    73  type InvalidHostError string
    74  
    75  func (e InvalidHostError) Error() string {
    76  	return "invalid character " + strconv.Quote(string(e)) + " in host name"
    77  }
    78  
    79  // See the reference implementation in gen_encoding_table.go.
    80  func shouldEscape(c byte, mode encoding) bool {
    81  	return table[c]&mode == 0
    82  }
    83  
    84  // QueryUnescape does the inverse transformation of [QueryEscape],
    85  // converting each 3-byte encoded substring of the form "%AB" into the
    86  // hex-decoded byte 0xAB.
    87  // It returns an error if any % is not followed by two hexadecimal
    88  // digits.
    89  func QueryUnescape(s string) (string, error) {
    90  	return unescape(s, encodeQueryComponent)
    91  }
    92  
    93  // PathUnescape does the inverse transformation of [PathEscape],
    94  // converting each 3-byte encoded substring of the form "%AB" into the
    95  // hex-decoded byte 0xAB. It returns an error if any % is not followed
    96  // by two hexadecimal digits.
    97  //
    98  // PathUnescape is identical to [QueryUnescape] except that it does not
    99  // unescape '+' to ' ' (space).
   100  func PathUnescape(s string) (string, error) {
   101  	return unescape(s, encodePathSegment)
   102  }
   103  
   104  // unescape unescapes a string; the mode specifies
   105  // which section of the URL string is being unescaped.
   106  func unescape(s string, mode encoding) (string, error) {
   107  	// Count %, check that they're well-formed.
   108  	n := 0
   109  	hasPlus := false
   110  	for i := 0; i < len(s); {
   111  		switch s[i] {
   112  		case '%':
   113  			n++
   114  			if i+2 >= len(s) || !ishex(s[i+1]) || !ishex(s[i+2]) {
   115  				s = s[i:]
   116  				if len(s) > 3 {
   117  					s = s[:3]
   118  				}
   119  				return "", EscapeError(s)
   120  			}
   121  			// Per https://tools.ietf.org/html/rfc3986#page-21
   122  			// in the host component %-encoding can only be used
   123  			// for non-ASCII bytes.
   124  			// But https://tools.ietf.org/html/rfc6874#section-2
   125  			// introduces %25 being allowed to escape a percent sign
   126  			// in IPv6 scoped-address literals. Yay.
   127  			if mode == encodeHost && unhex(s[i+1]) < 8 && s[i:i+3] != "%25" {
   128  				return "", EscapeError(s[i : i+3])
   129  			}
   130  			if mode == encodeZone {
   131  				// RFC 6874 says basically "anything goes" for zone identifiers
   132  				// and that even non-ASCII can be redundantly escaped,
   133  				// but it seems prudent to restrict %-escaped bytes here to those
   134  				// that are valid host name bytes in their unescaped form.
   135  				// That is, you can use escaping in the zone identifier but not
   136  				// to introduce bytes you couldn't just write directly.
   137  				// But Windows puts spaces here! Yay.
   138  				v := unhex(s[i+1])<<4 | unhex(s[i+2])
   139  				if s[i:i+3] != "%25" && v != ' ' && shouldEscape(v, encodeHost) {
   140  					return "", EscapeError(s[i : i+3])
   141  				}
   142  			}
   143  			i += 3
   144  		case '+':
   145  			hasPlus = mode == encodeQueryComponent
   146  			i++
   147  		default:
   148  			if (mode == encodeHost || mode == encodeZone) && s[i] < 0x80 && shouldEscape(s[i], mode) {
   149  				return "", InvalidHostError(s[i : i+1])
   150  			}
   151  			i++
   152  		}
   153  	}
   154  
   155  	if n == 0 && !hasPlus {
   156  		return s, nil
   157  	}
   158  
   159  	var unescapedPlusSign byte
   160  	switch mode {
   161  	case encodeQueryComponent:
   162  		unescapedPlusSign = ' '
   163  	default:
   164  		unescapedPlusSign = '+'
   165  	}
   166  	var t strings.Builder
   167  	t.Grow(len(s) - 2*n)
   168  	for i := 0; i < len(s); i++ {
   169  		switch s[i] {
   170  		case '%':
   171  			// In the loop above, we established that unhex's precondition is
   172  			// fulfilled for both s[i+1] and s[i+2].
   173  			t.WriteByte(unhex(s[i+1])<<4 | unhex(s[i+2]))
   174  			i += 2
   175  		case '+':
   176  			t.WriteByte(unescapedPlusSign)
   177  		default:
   178  			t.WriteByte(s[i])
   179  		}
   180  	}
   181  	return t.String(), nil
   182  }
   183  
   184  // QueryEscape escapes the string so it can be safely placed
   185  // inside a [URL] query.
   186  func QueryEscape(s string) string {
   187  	return escape(s, encodeQueryComponent)
   188  }
   189  
   190  // PathEscape escapes the string so it can be safely placed inside a [URL] path segment,
   191  // replacing special characters (including /) with %XX sequences as needed.
   192  func PathEscape(s string) string {
   193  	return escape(s, encodePathSegment)
   194  }
   195  
   196  func escape(s string, mode encoding) string {
   197  	spaceCount, hexCount := 0, 0
   198  	for _, c := range []byte(s) {
   199  		if shouldEscape(c, mode) {
   200  			if c == ' ' && mode == encodeQueryComponent {
   201  				spaceCount++
   202  			} else {
   203  				hexCount++
   204  			}
   205  		}
   206  	}
   207  
   208  	if spaceCount == 0 && hexCount == 0 {
   209  		return s
   210  	}
   211  
   212  	var buf [64]byte
   213  	var t []byte
   214  
   215  	required := len(s) + 2*hexCount
   216  	if required <= len(buf) {
   217  		t = buf[:required]
   218  	} else {
   219  		t = make([]byte, required)
   220  	}
   221  
   222  	if hexCount == 0 {
   223  		copy(t, s)
   224  		for i := 0; i < len(s); i++ {
   225  			if s[i] == ' ' {
   226  				t[i] = '+'
   227  			}
   228  		}
   229  		return string(t)
   230  	}
   231  
   232  	j := 0
   233  	for _, c := range []byte(s) {
   234  		switch {
   235  		case c == ' ' && mode == encodeQueryComponent:
   236  			t[j] = '+'
   237  			j++
   238  		case shouldEscape(c, mode):
   239  			t[j] = '%'
   240  			t[j+1] = upperhex[c>>4]
   241  			t[j+2] = upperhex[c&15]
   242  			j += 3
   243  		default:
   244  			t[j] = c
   245  			j++
   246  		}
   247  	}
   248  	return string(t)
   249  }
   250  
   251  // A URL represents a parsed URL (technically, a URI reference).
   252  //
   253  // The general form represented is:
   254  //
   255  //	[scheme:][//[userinfo@]host][/]path[?query][#fragment]
   256  //
   257  // URLs that do not start with a slash after the scheme are interpreted as:
   258  //
   259  //	scheme:opaque[?query][#fragment]
   260  //
   261  // The Host field contains the host and port subcomponents of the URL.
   262  // When the port is present, it is separated from the host with a colon.
   263  // When the host is an IPv6 address, it must be enclosed in square brackets:
   264  // "[fe80::1]:80". The [net.JoinHostPort] function combines a host and port
   265  // into a string suitable for the Host field, adding square brackets to
   266  // the host when necessary.
   267  //
   268  // Note that the Path field is stored in decoded form: /%47%6f%2f becomes /Go/.
   269  // A consequence is that it is impossible to tell which slashes in the Path were
   270  // slashes in the raw URL and which were %2f. This distinction is rarely important,
   271  // but when it is, the code should use the [URL.EscapedPath] method, which preserves
   272  // the original encoding of Path. The Fragment field is also stored in decoded form,
   273  // use [URL.EscapedFragment] to retrieve the original encoding.
   274  //
   275  // The [URL.String] method uses the [URL.EscapedPath] method to obtain the path.
   276  type URL struct {
   277  	Scheme   string
   278  	Opaque   string    // encoded opaque data
   279  	User     *Userinfo // username and password information
   280  	Host     string    // "host" or "host:port" (see Hostname and Port methods)
   281  	Path     string    // path (relative paths may omit leading slash)
   282  	Fragment string    // fragment for references (without '#')
   283  
   284  	// RawQuery contains the encoded query values, without the initial '?'.
   285  	// Use URL.Query to decode the query.
   286  	RawQuery string
   287  
   288  	// RawPath is an optional field containing an encoded path hint.
   289  	// See the EscapedPath method for more details.
   290  	//
   291  	// In general, code should call EscapedPath instead of reading RawPath.
   292  	RawPath string
   293  
   294  	// RawFragment is an optional field containing an encoded fragment hint.
   295  	// See the EscapedFragment method for more details.
   296  	//
   297  	// In general, code should call EscapedFragment instead of reading RawFragment.
   298  	RawFragment string
   299  
   300  	// ForceQuery indicates whether the original URL contained a query ('?') character.
   301  	// When set, the String method will include a trailing '?', even when RawQuery is empty.
   302  	ForceQuery bool
   303  
   304  	// OmitHost indicates the URL has an empty host (authority).
   305  	// When set, the String method will not include the host when it is empty.
   306  	OmitHost bool
   307  }
   308  
   309  // User returns a [Userinfo] containing the provided username
   310  // and no password set.
   311  func User(username string) *Userinfo {
   312  	return &Userinfo{username, "", false}
   313  }
   314  
   315  // UserPassword returns a [Userinfo] containing the provided username
   316  // and password.
   317  //
   318  // This functionality should only be used with legacy web sites.
   319  // RFC 2396 warns that interpreting Userinfo this way
   320  // “is NOT RECOMMENDED, because the passing of authentication
   321  // information in clear text (such as URI) has proven to be a
   322  // security risk in almost every case where it has been used.”
   323  func UserPassword(username, password string) *Userinfo {
   324  	return &Userinfo{username, password, true}
   325  }
   326  
   327  // The Userinfo type is an immutable encapsulation of username and
   328  // password details for a [URL]. An existing Userinfo value is guaranteed
   329  // to have a username set (potentially empty, as allowed by RFC 2396),
   330  // and optionally a password.
   331  type Userinfo struct {
   332  	username    string
   333  	password    string
   334  	passwordSet bool
   335  }
   336  
   337  // Username returns the username.
   338  func (u *Userinfo) Username() string {
   339  	if u == nil {
   340  		return ""
   341  	}
   342  	return u.username
   343  }
   344  
   345  // Password returns the password in case it is set, and whether it is set.
   346  func (u *Userinfo) Password() (string, bool) {
   347  	if u == nil {
   348  		return "", false
   349  	}
   350  	return u.password, u.passwordSet
   351  }
   352  
   353  // String returns the encoded userinfo information in the standard form
   354  // of "username[:password]".
   355  func (u *Userinfo) String() string {
   356  	if u == nil {
   357  		return ""
   358  	}
   359  	s := escape(u.username, encodeUserPassword)
   360  	if u.passwordSet {
   361  		s += ":" + escape(u.password, encodeUserPassword)
   362  	}
   363  	return s
   364  }
   365  
   366  // Maybe rawURL is of the form scheme:path.
   367  // (Scheme must be [a-zA-Z][a-zA-Z0-9+.-]*)
   368  // If so, return scheme, path; else return "", rawURL.
   369  func getScheme(rawURL string) (scheme, path string, err error) {
   370  	for i := 0; i < len(rawURL); i++ {
   371  		c := rawURL[i]
   372  		switch {
   373  		case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z':
   374  		// do nothing
   375  		case '0' <= c && c <= '9' || c == '+' || c == '-' || c == '.':
   376  			if i == 0 {
   377  				return "", rawURL, nil
   378  			}
   379  		case c == ':':
   380  			if i == 0 {
   381  				return "", "", errors.New("missing protocol scheme")
   382  			}
   383  			return rawURL[:i], rawURL[i+1:], nil
   384  		default:
   385  			// we have encountered an invalid character,
   386  			// so there is no valid scheme
   387  			return "", rawURL, nil
   388  		}
   389  	}
   390  	return "", rawURL, nil
   391  }
   392  
   393  // Parse parses a raw url into a [URL] structure.
   394  //
   395  // The url may be relative (a path, without a host) or absolute
   396  // (starting with a scheme). Trying to parse a hostname and path
   397  // without a scheme is invalid but may not necessarily return an
   398  // error, due to parsing ambiguities.
   399  func Parse(rawURL string) (*URL, error) {
   400  	// Cut off #frag
   401  	u, frag, _ := strings.Cut(rawURL, "#")
   402  	url, err := parse(u, false)
   403  	if err != nil {
   404  		return nil, &Error{"parse", u, err}
   405  	}
   406  	if frag == "" {
   407  		return url, nil
   408  	}
   409  	if err = url.setFragment(frag); err != nil {
   410  		return nil, &Error{"parse", rawURL, err}
   411  	}
   412  	return url, nil
   413  }
   414  
   415  // ParseRequestURI parses a raw url into a [URL] structure. It assumes that
   416  // url was received in an HTTP request, so the url is interpreted
   417  // only as an absolute URI or an absolute path.
   418  // The string url is assumed not to have a #fragment suffix.
   419  // (Web browsers strip #fragment before sending the URL to a web server.)
   420  func ParseRequestURI(rawURL string) (*URL, error) {
   421  	url, err := parse(rawURL, true)
   422  	if err != nil {
   423  		return nil, &Error{"parse", rawURL, err}
   424  	}
   425  	return url, nil
   426  }
   427  
   428  // parse parses a URL from a string in one of two contexts. If
   429  // viaRequest is true, the URL is assumed to have arrived via an HTTP request,
   430  // in which case only absolute URLs or path-absolute relative URLs are allowed.
   431  // If viaRequest is false, all forms of relative URLs are allowed.
   432  func parse(rawURL string, viaRequest bool) (*URL, error) {
   433  	var rest string
   434  	var err error
   435  
   436  	if stringContainsCTLByte(rawURL) {
   437  		return nil, errors.New("net/url: invalid control character in URL")
   438  	}
   439  
   440  	if rawURL == "" && viaRequest {
   441  		return nil, errors.New("empty url")
   442  	}
   443  	url := new(URL)
   444  
   445  	if rawURL == "*" {
   446  		url.Path = "*"
   447  		return url, nil
   448  	}
   449  
   450  	// Split off possible leading "http:", "mailto:", etc.
   451  	// Cannot contain escaped characters.
   452  	if url.Scheme, rest, err = getScheme(rawURL); err != nil {
   453  		return nil, err
   454  	}
   455  	url.Scheme = strings.ToLower(url.Scheme)
   456  
   457  	if strings.HasSuffix(rest, "?") && strings.Count(rest, "?") == 1 {
   458  		url.ForceQuery = true
   459  		rest = rest[:len(rest)-1]
   460  	} else {
   461  		rest, url.RawQuery, _ = strings.Cut(rest, "?")
   462  	}
   463  
   464  	if !strings.HasPrefix(rest, "/") {
   465  		if url.Scheme != "" {
   466  			// We consider rootless paths per RFC 3986 as opaque.
   467  			url.Opaque = rest
   468  			return url, nil
   469  		}
   470  		if viaRequest {
   471  			return nil, errors.New("invalid URI for request")
   472  		}
   473  
   474  		// Avoid confusion with malformed schemes, like cache_object:foo/bar.
   475  		// See golang.org/issue/16822.
   476  		//
   477  		// RFC 3986, §3.3:
   478  		// In addition, a URI reference (Section 4.1) may be a relative-path reference,
   479  		// in which case the first path segment cannot contain a colon (":") character.
   480  		if segment, _, _ := strings.Cut(rest, "/"); strings.Contains(segment, ":") {
   481  			// First path segment has colon. Not allowed in relative URL.
   482  			return nil, errors.New("first path segment in URL cannot contain colon")
   483  		}
   484  	}
   485  
   486  	if (url.Scheme != "" || !viaRequest && !strings.HasPrefix(rest, "///")) && strings.HasPrefix(rest, "//") {
   487  		var authority string
   488  		authority, rest = rest[2:], ""
   489  		if i := strings.Index(authority, "/"); i >= 0 {
   490  			authority, rest = authority[:i], authority[i:]
   491  		}
   492  		url.User, url.Host, err = parseAuthority(url.Scheme, authority)
   493  		if err != nil {
   494  			return nil, err
   495  		}
   496  	} else if url.Scheme != "" && strings.HasPrefix(rest, "/") {
   497  		// OmitHost is set to true when rawURL has an empty host (authority).
   498  		// See golang.org/issue/46059.
   499  		url.OmitHost = true
   500  	}
   501  
   502  	// Set Path and, optionally, RawPath.
   503  	// RawPath is a hint of the encoding of Path. We don't want to set it if
   504  	// the default escaping of Path is equivalent, to help make sure that people
   505  	// don't rely on it in general.
   506  	if err := url.setPath(rest); err != nil {
   507  		return nil, err
   508  	}
   509  	return url, nil
   510  }
   511  
   512  func parseAuthority(scheme, authority string) (user *Userinfo, host string, err error) {
   513  	i := strings.LastIndex(authority, "@")
   514  	if i < 0 {
   515  		host, err = parseHost(scheme, authority)
   516  	} else {
   517  		host, err = parseHost(scheme, authority[i+1:])
   518  	}
   519  	if err != nil {
   520  		return nil, "", err
   521  	}
   522  	if i < 0 {
   523  		return nil, host, nil
   524  	}
   525  	userinfo := authority[:i]
   526  	if !validUserinfo(userinfo) {
   527  		return nil, "", errors.New("net/url: invalid userinfo")
   528  	}
   529  	if !strings.Contains(userinfo, ":") {
   530  		if userinfo, err = unescape(userinfo, encodeUserPassword); err != nil {
   531  			return nil, "", err
   532  		}
   533  		user = User(userinfo)
   534  	} else {
   535  		username, password, _ := strings.Cut(userinfo, ":")
   536  		if username, err = unescape(username, encodeUserPassword); err != nil {
   537  			return nil, "", err
   538  		}
   539  		if password, err = unescape(password, encodeUserPassword); err != nil {
   540  			return nil, "", err
   541  		}
   542  		user = UserPassword(username, password)
   543  	}
   544  	return user, host, nil
   545  }
   546  
   547  // parseHost parses host as an authority without user
   548  // information. That is, as host[:port].
   549  func parseHost(scheme, host string) (string, error) {
   550  	if openBracketIdx := strings.LastIndex(host, "["); openBracketIdx > 0 {
   551  		return "", errors.New("invalid IP-literal")
   552  	} else if openBracketIdx == 0 {
   553  		// Parse an IP-Literal in RFC 3986 and RFC 6874.
   554  		// E.g., "[fe80::1]", "[fe80::1%25en0]", "[fe80::1]:80".
   555  		closeBracketIdx := strings.LastIndex(host, "]")
   556  		if closeBracketIdx < 0 {
   557  			return "", errors.New("missing ']' in host")
   558  		}
   559  
   560  		colonPort := host[closeBracketIdx+1:]
   561  		if !validOptionalPort(colonPort) {
   562  			return "", fmt.Errorf("invalid port %q after host", colonPort)
   563  		}
   564  		unescapedColonPort, err := unescape(colonPort, encodeHost)
   565  		if err != nil {
   566  			return "", err
   567  		}
   568  
   569  		hostname := host[openBracketIdx+1 : closeBracketIdx]
   570  		var unescapedHostname string
   571  		// RFC 6874 defines that %25 (%-encoded percent) introduces
   572  		// the zone identifier, and the zone identifier can use basically
   573  		// any %-encoding it likes. That's different from the host, which
   574  		// can only %-encode non-ASCII bytes.
   575  		// We do impose some restrictions on the zone, to avoid stupidity
   576  		// like newlines.
   577  		zoneIdx := strings.Index(hostname, "%25")
   578  		if zoneIdx >= 0 {
   579  			hostPart, err := unescape(hostname[:zoneIdx], encodeHost)
   580  			if err != nil {
   581  				return "", err
   582  			}
   583  			zonePart, err := unescape(hostname[zoneIdx:], encodeZone)
   584  			if err != nil {
   585  				return "", err
   586  			}
   587  			unescapedHostname = hostPart + zonePart
   588  		} else {
   589  			var err error
   590  			unescapedHostname, err = unescape(hostname, encodeHost)
   591  			if err != nil {
   592  				return "", err
   593  			}
   594  		}
   595  
   596  		// Per RFC 3986, only a host identified by a valid
   597  		// IPv6 address can be enclosed by square brackets.
   598  		// This excludes any IPv4, but notably not IPv4-mapped addresses.
   599  		addr, err := netip.ParseAddr(unescapedHostname)
   600  		if err != nil {
   601  			return "", fmt.Errorf("invalid host: %w", err)
   602  		}
   603  		if addr.Is4() {
   604  			return "", errors.New("invalid IP-literal")
   605  		}
   606  		return "[" + unescapedHostname + "]" + unescapedColonPort, nil
   607  	} else if i := strings.Index(host, ":"); i != -1 {
   608  		lastColon := strings.LastIndex(host, ":")
   609  		if lastColon != i {
   610  			// RFC 3986 does not allow colons to appear in the host subcomponent.
   611  			//
   612  			// However, a number of databases including PostgreSQL and MongoDB
   613  			// permit a comma-separated list of hosts (with optional ports) in the
   614  			// host subcomponent.
   615  			//
   616  			// Since we historically permitted colons to appear in the host,
   617  			// enforce strict colons only for http and https URLs.
   618  			//
   619  			// See https://go.dev/issue/75223 and https://go.dev/issue/78077.
   620  			if scheme == "http" || scheme == "https" {
   621  				if urlstrictcolons.Value() == "0" {
   622  					urlstrictcolons.IncNonDefault()
   623  					i = lastColon
   624  				}
   625  			} else {
   626  				i = lastColon
   627  			}
   628  		}
   629  		colonPort := host[i:]
   630  		if !validOptionalPort(colonPort) {
   631  			return "", fmt.Errorf("invalid port %q after host", colonPort)
   632  		}
   633  	}
   634  
   635  	var err error
   636  	if host, err = unescape(host, encodeHost); err != nil {
   637  		return "", err
   638  	}
   639  	return host, nil
   640  }
   641  
   642  // setPath sets the Path and RawPath fields of the URL based on the provided
   643  // escaped path p. It maintains the invariant that RawPath is only specified
   644  // when it differs from the default encoding of the path.
   645  // For example:
   646  // - setPath("/foo/bar")   will set Path="/foo/bar" and RawPath=""
   647  // - setPath("/foo%2fbar") will set Path="/foo/bar" and RawPath="/foo%2fbar"
   648  // setPath will return an error only if the provided path contains an invalid
   649  // escaping.
   650  //
   651  // setPath should be an internal detail,
   652  // but widely used packages access it using linkname.
   653  // Notable members of the hall of shame include:
   654  //   - github.com/sagernet/sing
   655  //
   656  // Do not remove or change the type signature.
   657  // See go.dev/issue/67401.
   658  //
   659  //go:linkname badSetPath net/url.(*URL).setPath
   660  func (u *URL) setPath(p string) error {
   661  	path, err := unescape(p, encodePath)
   662  	if err != nil {
   663  		return err
   664  	}
   665  	u.Path = path
   666  	if escp := escape(path, encodePath); p == escp {
   667  		// Default encoding is fine.
   668  		u.RawPath = ""
   669  	} else {
   670  		u.RawPath = p
   671  	}
   672  	return nil
   673  }
   674  
   675  // for linkname because we cannot linkname methods directly
   676  func badSetPath(*URL, string) error
   677  
   678  // EscapedPath returns the escaped form of u.Path.
   679  // In general there are multiple possible escaped forms of any path.
   680  // EscapedPath returns u.RawPath when it is a valid escaping of u.Path.
   681  // Otherwise EscapedPath ignores u.RawPath and computes an escaped
   682  // form on its own.
   683  // The [URL.String] and [URL.RequestURI] methods use EscapedPath to construct
   684  // their results.
   685  // In general, code should call EscapedPath instead of
   686  // reading u.RawPath directly.
   687  func (u *URL) EscapedPath() string {
   688  	if u.RawPath != "" && validEncoded(u.RawPath, encodePath) {
   689  		p, err := unescape(u.RawPath, encodePath)
   690  		if err == nil && p == u.Path {
   691  			return u.RawPath
   692  		}
   693  	}
   694  	if u.Path == "*" {
   695  		return "*" // don't escape (Issue 11202)
   696  	}
   697  	return escape(u.Path, encodePath)
   698  }
   699  
   700  // validEncoded reports whether s is a valid encoded path or fragment,
   701  // according to mode.
   702  // It must not contain any bytes that require escaping during encoding.
   703  func validEncoded(s string, mode encoding) bool {
   704  	for i := 0; i < len(s); i++ {
   705  		// RFC 3986, Appendix A.
   706  		// pchar = unreserved / pct-encoded / sub-delims / ":" / "@".
   707  		// shouldEscape is not quite compliant with the RFC,
   708  		// so we check the sub-delims ourselves and let
   709  		// shouldEscape handle the others.
   710  		switch s[i] {
   711  		case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '@':
   712  			// ok
   713  		case '[', ']':
   714  			// ok - not specified in RFC 3986 but left alone by modern browsers
   715  		case '%':
   716  			// ok - percent encoded, will decode
   717  		default:
   718  			if shouldEscape(s[i], mode) {
   719  				return false
   720  			}
   721  		}
   722  	}
   723  	return true
   724  }
   725  
   726  // setFragment is like setPath but for Fragment/RawFragment.
   727  func (u *URL) setFragment(f string) error {
   728  	frag, err := unescape(f, encodeFragment)
   729  	if err != nil {
   730  		return err
   731  	}
   732  	u.Fragment = frag
   733  	if escf := escape(frag, encodeFragment); f == escf {
   734  		// Default encoding is fine.
   735  		u.RawFragment = ""
   736  	} else {
   737  		u.RawFragment = f
   738  	}
   739  	return nil
   740  }
   741  
   742  // EscapedFragment returns the escaped form of u.Fragment.
   743  // In general there are multiple possible escaped forms of any fragment.
   744  // EscapedFragment returns u.RawFragment when it is a valid escaping of u.Fragment.
   745  // Otherwise EscapedFragment ignores u.RawFragment and computes an escaped
   746  // form on its own.
   747  // The [URL.String] method uses EscapedFragment to construct its result.
   748  // In general, code should call EscapedFragment instead of
   749  // reading u.RawFragment directly.
   750  func (u *URL) EscapedFragment() string {
   751  	if u.RawFragment != "" && validEncoded(u.RawFragment, encodeFragment) {
   752  		f, err := unescape(u.RawFragment, encodeFragment)
   753  		if err == nil && f == u.Fragment {
   754  			return u.RawFragment
   755  		}
   756  	}
   757  	return escape(u.Fragment, encodeFragment)
   758  }
   759  
   760  // validOptionalPort reports whether port is either an empty string
   761  // or matches /^:\d*$/
   762  func validOptionalPort(port string) bool {
   763  	if port == "" {
   764  		return true
   765  	}
   766  	if port[0] != ':' {
   767  		return false
   768  	}
   769  	for _, b := range port[1:] {
   770  		if b < '0' || b > '9' {
   771  			return false
   772  		}
   773  	}
   774  	return true
   775  }
   776  
   777  // String reassembles the [URL] into a valid URL string.
   778  // The general form of the result is one of:
   779  //
   780  //	scheme:opaque?query#fragment
   781  //	scheme://userinfo@host/path?query#fragment
   782  //
   783  // If u.Opaque is non-empty, String uses the first form;
   784  // otherwise it uses the second form.
   785  // Any non-ASCII characters in host are escaped.
   786  // To obtain the path, String uses u.EscapedPath().
   787  //
   788  // In the second form, the following rules apply:
   789  //   - if u.Scheme is empty, scheme: is omitted.
   790  //   - if u.User is nil, userinfo@ is omitted.
   791  //   - if u.Host is empty, host/ is omitted.
   792  //   - if u.Scheme and u.Host are empty and u.User is nil,
   793  //     the entire scheme://userinfo@host/ is omitted.
   794  //   - if u.Host is non-empty and u.Path begins with a /,
   795  //     the form host/path does not add its own /.
   796  //   - if u.RawQuery is empty, ?query is omitted.
   797  //   - if u.Fragment is empty, #fragment is omitted.
   798  func (u *URL) String() string {
   799  	var buf strings.Builder
   800  
   801  	n := len(u.Scheme)
   802  	if u.Opaque != "" {
   803  		n += len(u.Opaque)
   804  	} else {
   805  		if !u.OmitHost && (u.Scheme != "" || u.Host != "" || u.User != nil) {
   806  			username := u.User.Username()
   807  			password, _ := u.User.Password()
   808  			n += len(username) + len(password) + len(u.Host)
   809  		}
   810  		n += len(u.Path)
   811  	}
   812  	n += len(u.RawQuery) + len(u.RawFragment)
   813  	n += len(":" + "//" + "//" + ":" + "@" + "/" + "./" + "?" + "#")
   814  	buf.Grow(n)
   815  
   816  	if u.Scheme != "" {
   817  		buf.WriteString(u.Scheme)
   818  		buf.WriteByte(':')
   819  	}
   820  	if u.Opaque != "" {
   821  		buf.WriteString(u.Opaque)
   822  	} else {
   823  		if u.Scheme != "" || u.Host != "" || u.User != nil {
   824  			if u.OmitHost && u.Host == "" && u.User == nil {
   825  				// omit empty host
   826  			} else {
   827  				if u.Host != "" || u.Path != "" || u.User != nil {
   828  					buf.WriteString("//")
   829  				}
   830  				if ui := u.User; ui != nil {
   831  					buf.WriteString(ui.String())
   832  					buf.WriteByte('@')
   833  				}
   834  				if h := u.Host; h != "" {
   835  					buf.WriteString(escape(h, encodeHost))
   836  				}
   837  			}
   838  		}
   839  		path := u.EscapedPath()
   840  		if u.OmitHost && u.Host == "" && u.User == nil && strings.HasPrefix(path, "//") {
   841  			// Escape the first / in a path starting with "//" and no authority
   842  			// so that re-parsing the URL doesn't turn the path into an authority
   843  			// (e.g., Path="//host/p" producing "http://host/p").
   844  			buf.WriteString("%2F")
   845  			path = path[1:]
   846  		}
   847  		if path != "" && path[0] != '/' && u.Host != "" {
   848  			buf.WriteByte('/')
   849  		}
   850  		if buf.Len() == 0 {
   851  			// RFC 3986 §4.2
   852  			// A path segment that contains a colon character (e.g., "this:that")
   853  			// cannot be used as the first segment of a relative-path reference, as
   854  			// it would be mistaken for a scheme name. Such a segment must be
   855  			// preceded by a dot-segment (e.g., "./this:that") to make a relative-
   856  			// path reference.
   857  			if segment, _, _ := strings.Cut(path, "/"); strings.Contains(segment, ":") {
   858  				buf.WriteString("./")
   859  			}
   860  		}
   861  		buf.WriteString(path)
   862  	}
   863  	if u.ForceQuery || u.RawQuery != "" {
   864  		buf.WriteByte('?')
   865  		buf.WriteString(u.RawQuery)
   866  	}
   867  	if u.Fragment != "" {
   868  		buf.WriteByte('#')
   869  		buf.WriteString(u.EscapedFragment())
   870  	}
   871  	return buf.String()
   872  }
   873  
   874  // Redacted is like [URL.String] but replaces any password with "xxxxx".
   875  // Only the password in u.User is redacted.
   876  func (u *URL) Redacted() string {
   877  	if u == nil {
   878  		return ""
   879  	}
   880  
   881  	ru := *u
   882  	if _, has := ru.User.Password(); has {
   883  		ru.User = UserPassword(ru.User.Username(), "xxxxx")
   884  	}
   885  	return ru.String()
   886  }
   887  
   888  // Values maps a string key to a list of values.
   889  // It is typically used for query parameters and form values.
   890  // Unlike in the http.Header map, the keys in a Values map
   891  // are case-sensitive.
   892  type Values map[string][]string
   893  
   894  // Get gets the first value associated with the given key.
   895  // If there are no values associated with the key, Get returns
   896  // the empty string. To access multiple values, use the map
   897  // directly.
   898  func (v Values) Get(key string) string {
   899  	vs := v[key]
   900  	if len(vs) == 0 {
   901  		return ""
   902  	}
   903  	return vs[0]
   904  }
   905  
   906  // Set sets the key to value. It replaces any existing
   907  // values.
   908  func (v Values) Set(key, value string) {
   909  	v[key] = []string{value}
   910  }
   911  
   912  // Add adds the value to key. It appends to any existing
   913  // values associated with key.
   914  func (v Values) Add(key, value string) {
   915  	v[key] = append(v[key], value)
   916  }
   917  
   918  // Del deletes the values associated with key.
   919  func (v Values) Del(key string) {
   920  	delete(v, key)
   921  }
   922  
   923  // Has checks whether a given key is set.
   924  func (v Values) Has(key string) bool {
   925  	_, ok := v[key]
   926  	return ok
   927  }
   928  
   929  // Clone creates a deep copy of the subject [Values].
   930  func (vs Values) Clone() Values {
   931  	if vs == nil {
   932  		return nil
   933  	}
   934  
   935  	newVals := make(Values, len(vs))
   936  	for k, v := range vs {
   937  		newVals[k] = slices.Clone(v)
   938  	}
   939  	return newVals
   940  }
   941  
   942  // ParseQuery parses the URL-encoded query string and returns
   943  // a map listing the values specified for each key.
   944  // ParseQuery always returns a non-nil map containing all the
   945  // valid query parameters found; err describes the first decoding error
   946  // encountered, if any.
   947  //
   948  // Query is expected to be a list of key=value settings separated by ampersands.
   949  // A setting without an equals sign is interpreted as a key set to an empty
   950  // value.
   951  // Settings containing a non-URL-encoded semicolon are considered invalid.
   952  func ParseQuery(query string) (Values, error) {
   953  	m := make(Values)
   954  	err := parseQuery(m, query)
   955  	return m, err
   956  }
   957  
   958  var urlmaxqueryparams = godebug.New("urlmaxqueryparams")
   959  
   960  // Keep this in sync with net/http/httputil.
   961  const defaultMaxParams = 10000
   962  
   963  func urlParamsWithinMax(params int) bool {
   964  	withinDefaultMax := params <= defaultMaxParams
   965  	if urlmaxqueryparams.Value() == "" {
   966  		return withinDefaultMax
   967  	}
   968  	customMax, err := strconv.Atoi(urlmaxqueryparams.Value())
   969  	if err != nil {
   970  		return withinDefaultMax
   971  	}
   972  	withinCustomMax := customMax == 0 || params < customMax
   973  	if withinDefaultMax != withinCustomMax {
   974  		urlmaxqueryparams.IncNonDefault()
   975  	}
   976  	return withinCustomMax
   977  }
   978  
   979  func parseQuery(m Values, query string) (err error) {
   980  	if !urlParamsWithinMax(strings.Count(query, "&") + 1) {
   981  		return errors.New("number of URL query parameters exceeded limit")
   982  	}
   983  	for query != "" {
   984  		var key string
   985  		key, query, _ = strings.Cut(query, "&")
   986  		if strings.Contains(key, ";") {
   987  			err = fmt.Errorf("invalid semicolon separator in query")
   988  			continue
   989  		}
   990  		if key == "" {
   991  			continue
   992  		}
   993  		key, value, _ := strings.Cut(key, "=")
   994  		key, err1 := QueryUnescape(key)
   995  		if err1 != nil {
   996  			if err == nil {
   997  				err = err1
   998  			}
   999  			continue
  1000  		}
  1001  		value, err1 = QueryUnescape(value)
  1002  		if err1 != nil {
  1003  			if err == nil {
  1004  				err = err1
  1005  			}
  1006  			continue
  1007  		}
  1008  		m[key] = append(m[key], value)
  1009  	}
  1010  	return err
  1011  }
  1012  
  1013  // Encode encodes the values into “URL encoded” form
  1014  // ("bar=baz&foo=quux") sorted by key.
  1015  func (v Values) Encode() string {
  1016  	if len(v) == 0 {
  1017  		return ""
  1018  	}
  1019  	var buf strings.Builder
  1020  	// To minimize allocations, we eschew iterators and pre-size the slice in
  1021  	// which we collect v's keys.
  1022  	keys := make([]string, len(v))
  1023  	var i int
  1024  	for k := range v {
  1025  		keys[i] = k
  1026  		i++
  1027  	}
  1028  	slices.Sort(keys)
  1029  	for _, k := range keys {
  1030  		vs := v[k]
  1031  		keyEscaped := QueryEscape(k)
  1032  		for _, v := range vs {
  1033  			if buf.Len() > 0 {
  1034  				buf.WriteByte('&')
  1035  			}
  1036  			buf.WriteString(keyEscaped)
  1037  			buf.WriteByte('=')
  1038  			buf.WriteString(QueryEscape(v))
  1039  		}
  1040  	}
  1041  	return buf.String()
  1042  }
  1043  
  1044  // resolvePath applies special path segments from refs and applies
  1045  // them to base, per RFC 3986.
  1046  func resolvePath(base, ref string) string {
  1047  	var full string
  1048  	if ref == "" {
  1049  		full = base
  1050  	} else if ref[0] != '/' {
  1051  		i := strings.LastIndex(base, "/")
  1052  		full = base[:i+1] + ref
  1053  	} else {
  1054  		full = ref
  1055  	}
  1056  	if full == "" {
  1057  		return ""
  1058  	}
  1059  
  1060  	dst := make([]byte, 0, len(full)+1)
  1061  	dst = append(dst, '/')
  1062  	elem := ""
  1063  	remaining := full
  1064  	found := true
  1065  	first := true
  1066  	for found {
  1067  		elem, remaining, found = strings.Cut(remaining, "/")
  1068  		switch elem {
  1069  		case ".":
  1070  			first = false
  1071  			continue
  1072  		case "..":
  1073  			if i := bytes.LastIndexByte(dst[1:], '/'); i >= 0 {
  1074  				dst = dst[:i+1]
  1075  			} else {
  1076  				dst = dst[:1]
  1077  			}
  1078  			first = len(dst) == 1
  1079  		default:
  1080  			if !first {
  1081  				dst = append(dst, '/')
  1082  			}
  1083  			dst = append(dst, elem...)
  1084  			first = false
  1085  		}
  1086  	}
  1087  
  1088  	if elem == "." || elem == ".." {
  1089  		dst = append(dst, '/')
  1090  	}
  1091  
  1092  	// We wrote an initial '/', but we don't want two.
  1093  	if len(dst) > 1 && dst[1] == '/' {
  1094  		return string(dst[1:])
  1095  	}
  1096  	return string(dst)
  1097  }
  1098  
  1099  // IsAbs reports whether the [URL] is absolute.
  1100  // Absolute means that it has a non-empty scheme.
  1101  func (u *URL) IsAbs() bool {
  1102  	return u.Scheme != ""
  1103  }
  1104  
  1105  // Parse parses a [URL] in the context of the receiver. The provided URL
  1106  // may be relative or absolute. Parse returns nil, err on parse
  1107  // failure, otherwise its return value is the same as [URL.ResolveReference].
  1108  func (u *URL) Parse(ref string) (*URL, error) {
  1109  	refURL, err := Parse(ref)
  1110  	if err != nil {
  1111  		return nil, err
  1112  	}
  1113  	return u.ResolveReference(refURL), nil
  1114  }
  1115  
  1116  // ResolveReference resolves a URI reference to an absolute URI from
  1117  // an absolute base URI u, per RFC 3986 Section 5.2. The URI reference
  1118  // may be relative or absolute. ResolveReference always returns a new
  1119  // [URL] instance, even if the returned URL is identical to either the
  1120  // base or reference. If ref is an absolute URL, then ResolveReference
  1121  // ignores base and returns a copy of ref.
  1122  func (u *URL) ResolveReference(ref *URL) *URL {
  1123  	url := *ref
  1124  	if ref.Scheme == "" {
  1125  		url.Scheme = u.Scheme
  1126  	}
  1127  	if ref.Scheme != "" || ref.Host != "" || ref.User != nil {
  1128  		// The "absoluteURI" or "net_path" cases.
  1129  		// We can ignore the error from setPath since we know we provided a
  1130  		// validly-escaped path.
  1131  		url.setPath(resolvePath(ref.EscapedPath(), ""))
  1132  		return &url
  1133  	}
  1134  	if ref.Opaque != "" {
  1135  		url.User = nil
  1136  		url.Host = ""
  1137  		url.Path = ""
  1138  		return &url
  1139  	}
  1140  	if ref.Path == "" && !ref.ForceQuery && ref.RawQuery == "" {
  1141  		url.RawQuery = u.RawQuery
  1142  		if ref.Fragment == "" {
  1143  			url.Fragment = u.Fragment
  1144  			url.RawFragment = u.RawFragment
  1145  		}
  1146  	}
  1147  	if ref.Path == "" && u.Opaque != "" {
  1148  		url.Opaque = u.Opaque
  1149  		url.User = nil
  1150  		url.Host = ""
  1151  		url.Path = ""
  1152  		return &url
  1153  	}
  1154  	// The "abs_path" or "rel_path" cases.
  1155  	url.Host = u.Host
  1156  	url.User = u.User
  1157  	url.setPath(resolvePath(u.EscapedPath(), ref.EscapedPath()))
  1158  	return &url
  1159  }
  1160  
  1161  // Query parses RawQuery and returns the corresponding values.
  1162  // It silently discards malformed value pairs.
  1163  // To check errors use [ParseQuery].
  1164  func (u *URL) Query() Values {
  1165  	v, _ := ParseQuery(u.RawQuery)
  1166  	return v
  1167  }
  1168  
  1169  // RequestURI returns the encoded path?query or opaque?query
  1170  // string that would be used in an HTTP request for u.
  1171  func (u *URL) RequestURI() string {
  1172  	result := u.Opaque
  1173  	if result == "" {
  1174  		result = u.EscapedPath()
  1175  		if result == "" {
  1176  			result = "/"
  1177  		}
  1178  	} else {
  1179  		if strings.HasPrefix(result, "//") {
  1180  			result = u.Scheme + ":" + result
  1181  		}
  1182  	}
  1183  	if u.ForceQuery || u.RawQuery != "" {
  1184  		result += "?" + u.RawQuery
  1185  	}
  1186  	return result
  1187  }
  1188  
  1189  // Hostname returns u.Host, stripping any valid port number if present.
  1190  //
  1191  // If the result is enclosed in square brackets, as literal IPv6 addresses are,
  1192  // the square brackets are removed from the result.
  1193  func (u *URL) Hostname() string {
  1194  	host, _ := splitHostPort(u.Host)
  1195  	return host
  1196  }
  1197  
  1198  // Port returns the port part of u.Host, without the leading colon.
  1199  //
  1200  // If u.Host doesn't contain a valid numeric port, Port returns an empty string.
  1201  func (u *URL) Port() string {
  1202  	_, port := splitHostPort(u.Host)
  1203  	return port
  1204  }
  1205  
  1206  // splitHostPort separates host and port. If the port is not valid, it returns
  1207  // the entire input as host, and it doesn't check the validity of the host.
  1208  // Unlike net.SplitHostPort, but per RFC 3986, it requires ports to be numeric.
  1209  func splitHostPort(hostPort string) (host, port string) {
  1210  	host = hostPort
  1211  
  1212  	colon := strings.LastIndexByte(host, ':')
  1213  	if colon != -1 && validOptionalPort(host[colon:]) {
  1214  		host, port = host[:colon], host[colon+1:]
  1215  	}
  1216  
  1217  	if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
  1218  		host = host[1 : len(host)-1]
  1219  	}
  1220  
  1221  	return
  1222  }
  1223  
  1224  // Marshaling interface implementations.
  1225  // Would like to implement MarshalText/UnmarshalText but that will change the JSON representation of URLs.
  1226  
  1227  func (u *URL) MarshalBinary() (text []byte, err error) {
  1228  	return u.AppendBinary(nil)
  1229  }
  1230  
  1231  func (u *URL) AppendBinary(b []byte) ([]byte, error) {
  1232  	return append(b, u.String()...), nil
  1233  }
  1234  
  1235  func (u *URL) UnmarshalBinary(text []byte) error {
  1236  	u1, err := Parse(string(text))
  1237  	if err != nil {
  1238  		return err
  1239  	}
  1240  	*u = *u1
  1241  	return nil
  1242  }
  1243  
  1244  // JoinPath returns a new [URL] with the provided path elements joined to
  1245  // any existing path and the resulting path cleaned of any ./ or ../ elements.
  1246  // Any sequences of multiple / characters will be reduced to a single /.
  1247  // Path elements must already be in escaped form, as produced by [PathEscape].
  1248  func (u *URL) JoinPath(elem ...string) *URL {
  1249  	url, _ := u.joinPath(elem...)
  1250  	return url
  1251  }
  1252  
  1253  func (u *URL) joinPath(elem ...string) (*URL, error) {
  1254  	elem = append([]string{u.EscapedPath()}, elem...)
  1255  	var p string
  1256  	if !strings.HasPrefix(elem[0], "/") {
  1257  		// Return a relative path if u is relative,
  1258  		// but ensure that it contains no ../ elements.
  1259  		elem[0] = "/" + elem[0]
  1260  		p = path.Join(elem...)[1:]
  1261  	} else {
  1262  		p = path.Join(elem...)
  1263  	}
  1264  	// path.Join will remove any trailing slashes.
  1265  	// Preserve at least one.
  1266  	if strings.HasSuffix(elem[len(elem)-1], "/") && !strings.HasSuffix(p, "/") {
  1267  		p += "/"
  1268  	}
  1269  	url := *u
  1270  	err := url.setPath(p)
  1271  	return &url, err
  1272  }
  1273  
  1274  // validUserinfo reports whether s is a valid userinfo string per RFC 3986
  1275  // Section 3.2.1:
  1276  //
  1277  //	userinfo    = *( unreserved / pct-encoded / sub-delims / ":" )
  1278  //	unreserved  = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1279  //	sub-delims  = "!" / "$" / "&" / "'" / "(" / ")"
  1280  //	              / "*" / "+" / "," / ";" / "="
  1281  //
  1282  // It doesn't validate pct-encoded. The caller does that via func unescape.
  1283  func validUserinfo(s string) bool {
  1284  	for _, r := range s {
  1285  		if 'A' <= r && r <= 'Z' {
  1286  			continue
  1287  		}
  1288  		if 'a' <= r && r <= 'z' {
  1289  			continue
  1290  		}
  1291  		if '0' <= r && r <= '9' {
  1292  			continue
  1293  		}
  1294  		switch r {
  1295  		case '-', '.', '_', ':', '~', '!', '$', '&', '\'',
  1296  			'(', ')', '*', '+', ',', ';', '=', '%':
  1297  			continue
  1298  		case '@':
  1299  			// `RFC 3986 section 3.2.1` does not allow '@' in userinfo.
  1300  			// It is a delimiter between userinfo and host.
  1301  			// However, URLs are diverse, and in some cases,
  1302  			// the userinfo may contain an '@' character,
  1303  			// for example, in "http://username:p@ssword@google.com",
  1304  			// the string "username:p@ssword" should be treated as valid userinfo.
  1305  			// Ref:
  1306  			//   https://go.dev/issue/3439
  1307  			//   https://go.dev/issue/22655
  1308  			continue
  1309  		default:
  1310  			return false
  1311  		}
  1312  	}
  1313  	return true
  1314  }
  1315  
  1316  // stringContainsCTLByte reports whether s contains any ASCII control character.
  1317  func stringContainsCTLByte(s string) bool {
  1318  	for i := 0; i < len(s); i++ {
  1319  		b := s[i]
  1320  		if b < ' ' || b == 0x7f {
  1321  			return true
  1322  		}
  1323  	}
  1324  	return false
  1325  }
  1326  
  1327  // JoinPath returns a [URL] string with the provided path elements joined to
  1328  // the existing path of base and the resulting path cleaned of any ./ or ../ elements.
  1329  // Path elements must already be in escaped form, as produced by [PathEscape].
  1330  func JoinPath(base string, elem ...string) (result string, err error) {
  1331  	url, err := Parse(base)
  1332  	if err != nil {
  1333  		return
  1334  	}
  1335  	res, err := url.joinPath(elem...)
  1336  	if err != nil {
  1337  		return "", err
  1338  	}
  1339  	return res.String(), nil
  1340  }
  1341  
  1342  // Clone creates a deep copy of the fields of the subject [URL].
  1343  func (u *URL) Clone() *URL {
  1344  	if u == nil {
  1345  		return nil
  1346  	}
  1347  
  1348  	uc := new(*u)
  1349  	if u.User != nil {
  1350  		uc.User = new(*u.User)
  1351  	}
  1352  	return uc
  1353  }
  1354  

View as plain text