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

View as plain text