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  // MustParse calls [Parse](rawURL) and panics on error.
   415  // It is intended for use with hard-coded strings representing valid urls.
   416  func MustParse(rawURL string) *URL {
   417  	url, err := Parse(rawURL)
   418  	if err != nil {
   419  		panic(err)
   420  	}
   421  	return url
   422  }
   423  
   424  // ParseRequestURI parses a raw url into a [URL] structure. It assumes that
   425  // url was received in an HTTP request, so the url is interpreted
   426  // only as an absolute URI or an absolute path.
   427  // The string url is assumed not to have a #fragment suffix.
   428  // (Web browsers strip #fragment before sending the URL to a web server.)
   429  func ParseRequestURI(rawURL string) (*URL, error) {
   430  	url, err := parse(rawURL, true)
   431  	if err != nil {
   432  		return nil, &Error{"parse", rawURL, err}
   433  	}
   434  	return url, nil
   435  }
   436  
   437  // parse parses a URL from a string in one of two contexts. If
   438  // viaRequest is true, the URL is assumed to have arrived via an HTTP request,
   439  // in which case only absolute URLs or path-absolute relative URLs are allowed.
   440  // If viaRequest is false, all forms of relative URLs are allowed.
   441  func parse(rawURL string, viaRequest bool) (*URL, error) {
   442  	var rest string
   443  	var err error
   444  
   445  	if stringContainsCTLByte(rawURL) {
   446  		return nil, errors.New("net/url: invalid control character in URL")
   447  	}
   448  
   449  	if rawURL == "" && viaRequest {
   450  		return nil, errors.New("empty url")
   451  	}
   452  	url := new(URL)
   453  
   454  	if rawURL == "*" {
   455  		url.Path = "*"
   456  		return url, nil
   457  	}
   458  
   459  	// Split off possible leading "http:", "mailto:", etc.
   460  	// Cannot contain escaped characters.
   461  	if url.Scheme, rest, err = getScheme(rawURL); err != nil {
   462  		return nil, err
   463  	}
   464  	url.Scheme = strings.ToLower(url.Scheme)
   465  
   466  	if strings.HasSuffix(rest, "?") && strings.Count(rest, "?") == 1 {
   467  		url.ForceQuery = true
   468  		rest = rest[:len(rest)-1]
   469  	} else {
   470  		rest, url.RawQuery, _ = strings.Cut(rest, "?")
   471  	}
   472  
   473  	if !strings.HasPrefix(rest, "/") {
   474  		if url.Scheme != "" {
   475  			// We consider rootless paths per RFC 3986 as opaque.
   476  			url.Opaque = rest
   477  			return url, nil
   478  		}
   479  		if viaRequest {
   480  			return nil, errors.New("invalid URI for request")
   481  		}
   482  
   483  		// Avoid confusion with malformed schemes, like cache_object:foo/bar.
   484  		// See golang.org/issue/16822.
   485  		//
   486  		// RFC 3986, §3.3:
   487  		// In addition, a URI reference (Section 4.1) may be a relative-path reference,
   488  		// in which case the first path segment cannot contain a colon (":") character.
   489  		if segment, _, _ := strings.Cut(rest, "/"); strings.Contains(segment, ":") {
   490  			// First path segment has colon. Not allowed in relative URL.
   491  			return nil, errors.New("first path segment in URL cannot contain colon")
   492  		}
   493  	}
   494  
   495  	if (url.Scheme != "" || !viaRequest && !strings.HasPrefix(rest, "///")) && strings.HasPrefix(rest, "//") {
   496  		var authority string
   497  		authority, rest = rest[2:], ""
   498  		if i := strings.Index(authority, "/"); i >= 0 {
   499  			authority, rest = authority[:i], authority[i:]
   500  		}
   501  		url.User, url.Host, err = parseAuthority(url.Scheme, authority)
   502  		if err != nil {
   503  			return nil, err
   504  		}
   505  	} else if url.Scheme != "" && strings.HasPrefix(rest, "/") {
   506  		// OmitHost is set to true when rawURL has an empty host (authority).
   507  		// See golang.org/issue/46059.
   508  		url.OmitHost = true
   509  	}
   510  
   511  	// Set Path and, optionally, RawPath.
   512  	// RawPath is a hint of the encoding of Path. We don't want to set it if
   513  	// the default escaping of Path is equivalent, to help make sure that people
   514  	// don't rely on it in general.
   515  	if err := url.setPath(rest); err != nil {
   516  		return nil, err
   517  	}
   518  	return url, nil
   519  }
   520  
   521  func parseAuthority(scheme, authority string) (user *Userinfo, host string, err error) {
   522  	i := strings.LastIndex(authority, "@")
   523  	if i < 0 {
   524  		host, err = parseHost(scheme, authority)
   525  	} else {
   526  		host, err = parseHost(scheme, authority[i+1:])
   527  	}
   528  	if err != nil {
   529  		return nil, "", err
   530  	}
   531  	if i < 0 {
   532  		return nil, host, nil
   533  	}
   534  	userinfo := authority[:i]
   535  	if !validUserinfo(userinfo) {
   536  		return nil, "", errors.New("net/url: invalid userinfo")
   537  	}
   538  	if !strings.Contains(userinfo, ":") {
   539  		if userinfo, err = unescape(userinfo, encodeUserPassword); err != nil {
   540  			return nil, "", err
   541  		}
   542  		user = User(userinfo)
   543  	} else {
   544  		username, password, _ := strings.Cut(userinfo, ":")
   545  		if username, err = unescape(username, encodeUserPassword); err != nil {
   546  			return nil, "", err
   547  		}
   548  		if password, err = unescape(password, encodeUserPassword); err != nil {
   549  			return nil, "", err
   550  		}
   551  		user = UserPassword(username, password)
   552  	}
   553  	return user, host, nil
   554  }
   555  
   556  // parseHost parses host as an authority without user
   557  // information. That is, as host[:port].
   558  func parseHost(scheme, host string) (string, error) {
   559  	if openBracketIdx := strings.LastIndex(host, "["); openBracketIdx > 0 {
   560  		return "", errors.New("invalid IP-literal")
   561  	} else if openBracketIdx == 0 {
   562  		// Parse an IP-Literal in RFC 3986 and RFC 6874.
   563  		// E.g., "[fe80::1]", "[fe80::1%25en0]", "[fe80::1]:80".
   564  		closeBracketIdx := strings.LastIndex(host, "]")
   565  		if closeBracketIdx < 0 {
   566  			return "", errors.New("missing ']' in host")
   567  		}
   568  
   569  		colonPort := host[closeBracketIdx+1:]
   570  		if !validOptionalPort(colonPort) {
   571  			return "", fmt.Errorf("invalid port %q after host", colonPort)
   572  		}
   573  		unescapedColonPort, err := unescape(colonPort, encodeHost)
   574  		if err != nil {
   575  			return "", err
   576  		}
   577  
   578  		hostname := host[openBracketIdx+1 : closeBracketIdx]
   579  		var unescapedHostname string
   580  		// RFC 6874 defines that %25 (%-encoded percent) introduces
   581  		// the zone identifier, and the zone identifier can use basically
   582  		// any %-encoding it likes. That's different from the host, which
   583  		// can only %-encode non-ASCII bytes.
   584  		// We do impose some restrictions on the zone, to avoid stupidity
   585  		// like newlines.
   586  		zoneIdx := strings.Index(hostname, "%25")
   587  		if zoneIdx >= 0 {
   588  			hostPart, err := unescape(hostname[:zoneIdx], encodeHost)
   589  			if err != nil {
   590  				return "", err
   591  			}
   592  			zonePart, err := unescape(hostname[zoneIdx:], encodeZone)
   593  			if err != nil {
   594  				return "", err
   595  			}
   596  			unescapedHostname = hostPart + zonePart
   597  		} else {
   598  			var err error
   599  			unescapedHostname, err = unescape(hostname, encodeHost)
   600  			if err != nil {
   601  				return "", err
   602  			}
   603  		}
   604  
   605  		// Per RFC 3986, only a host identified by a valid
   606  		// IPv6 address can be enclosed by square brackets.
   607  		// This excludes any IPv4, but notably not IPv4-mapped addresses.
   608  		addr, err := netip.ParseAddr(unescapedHostname)
   609  		if err != nil {
   610  			return "", fmt.Errorf("invalid host: %w", err)
   611  		}
   612  		if addr.Is4() {
   613  			return "", errors.New("invalid IP-literal")
   614  		}
   615  		return "[" + unescapedHostname + "]" + unescapedColonPort, nil
   616  	} else if i := strings.Index(host, ":"); i != -1 {
   617  		lastColon := strings.LastIndex(host, ":")
   618  		if lastColon != i {
   619  			// RFC 3986 does not allow colons to appear in the host subcomponent.
   620  			//
   621  			// However, a number of databases including PostgreSQL and MongoDB
   622  			// permit a comma-separated list of hosts (with optional ports) in the
   623  			// host subcomponent.
   624  			//
   625  			// Since we historically permitted colons to appear in the host,
   626  			// enforce strict colons only for http and https URLs.
   627  			//
   628  			// See https://go.dev/issue/75223 and https://go.dev/issue/78077.
   629  			if scheme == "http" || scheme == "https" {
   630  				if urlstrictcolons.Value() == "0" {
   631  					urlstrictcolons.IncNonDefault()
   632  					i = lastColon
   633  				}
   634  			} else {
   635  				i = lastColon
   636  			}
   637  		}
   638  		colonPort := host[i:]
   639  		if !validOptionalPort(colonPort) {
   640  			return "", fmt.Errorf("invalid port %q after host", colonPort)
   641  		}
   642  	}
   643  
   644  	var err error
   645  	if host, err = unescape(host, encodeHost); err != nil {
   646  		return "", err
   647  	}
   648  	return host, nil
   649  }
   650  
   651  // setPath sets the Path and RawPath fields of the URL based on the provided
   652  // escaped path p. It maintains the invariant that RawPath is only specified
   653  // when it differs from the default encoding of the path.
   654  // For example:
   655  // - setPath("/foo/bar")   will set Path="/foo/bar" and RawPath=""
   656  // - setPath("/foo%2fbar") will set Path="/foo/bar" and RawPath="/foo%2fbar"
   657  // setPath will return an error only if the provided path contains an invalid
   658  // escaping.
   659  //
   660  // setPath should be an internal detail,
   661  // but widely used packages access it using linkname.
   662  // Notable members of the hall of shame include:
   663  //   - github.com/sagernet/sing
   664  //
   665  // Do not remove or change the type signature.
   666  // See go.dev/issue/67401.
   667  //
   668  //go:linkname badSetPath net/url.(*URL).setPath
   669  func (u *URL) setPath(p string) error {
   670  	path, err := unescape(p, encodePath)
   671  	if err != nil {
   672  		return err
   673  	}
   674  	u.Path = path
   675  	if escp := escape(path, encodePath); p == escp {
   676  		// Default encoding is fine.
   677  		u.RawPath = ""
   678  	} else {
   679  		u.RawPath = p
   680  	}
   681  	return nil
   682  }
   683  
   684  // for linkname because we cannot linkname methods directly
   685  func badSetPath(*URL, string) error
   686  
   687  // EscapedPath returns the escaped form of u.Path.
   688  // In general there are multiple possible escaped forms of any path.
   689  // EscapedPath returns u.RawPath when it is a valid escaping of u.Path.
   690  // Otherwise EscapedPath ignores u.RawPath and computes an escaped
   691  // form on its own.
   692  // The [URL.String] and [URL.RequestURI] methods use EscapedPath to construct
   693  // their results.
   694  // In general, code should call EscapedPath instead of
   695  // reading u.RawPath directly.
   696  func (u *URL) EscapedPath() string {
   697  	if u.RawPath != "" && validEncoded(u.RawPath, encodePath) {
   698  		p, err := unescape(u.RawPath, encodePath)
   699  		if err == nil && p == u.Path {
   700  			return u.RawPath
   701  		}
   702  	}
   703  	if u.Path == "*" {
   704  		return "*" // don't escape (Issue 11202)
   705  	}
   706  	return escape(u.Path, encodePath)
   707  }
   708  
   709  // validEncoded reports whether s is a valid encoded path or fragment,
   710  // according to mode.
   711  // It must not contain any bytes that require escaping during encoding.
   712  func validEncoded(s string, mode encoding) bool {
   713  	for i := 0; i < len(s); i++ {
   714  		// RFC 3986, Appendix A.
   715  		// pchar = unreserved / pct-encoded / sub-delims / ":" / "@".
   716  		// shouldEscape is not quite compliant with the RFC,
   717  		// so we check the sub-delims ourselves and let
   718  		// shouldEscape handle the others.
   719  		switch s[i] {
   720  		case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '@':
   721  			// ok
   722  		case '[', ']':
   723  			// ok - not specified in RFC 3986 but left alone by modern browsers
   724  		case '%':
   725  			// ok - percent encoded, will decode
   726  		default:
   727  			if shouldEscape(s[i], mode) {
   728  				return false
   729  			}
   730  		}
   731  	}
   732  	return true
   733  }
   734  
   735  // setFragment is like setPath but for Fragment/RawFragment.
   736  func (u *URL) setFragment(f string) error {
   737  	frag, err := unescape(f, encodeFragment)
   738  	if err != nil {
   739  		return err
   740  	}
   741  	u.Fragment = frag
   742  	if escf := escape(frag, encodeFragment); f == escf {
   743  		// Default encoding is fine.
   744  		u.RawFragment = ""
   745  	} else {
   746  		u.RawFragment = f
   747  	}
   748  	return nil
   749  }
   750  
   751  // EscapedFragment returns the escaped form of u.Fragment.
   752  // In general there are multiple possible escaped forms of any fragment.
   753  // EscapedFragment returns u.RawFragment when it is a valid escaping of u.Fragment.
   754  // Otherwise EscapedFragment ignores u.RawFragment and computes an escaped
   755  // form on its own.
   756  // The [URL.String] method uses EscapedFragment to construct its result.
   757  // In general, code should call EscapedFragment instead of
   758  // reading u.RawFragment directly.
   759  func (u *URL) EscapedFragment() string {
   760  	if u.RawFragment != "" && validEncoded(u.RawFragment, encodeFragment) {
   761  		f, err := unescape(u.RawFragment, encodeFragment)
   762  		if err == nil && f == u.Fragment {
   763  			return u.RawFragment
   764  		}
   765  	}
   766  	return escape(u.Fragment, encodeFragment)
   767  }
   768  
   769  // validOptionalPort reports whether port is either an empty string
   770  // or matches /^:\d*$/
   771  func validOptionalPort(port string) bool {
   772  	if port == "" {
   773  		return true
   774  	}
   775  	if port[0] != ':' {
   776  		return false
   777  	}
   778  	for _, b := range port[1:] {
   779  		if b < '0' || b > '9' {
   780  			return false
   781  		}
   782  	}
   783  	return true
   784  }
   785  
   786  // String reassembles the [URL] into a valid URL string.
   787  // The general form of the result is one of:
   788  //
   789  //	scheme:opaque?query#fragment
   790  //	scheme://userinfo@host/path?query#fragment
   791  //
   792  // If u.Opaque is non-empty, String uses the first form;
   793  // otherwise it uses the second form.
   794  // Any non-ASCII characters in host are escaped.
   795  // To obtain the path, String uses u.EscapedPath().
   796  //
   797  // In the second form, the following rules apply:
   798  //   - if u.Scheme is empty, scheme: is omitted.
   799  //   - if u.User is nil, userinfo@ is omitted.
   800  //   - if u.Host is empty, host/ is omitted.
   801  //   - if u.Scheme and u.Host are empty and u.User is nil,
   802  //     the entire scheme://userinfo@host/ is omitted.
   803  //   - if u.Host is non-empty and u.Path begins with a /,
   804  //     the form host/path does not add its own /.
   805  //   - if u.RawQuery is empty, ?query is omitted.
   806  //   - if u.Fragment is empty, #fragment is omitted.
   807  func (u *URL) String() string {
   808  	var buf strings.Builder
   809  
   810  	n := len(u.Scheme)
   811  	if u.Opaque != "" {
   812  		n += len(u.Opaque)
   813  	} else {
   814  		if !u.OmitHost && (u.Scheme != "" || u.Host != "" || u.User != nil) {
   815  			username := u.User.Username()
   816  			password, _ := u.User.Password()
   817  			n += len(username) + len(password) + len(u.Host)
   818  		}
   819  		n += len(u.Path)
   820  	}
   821  	n += len(u.RawQuery) + len(u.RawFragment)
   822  	n += len(":" + "//" + "//" + ":" + "@" + "/" + "./" + "?" + "#")
   823  	buf.Grow(n)
   824  
   825  	if u.Scheme != "" {
   826  		buf.WriteString(u.Scheme)
   827  		buf.WriteByte(':')
   828  	}
   829  	if u.Opaque != "" {
   830  		buf.WriteString(u.Opaque)
   831  	} else {
   832  		if u.Scheme != "" || u.Host != "" || u.User != nil {
   833  			if u.OmitHost && u.Host == "" && u.User == nil {
   834  				// omit empty host
   835  			} else {
   836  				if u.Host != "" || u.Path != "" || u.User != nil {
   837  					buf.WriteString("//")
   838  				}
   839  				if ui := u.User; ui != nil {
   840  					buf.WriteString(ui.String())
   841  					buf.WriteByte('@')
   842  				}
   843  				if h := u.Host; h != "" {
   844  					buf.WriteString(escape(h, encodeHost))
   845  				}
   846  			}
   847  		}
   848  		path := u.EscapedPath()
   849  		if u.OmitHost && u.Host == "" && u.User == nil && strings.HasPrefix(path, "//") {
   850  			// Escape the first / in a path starting with "//" and no authority
   851  			// so that re-parsing the URL doesn't turn the path into an authority
   852  			// (e.g., Path="//host/p" producing "http://host/p").
   853  			buf.WriteString("%2F")
   854  			path = path[1:]
   855  		}
   856  		if path != "" && path[0] != '/' && u.Host != "" {
   857  			buf.WriteByte('/')
   858  		}
   859  		if buf.Len() == 0 {
   860  			// RFC 3986 §4.2
   861  			// A path segment that contains a colon character (e.g., "this:that")
   862  			// cannot be used as the first segment of a relative-path reference, as
   863  			// it would be mistaken for a scheme name. Such a segment must be
   864  			// preceded by a dot-segment (e.g., "./this:that") to make a relative-
   865  			// path reference.
   866  			if segment, _, _ := strings.Cut(path, "/"); strings.Contains(segment, ":") {
   867  				buf.WriteString("./")
   868  			}
   869  		}
   870  		buf.WriteString(path)
   871  	}
   872  	if u.ForceQuery || u.RawQuery != "" {
   873  		buf.WriteByte('?')
   874  		buf.WriteString(u.RawQuery)
   875  	}
   876  	if u.Fragment != "" {
   877  		buf.WriteByte('#')
   878  		buf.WriteString(u.EscapedFragment())
   879  	}
   880  	return buf.String()
   881  }
   882  
   883  // Redacted is like [URL.String] but replaces any password with "xxxxx".
   884  // Only the password in u.User is redacted.
   885  func (u *URL) Redacted() string {
   886  	if u == nil {
   887  		return ""
   888  	}
   889  
   890  	ru := *u
   891  	if _, has := ru.User.Password(); has {
   892  		ru.User = UserPassword(ru.User.Username(), "xxxxx")
   893  	}
   894  	return ru.String()
   895  }
   896  
   897  // Values maps a string key to a list of values.
   898  // It is typically used for query parameters and form values.
   899  // Unlike in the http.Header map, the keys in a Values map
   900  // are case-sensitive.
   901  type Values map[string][]string
   902  
   903  // Get gets the first value associated with the given key.
   904  // If there are no values associated with the key, Get returns
   905  // the empty string. To access multiple values, use the map
   906  // directly.
   907  func (v Values) Get(key string) string {
   908  	vs := v[key]
   909  	if len(vs) == 0 {
   910  		return ""
   911  	}
   912  	return vs[0]
   913  }
   914  
   915  // Set sets the key to value. It replaces any existing
   916  // values.
   917  func (v Values) Set(key, value string) {
   918  	v[key] = []string{value}
   919  }
   920  
   921  // Add adds the value to key. It appends to any existing
   922  // values associated with key.
   923  func (v Values) Add(key, value string) {
   924  	v[key] = append(v[key], value)
   925  }
   926  
   927  // Del deletes the values associated with key.
   928  func (v Values) Del(key string) {
   929  	delete(v, key)
   930  }
   931  
   932  // Has checks whether a given key is set.
   933  func (v Values) Has(key string) bool {
   934  	_, ok := v[key]
   935  	return ok
   936  }
   937  
   938  // Clone creates a deep copy of the subject [Values].
   939  func (vs Values) Clone() Values {
   940  	if vs == nil {
   941  		return nil
   942  	}
   943  
   944  	newVals := make(Values, len(vs))
   945  	for k, v := range vs {
   946  		newVals[k] = slices.Clone(v)
   947  	}
   948  	return newVals
   949  }
   950  
   951  // ParseQuery parses the URL-encoded query string and returns
   952  // a map listing the values specified for each key.
   953  // ParseQuery always returns a non-nil map containing all the
   954  // valid query parameters found; err describes the first decoding error
   955  // encountered, if any.
   956  //
   957  // Query is expected to be a list of key=value settings separated by ampersands.
   958  // A setting without an equals sign is interpreted as a key set to an empty
   959  // value.
   960  // Settings containing a non-URL-encoded semicolon are considered invalid.
   961  func ParseQuery(query string) (Values, error) {
   962  	m := make(Values)
   963  	err := parseQuery(m, query)
   964  	return m, err
   965  }
   966  
   967  var urlmaxqueryparams = godebug.New("urlmaxqueryparams")
   968  
   969  // Keep this in sync with net/http/httputil.
   970  const defaultMaxParams = 10000
   971  
   972  func urlParamsWithinMax(params int) bool {
   973  	withinDefaultMax := params <= defaultMaxParams
   974  	if urlmaxqueryparams.Value() == "" {
   975  		return withinDefaultMax
   976  	}
   977  	customMax, err := strconv.Atoi(urlmaxqueryparams.Value())
   978  	if err != nil {
   979  		return withinDefaultMax
   980  	}
   981  	withinCustomMax := customMax == 0 || params < customMax
   982  	if withinDefaultMax != withinCustomMax {
   983  		urlmaxqueryparams.IncNonDefault()
   984  	}
   985  	return withinCustomMax
   986  }
   987  
   988  func parseQuery(m Values, query string) (err error) {
   989  	if !urlParamsWithinMax(strings.Count(query, "&") + 1) {
   990  		return errors.New("number of URL query parameters exceeded limit")
   991  	}
   992  	for query != "" {
   993  		var key string
   994  		key, query, _ = strings.Cut(query, "&")
   995  		if strings.Contains(key, ";") {
   996  			err = fmt.Errorf("invalid semicolon separator in query")
   997  			continue
   998  		}
   999  		if key == "" {
  1000  			continue
  1001  		}
  1002  		key, value, _ := strings.Cut(key, "=")
  1003  		key, err1 := QueryUnescape(key)
  1004  		if err1 != nil {
  1005  			if err == nil {
  1006  				err = err1
  1007  			}
  1008  			continue
  1009  		}
  1010  		value, err1 = QueryUnescape(value)
  1011  		if err1 != nil {
  1012  			if err == nil {
  1013  				err = err1
  1014  			}
  1015  			continue
  1016  		}
  1017  		m[key] = append(m[key], value)
  1018  	}
  1019  	return err
  1020  }
  1021  
  1022  // Encode encodes the values into “URL encoded” form
  1023  // ("bar=baz&foo=quux") sorted by key.
  1024  func (v Values) Encode() string {
  1025  	if len(v) == 0 {
  1026  		return ""
  1027  	}
  1028  	var buf strings.Builder
  1029  	// To minimize allocations, we eschew iterators and pre-size the slice in
  1030  	// which we collect v's keys.
  1031  	keys := make([]string, len(v))
  1032  	var i int
  1033  	for k := range v {
  1034  		keys[i] = k
  1035  		i++
  1036  	}
  1037  	slices.Sort(keys)
  1038  	for _, k := range keys {
  1039  		vs := v[k]
  1040  		keyEscaped := QueryEscape(k)
  1041  		for _, v := range vs {
  1042  			if buf.Len() > 0 {
  1043  				buf.WriteByte('&')
  1044  			}
  1045  			buf.WriteString(keyEscaped)
  1046  			buf.WriteByte('=')
  1047  			buf.WriteString(QueryEscape(v))
  1048  		}
  1049  	}
  1050  	return buf.String()
  1051  }
  1052  
  1053  // resolvePath applies special path segments from refs and applies
  1054  // them to base, per RFC 3986.
  1055  func resolvePath(base, ref string) string {
  1056  	var full string
  1057  	if ref == "" {
  1058  		full = base
  1059  	} else if ref[0] != '/' {
  1060  		i := strings.LastIndex(base, "/")
  1061  		full = base[:i+1] + ref
  1062  	} else {
  1063  		full = ref
  1064  	}
  1065  	if full == "" {
  1066  		return ""
  1067  	}
  1068  
  1069  	var (
  1070  		elem string
  1071  		dst  strings.Builder
  1072  	)
  1073  	first := true
  1074  	remaining := full
  1075  	// We want to return a leading '/', so write it now.
  1076  	dst.WriteByte('/')
  1077  	found := true
  1078  	for found {
  1079  		elem, remaining, found = strings.Cut(remaining, "/")
  1080  		if elem == "." {
  1081  			first = false
  1082  			// drop
  1083  			continue
  1084  		}
  1085  
  1086  		if elem == ".." {
  1087  			// Ignore the leading '/' we already wrote.
  1088  			str := dst.String()[1:]
  1089  			index := strings.LastIndexByte(str, '/')
  1090  
  1091  			dst.Reset()
  1092  			dst.WriteByte('/')
  1093  			if index == -1 {
  1094  				first = true
  1095  			} else {
  1096  				dst.WriteString(str[:index])
  1097  			}
  1098  		} else {
  1099  			if !first {
  1100  				dst.WriteByte('/')
  1101  			}
  1102  			dst.WriteString(elem)
  1103  			first = false
  1104  		}
  1105  	}
  1106  
  1107  	if elem == "." || elem == ".." {
  1108  		dst.WriteByte('/')
  1109  	}
  1110  
  1111  	// We wrote an initial '/', but we don't want two.
  1112  	r := dst.String()
  1113  	if len(r) > 1 && r[1] == '/' {
  1114  		r = r[1:]
  1115  	}
  1116  	return r
  1117  }
  1118  
  1119  // IsAbs reports whether the [URL] is absolute.
  1120  // Absolute means that it has a non-empty scheme.
  1121  func (u *URL) IsAbs() bool {
  1122  	return u.Scheme != ""
  1123  }
  1124  
  1125  // Parse parses a [URL] in the context of the receiver. The provided URL
  1126  // may be relative or absolute. Parse returns nil, err on parse
  1127  // failure, otherwise its return value is the same as [URL.ResolveReference].
  1128  func (u *URL) Parse(ref string) (*URL, error) {
  1129  	refURL, err := Parse(ref)
  1130  	if err != nil {
  1131  		return nil, err
  1132  	}
  1133  	return u.ResolveReference(refURL), nil
  1134  }
  1135  
  1136  // ResolveReference resolves a URI reference to an absolute URI from
  1137  // an absolute base URI u, per RFC 3986 Section 5.2. The URI reference
  1138  // may be relative or absolute. ResolveReference always returns a new
  1139  // [URL] instance, even if the returned URL is identical to either the
  1140  // base or reference. If ref is an absolute URL, then ResolveReference
  1141  // ignores base and returns a copy of ref.
  1142  func (u *URL) ResolveReference(ref *URL) *URL {
  1143  	url := *ref
  1144  	if ref.Scheme == "" {
  1145  		url.Scheme = u.Scheme
  1146  	}
  1147  	if ref.Scheme != "" || ref.Host != "" || ref.User != nil {
  1148  		// The "absoluteURI" or "net_path" cases.
  1149  		// We can ignore the error from setPath since we know we provided a
  1150  		// validly-escaped path.
  1151  		url.setPath(resolvePath(ref.EscapedPath(), ""))
  1152  		return &url
  1153  	}
  1154  	if ref.Opaque != "" {
  1155  		url.User = nil
  1156  		url.Host = ""
  1157  		url.Path = ""
  1158  		return &url
  1159  	}
  1160  	if ref.Path == "" && !ref.ForceQuery && ref.RawQuery == "" {
  1161  		url.RawQuery = u.RawQuery
  1162  		if ref.Fragment == "" {
  1163  			url.Fragment = u.Fragment
  1164  			url.RawFragment = u.RawFragment
  1165  		}
  1166  	}
  1167  	if ref.Path == "" && u.Opaque != "" {
  1168  		url.Opaque = u.Opaque
  1169  		url.User = nil
  1170  		url.Host = ""
  1171  		url.Path = ""
  1172  		return &url
  1173  	}
  1174  	// The "abs_path" or "rel_path" cases.
  1175  	url.Host = u.Host
  1176  	url.User = u.User
  1177  	url.setPath(resolvePath(u.EscapedPath(), ref.EscapedPath()))
  1178  	return &url
  1179  }
  1180  
  1181  // Query parses RawQuery and returns the corresponding values.
  1182  // It silently discards malformed value pairs.
  1183  // To check errors use [ParseQuery].
  1184  func (u *URL) Query() Values {
  1185  	v, _ := ParseQuery(u.RawQuery)
  1186  	return v
  1187  }
  1188  
  1189  // RequestURI returns the encoded path?query or opaque?query
  1190  // string that would be used in an HTTP request for u.
  1191  func (u *URL) RequestURI() string {
  1192  	result := u.Opaque
  1193  	if result == "" {
  1194  		result = u.EscapedPath()
  1195  		if result == "" {
  1196  			result = "/"
  1197  		}
  1198  	} else {
  1199  		if strings.HasPrefix(result, "//") {
  1200  			result = u.Scheme + ":" + result
  1201  		}
  1202  	}
  1203  	if u.ForceQuery || u.RawQuery != "" {
  1204  		result += "?" + u.RawQuery
  1205  	}
  1206  	return result
  1207  }
  1208  
  1209  // Hostname returns u.Host, stripping any valid port number if present.
  1210  //
  1211  // If the result is enclosed in square brackets, as literal IPv6 addresses are,
  1212  // the square brackets are removed from the result.
  1213  func (u *URL) Hostname() string {
  1214  	host, _ := splitHostPort(u.Host)
  1215  	return host
  1216  }
  1217  
  1218  // Port returns the port part of u.Host, without the leading colon.
  1219  //
  1220  // If u.Host doesn't contain a valid numeric port, Port returns an empty string.
  1221  func (u *URL) Port() string {
  1222  	_, port := splitHostPort(u.Host)
  1223  	return port
  1224  }
  1225  
  1226  // splitHostPort separates host and port. If the port is not valid, it returns
  1227  // the entire input as host, and it doesn't check the validity of the host.
  1228  // Unlike net.SplitHostPort, but per RFC 3986, it requires ports to be numeric.
  1229  func splitHostPort(hostPort string) (host, port string) {
  1230  	host = hostPort
  1231  
  1232  	colon := strings.LastIndexByte(host, ':')
  1233  	if colon != -1 && validOptionalPort(host[colon:]) {
  1234  		host, port = host[:colon], host[colon+1:]
  1235  	}
  1236  
  1237  	if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
  1238  		host = host[1 : len(host)-1]
  1239  	}
  1240  
  1241  	return
  1242  }
  1243  
  1244  // Marshaling interface implementations.
  1245  // Would like to implement MarshalText/UnmarshalText but that will change the JSON representation of URLs.
  1246  
  1247  func (u *URL) MarshalBinary() (text []byte, err error) {
  1248  	return u.AppendBinary(nil)
  1249  }
  1250  
  1251  func (u *URL) AppendBinary(b []byte) ([]byte, error) {
  1252  	return append(b, u.String()...), nil
  1253  }
  1254  
  1255  func (u *URL) UnmarshalBinary(text []byte) error {
  1256  	u1, err := Parse(string(text))
  1257  	if err != nil {
  1258  		return err
  1259  	}
  1260  	*u = *u1
  1261  	return nil
  1262  }
  1263  
  1264  // JoinPath returns a new [URL] with the provided path elements joined to
  1265  // any existing path and the resulting path cleaned of any ./ or ../ elements.
  1266  // Any sequences of multiple / characters will be reduced to a single /.
  1267  // Path elements must already be in escaped form, as produced by [PathEscape].
  1268  func (u *URL) JoinPath(elem ...string) *URL {
  1269  	url, _ := u.joinPath(elem...)
  1270  	return url
  1271  }
  1272  
  1273  func (u *URL) joinPath(elem ...string) (*URL, error) {
  1274  	elem = append([]string{u.EscapedPath()}, elem...)
  1275  	var p string
  1276  	if !strings.HasPrefix(elem[0], "/") {
  1277  		// Return a relative path if u is relative,
  1278  		// but ensure that it contains no ../ elements.
  1279  		elem[0] = "/" + elem[0]
  1280  		p = path.Join(elem...)[1:]
  1281  	} else {
  1282  		p = path.Join(elem...)
  1283  	}
  1284  	// path.Join will remove any trailing slashes.
  1285  	// Preserve at least one.
  1286  	if strings.HasSuffix(elem[len(elem)-1], "/") && !strings.HasSuffix(p, "/") {
  1287  		p += "/"
  1288  	}
  1289  	url := *u
  1290  	err := url.setPath(p)
  1291  	return &url, err
  1292  }
  1293  
  1294  // validUserinfo reports whether s is a valid userinfo string per RFC 3986
  1295  // Section 3.2.1:
  1296  //
  1297  //	userinfo    = *( unreserved / pct-encoded / sub-delims / ":" )
  1298  //	unreserved  = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1299  //	sub-delims  = "!" / "$" / "&" / "'" / "(" / ")"
  1300  //	              / "*" / "+" / "," / ";" / "="
  1301  //
  1302  // It doesn't validate pct-encoded. The caller does that via func unescape.
  1303  func validUserinfo(s string) bool {
  1304  	for _, r := range s {
  1305  		if 'A' <= r && r <= 'Z' {
  1306  			continue
  1307  		}
  1308  		if 'a' <= r && r <= 'z' {
  1309  			continue
  1310  		}
  1311  		if '0' <= r && r <= '9' {
  1312  			continue
  1313  		}
  1314  		switch r {
  1315  		case '-', '.', '_', ':', '~', '!', '$', '&', '\'',
  1316  			'(', ')', '*', '+', ',', ';', '=', '%':
  1317  			continue
  1318  		case '@':
  1319  			// `RFC 3986 section 3.2.1` does not allow '@' in userinfo.
  1320  			// It is a delimiter between userinfo and host.
  1321  			// However, URLs are diverse, and in some cases,
  1322  			// the userinfo may contain an '@' character,
  1323  			// for example, in "http://username:p@ssword@google.com",
  1324  			// the string "username:p@ssword" should be treated as valid userinfo.
  1325  			// Ref:
  1326  			//   https://go.dev/issue/3439
  1327  			//   https://go.dev/issue/22655
  1328  			continue
  1329  		default:
  1330  			return false
  1331  		}
  1332  	}
  1333  	return true
  1334  }
  1335  
  1336  // stringContainsCTLByte reports whether s contains any ASCII control character.
  1337  func stringContainsCTLByte(s string) bool {
  1338  	for i := 0; i < len(s); i++ {
  1339  		b := s[i]
  1340  		if b < ' ' || b == 0x7f {
  1341  			return true
  1342  		}
  1343  	}
  1344  	return false
  1345  }
  1346  
  1347  // JoinPath returns a [URL] string with the provided path elements joined to
  1348  // the existing path of base and the resulting path cleaned of any ./ or ../ elements.
  1349  // Path elements must already be in escaped form, as produced by [PathEscape].
  1350  func JoinPath(base string, elem ...string) (result string, err error) {
  1351  	url, err := Parse(base)
  1352  	if err != nil {
  1353  		return
  1354  	}
  1355  	res, err := url.joinPath(elem...)
  1356  	if err != nil {
  1357  		return "", err
  1358  	}
  1359  	return res.String(), nil
  1360  }
  1361  
  1362  // Clone creates a deep copy of the fields of the subject [URL].
  1363  func (u *URL) Clone() *URL {
  1364  	if u == nil {
  1365  		return nil
  1366  	}
  1367  
  1368  	uc := new(*u)
  1369  	if u.User != nil {
  1370  		uc.User = new(*u.User)
  1371  	}
  1372  	return uc
  1373  }
  1374  

View as plain text