...

Source file src/net/url/url.go

Documentation: net/url

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

View as plain text