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

View as plain text