...

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  // The Host field contains the host and port subcomponents of the URL.
   352  // When the port is present, it is separated from the host with a colon.
   353  // When the host is an IPv6 address, it must be enclosed in square brackets:
   354  // "[fe80::1]:80". The [net.JoinHostPort] function combines a host and port
   355  // into a string suitable for the Host field, adding square brackets to
   356  // the host when necessary.
   357  //
   358  // Note that the Path field is stored in decoded form: /%47%6f%2f becomes /Go/.
   359  // A consequence is that it is impossible to tell which slashes in the Path were
   360  // slashes in the raw URL and which were %2f. This distinction is rarely important,
   361  // but when it is, the code should use the [URL.EscapedPath] method, which preserves
   362  // the original encoding of Path.
   363  //
   364  // The RawPath field is an optional field which is only set when the default
   365  // encoding of Path is different from the escaped path. See the EscapedPath method
   366  // for more details.
   367  //
   368  // URL's String method uses the EscapedPath method to obtain the path.
   369  type URL struct {
   370  	Scheme      string
   371  	Opaque      string    // encoded opaque data
   372  	User        *Userinfo // username and password information
   373  	Host        string    // host or host:port (see Hostname and Port methods)
   374  	Path        string    // path (relative paths may omit leading slash)
   375  	RawPath     string    // encoded path hint (see EscapedPath method)
   376  	OmitHost    bool      // do not emit empty host (authority)
   377  	ForceQuery  bool      // append a query ('?') even if RawQuery is empty
   378  	RawQuery    string    // encoded query values, without '?'
   379  	Fragment    string    // fragment for references, without '#'
   380  	RawFragment string    // encoded fragment hint (see EscapedFragment method)
   381  }
   382  
   383  // User returns a [Userinfo] containing the provided username
   384  // and no password set.
   385  func User(username string) *Userinfo {
   386  	return &Userinfo{username, "", false}
   387  }
   388  
   389  // UserPassword returns a [Userinfo] containing the provided username
   390  // and password.
   391  //
   392  // This functionality should only be used with legacy web sites.
   393  // RFC 2396 warns that interpreting Userinfo this way
   394  // “is NOT RECOMMENDED, because the passing of authentication
   395  // information in clear text (such as URI) has proven to be a
   396  // security risk in almost every case where it has been used.”
   397  func UserPassword(username, password string) *Userinfo {
   398  	return &Userinfo{username, password, true}
   399  }
   400  
   401  // The Userinfo type is an immutable encapsulation of username and
   402  // password details for a [URL]. An existing Userinfo value is guaranteed
   403  // to have a username set (potentially empty, as allowed by RFC 2396),
   404  // and optionally a password.
   405  type Userinfo struct {
   406  	username    string
   407  	password    string
   408  	passwordSet bool
   409  }
   410  
   411  // Username returns the username.
   412  func (u *Userinfo) Username() string {
   413  	if u == nil {
   414  		return ""
   415  	}
   416  	return u.username
   417  }
   418  
   419  // Password returns the password in case it is set, and whether it is set.
   420  func (u *Userinfo) Password() (string, bool) {
   421  	if u == nil {
   422  		return "", false
   423  	}
   424  	return u.password, u.passwordSet
   425  }
   426  
   427  // String returns the encoded userinfo information in the standard form
   428  // of "username[:password]".
   429  func (u *Userinfo) String() string {
   430  	if u == nil {
   431  		return ""
   432  	}
   433  	s := escape(u.username, encodeUserPassword)
   434  	if u.passwordSet {
   435  		s += ":" + escape(u.password, encodeUserPassword)
   436  	}
   437  	return s
   438  }
   439  
   440  // Maybe rawURL is of the form scheme:path.
   441  // (Scheme must be [a-zA-Z][a-zA-Z0-9+.-]*)
   442  // If so, return scheme, path; else return "", rawURL.
   443  func getScheme(rawURL string) (scheme, path string, err error) {
   444  	for i := 0; i < len(rawURL); i++ {
   445  		c := rawURL[i]
   446  		switch {
   447  		case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z':
   448  		// do nothing
   449  		case '0' <= c && c <= '9' || c == '+' || c == '-' || c == '.':
   450  			if i == 0 {
   451  				return "", rawURL, nil
   452  			}
   453  		case c == ':':
   454  			if i == 0 {
   455  				return "", "", errors.New("missing protocol scheme")
   456  			}
   457  			return rawURL[:i], rawURL[i+1:], nil
   458  		default:
   459  			// we have encountered an invalid character,
   460  			// so there is no valid scheme
   461  			return "", rawURL, nil
   462  		}
   463  	}
   464  	return "", rawURL, nil
   465  }
   466  
   467  // Parse parses a raw url into a [URL] structure.
   468  //
   469  // The url may be relative (a path, without a host) or absolute
   470  // (starting with a scheme). Trying to parse a hostname and path
   471  // without a scheme is invalid but may not necessarily return an
   472  // error, due to parsing ambiguities.
   473  func Parse(rawURL string) (*URL, error) {
   474  	// Cut off #frag
   475  	u, frag, _ := strings.Cut(rawURL, "#")
   476  	url, err := parse(u, false)
   477  	if err != nil {
   478  		return nil, &Error{"parse", u, err}
   479  	}
   480  	if frag == "" {
   481  		return url, nil
   482  	}
   483  	if err = url.setFragment(frag); err != nil {
   484  		return nil, &Error{"parse", rawURL, err}
   485  	}
   486  	return url, nil
   487  }
   488  
   489  // ParseRequestURI parses a raw url into a [URL] structure. It assumes that
   490  // url was received in an HTTP request, so the url is interpreted
   491  // only as an absolute URI or an absolute path.
   492  // The string url is assumed not to have a #fragment suffix.
   493  // (Web browsers strip #fragment before sending the URL to a web server.)
   494  func ParseRequestURI(rawURL string) (*URL, error) {
   495  	url, err := parse(rawURL, true)
   496  	if err != nil {
   497  		return nil, &Error{"parse", rawURL, err}
   498  	}
   499  	return url, nil
   500  }
   501  
   502  // parse parses a URL from a string in one of two contexts. If
   503  // viaRequest is true, the URL is assumed to have arrived via an HTTP request,
   504  // in which case only absolute URLs or path-absolute relative URLs are allowed.
   505  // If viaRequest is false, all forms of relative URLs are allowed.
   506  func parse(rawURL string, viaRequest bool) (*URL, error) {
   507  	var rest string
   508  	var err error
   509  
   510  	if stringContainsCTLByte(rawURL) {
   511  		return nil, errors.New("net/url: invalid control character in URL")
   512  	}
   513  
   514  	if rawURL == "" && viaRequest {
   515  		return nil, errors.New("empty url")
   516  	}
   517  	url := new(URL)
   518  
   519  	if rawURL == "*" {
   520  		url.Path = "*"
   521  		return url, nil
   522  	}
   523  
   524  	// Split off possible leading "http:", "mailto:", etc.
   525  	// Cannot contain escaped characters.
   526  	if url.Scheme, rest, err = getScheme(rawURL); err != nil {
   527  		return nil, err
   528  	}
   529  	url.Scheme = strings.ToLower(url.Scheme)
   530  
   531  	if strings.HasSuffix(rest, "?") && strings.Count(rest, "?") == 1 {
   532  		url.ForceQuery = true
   533  		rest = rest[:len(rest)-1]
   534  	} else {
   535  		rest, url.RawQuery, _ = strings.Cut(rest, "?")
   536  	}
   537  
   538  	if !strings.HasPrefix(rest, "/") {
   539  		if url.Scheme != "" {
   540  			// We consider rootless paths per RFC 3986 as opaque.
   541  			url.Opaque = rest
   542  			return url, nil
   543  		}
   544  		if viaRequest {
   545  			return nil, errors.New("invalid URI for request")
   546  		}
   547  
   548  		// Avoid confusion with malformed schemes, like cache_object:foo/bar.
   549  		// See golang.org/issue/16822.
   550  		//
   551  		// RFC 3986, §3.3:
   552  		// In addition, a URI reference (Section 4.1) may be a relative-path reference,
   553  		// in which case the first path segment cannot contain a colon (":") character.
   554  		if segment, _, _ := strings.Cut(rest, "/"); strings.Contains(segment, ":") {
   555  			// First path segment has colon. Not allowed in relative URL.
   556  			return nil, errors.New("first path segment in URL cannot contain colon")
   557  		}
   558  	}
   559  
   560  	if (url.Scheme != "" || !viaRequest && !strings.HasPrefix(rest, "///")) && strings.HasPrefix(rest, "//") {
   561  		var authority string
   562  		authority, rest = rest[2:], ""
   563  		if i := strings.Index(authority, "/"); i >= 0 {
   564  			authority, rest = authority[:i], authority[i:]
   565  		}
   566  		url.User, url.Host, err = parseAuthority(authority)
   567  		if err != nil {
   568  			return nil, err
   569  		}
   570  	} else if url.Scheme != "" && strings.HasPrefix(rest, "/") {
   571  		// OmitHost is set to true when rawURL has an empty host (authority).
   572  		// See golang.org/issue/46059.
   573  		url.OmitHost = true
   574  	}
   575  
   576  	// Set Path and, optionally, RawPath.
   577  	// RawPath is a hint of the encoding of Path. We don't want to set it if
   578  	// the default escaping of Path is equivalent, to help make sure that people
   579  	// don't rely on it in general.
   580  	if err := url.setPath(rest); err != nil {
   581  		return nil, err
   582  	}
   583  	return url, nil
   584  }
   585  
   586  func parseAuthority(authority string) (user *Userinfo, host string, err error) {
   587  	i := strings.LastIndex(authority, "@")
   588  	if i < 0 {
   589  		host, err = parseHost(authority)
   590  	} else {
   591  		host, err = parseHost(authority[i+1:])
   592  	}
   593  	if err != nil {
   594  		return nil, "", err
   595  	}
   596  	if i < 0 {
   597  		return nil, host, nil
   598  	}
   599  	userinfo := authority[:i]
   600  	if !validUserinfo(userinfo) {
   601  		return nil, "", errors.New("net/url: invalid userinfo")
   602  	}
   603  	if !strings.Contains(userinfo, ":") {
   604  		if userinfo, err = unescape(userinfo, encodeUserPassword); err != nil {
   605  			return nil, "", err
   606  		}
   607  		user = User(userinfo)
   608  	} else {
   609  		username, password, _ := strings.Cut(userinfo, ":")
   610  		if username, err = unescape(username, encodeUserPassword); err != nil {
   611  			return nil, "", err
   612  		}
   613  		if password, err = unescape(password, encodeUserPassword); err != nil {
   614  			return nil, "", err
   615  		}
   616  		user = UserPassword(username, password)
   617  	}
   618  	return user, host, nil
   619  }
   620  
   621  // parseHost parses host as an authority without user
   622  // information. That is, as host[:port].
   623  func parseHost(host string) (string, error) {
   624  	if strings.HasPrefix(host, "[") {
   625  		// Parse an IP-Literal in RFC 3986 and RFC 6874.
   626  		// E.g., "[fe80::1]", "[fe80::1%25en0]", "[fe80::1]:80".
   627  		i := strings.LastIndex(host, "]")
   628  		if i < 0 {
   629  			return "", errors.New("missing ']' in host")
   630  		}
   631  		colonPort := host[i+1:]
   632  		if !validOptionalPort(colonPort) {
   633  			return "", fmt.Errorf("invalid port %q after host", colonPort)
   634  		}
   635  
   636  		// RFC 6874 defines that %25 (%-encoded percent) introduces
   637  		// the zone identifier, and the zone identifier can use basically
   638  		// any %-encoding it likes. That's different from the host, which
   639  		// can only %-encode non-ASCII bytes.
   640  		// We do impose some restrictions on the zone, to avoid stupidity
   641  		// like newlines.
   642  		zone := strings.Index(host[:i], "%25")
   643  		if zone >= 0 {
   644  			host1, err := unescape(host[:zone], encodeHost)
   645  			if err != nil {
   646  				return "", err
   647  			}
   648  			host2, err := unescape(host[zone:i], encodeZone)
   649  			if err != nil {
   650  				return "", err
   651  			}
   652  			host3, err := unescape(host[i:], encodeHost)
   653  			if err != nil {
   654  				return "", err
   655  			}
   656  			return host1 + host2 + host3, nil
   657  		}
   658  	} else if i := strings.LastIndex(host, ":"); i != -1 {
   659  		colonPort := host[i:]
   660  		if !validOptionalPort(colonPort) {
   661  			return "", fmt.Errorf("invalid port %q after host", colonPort)
   662  		}
   663  	}
   664  
   665  	var err error
   666  	if host, err = unescape(host, encodeHost); err != nil {
   667  		return "", err
   668  	}
   669  	return host, nil
   670  }
   671  
   672  // setPath sets the Path and RawPath fields of the URL based on the provided
   673  // escaped path p. It maintains the invariant that RawPath is only specified
   674  // when it differs from the default encoding of the path.
   675  // For example:
   676  // - setPath("/foo/bar")   will set Path="/foo/bar" and RawPath=""
   677  // - setPath("/foo%2fbar") will set Path="/foo/bar" and RawPath="/foo%2fbar"
   678  // setPath will return an error only if the provided path contains an invalid
   679  // escaping.
   680  func (u *URL) setPath(p string) error {
   681  	path, err := unescape(p, encodePath)
   682  	if err != nil {
   683  		return err
   684  	}
   685  	u.Path = path
   686  	if escp := escape(path, encodePath); p == escp {
   687  		// Default encoding is fine.
   688  		u.RawPath = ""
   689  	} else {
   690  		u.RawPath = p
   691  	}
   692  	return nil
   693  }
   694  
   695  // EscapedPath returns the escaped form of u.Path.
   696  // In general there are multiple possible escaped forms of any path.
   697  // EscapedPath returns u.RawPath when it is a valid escaping of u.Path.
   698  // Otherwise EscapedPath ignores u.RawPath and computes an escaped
   699  // form on its own.
   700  // The [URL.String] and [URL.RequestURI] methods use EscapedPath to construct
   701  // their results.
   702  // In general, code should call EscapedPath instead of
   703  // reading u.RawPath directly.
   704  func (u *URL) EscapedPath() string {
   705  	if u.RawPath != "" && validEncoded(u.RawPath, encodePath) {
   706  		p, err := unescape(u.RawPath, encodePath)
   707  		if err == nil && p == u.Path {
   708  			return u.RawPath
   709  		}
   710  	}
   711  	if u.Path == "*" {
   712  		return "*" // don't escape (Issue 11202)
   713  	}
   714  	return escape(u.Path, encodePath)
   715  }
   716  
   717  // validEncoded reports whether s is a valid encoded path or fragment,
   718  // according to mode.
   719  // It must not contain any bytes that require escaping during encoding.
   720  func validEncoded(s string, mode encoding) bool {
   721  	for i := 0; i < len(s); i++ {
   722  		// RFC 3986, Appendix A.
   723  		// pchar = unreserved / pct-encoded / sub-delims / ":" / "@".
   724  		// shouldEscape is not quite compliant with the RFC,
   725  		// so we check the sub-delims ourselves and let
   726  		// shouldEscape handle the others.
   727  		switch s[i] {
   728  		case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '@':
   729  			// ok
   730  		case '[', ']':
   731  			// ok - not specified in RFC 3986 but left alone by modern browsers
   732  		case '%':
   733  			// ok - percent encoded, will decode
   734  		default:
   735  			if shouldEscape(s[i], mode) {
   736  				return false
   737  			}
   738  		}
   739  	}
   740  	return true
   741  }
   742  
   743  // setFragment is like setPath but for Fragment/RawFragment.
   744  func (u *URL) setFragment(f string) error {
   745  	frag, err := unescape(f, encodeFragment)
   746  	if err != nil {
   747  		return err
   748  	}
   749  	u.Fragment = frag
   750  	if escf := escape(frag, encodeFragment); f == escf {
   751  		// Default encoding is fine.
   752  		u.RawFragment = ""
   753  	} else {
   754  		u.RawFragment = f
   755  	}
   756  	return nil
   757  }
   758  
   759  // EscapedFragment returns the escaped form of u.Fragment.
   760  // In general there are multiple possible escaped forms of any fragment.
   761  // EscapedFragment returns u.RawFragment when it is a valid escaping of u.Fragment.
   762  // Otherwise EscapedFragment ignores u.RawFragment and computes an escaped
   763  // form on its own.
   764  // The [URL.String] method uses EscapedFragment to construct its result.
   765  // In general, code should call EscapedFragment instead of
   766  // reading u.RawFragment directly.
   767  func (u *URL) EscapedFragment() string {
   768  	if u.RawFragment != "" && validEncoded(u.RawFragment, encodeFragment) {
   769  		f, err := unescape(u.RawFragment, encodeFragment)
   770  		if err == nil && f == u.Fragment {
   771  			return u.RawFragment
   772  		}
   773  	}
   774  	return escape(u.Fragment, encodeFragment)
   775  }
   776  
   777  // validOptionalPort reports whether port is either an empty string
   778  // or matches /^:\d*$/
   779  func validOptionalPort(port string) bool {
   780  	if port == "" {
   781  		return true
   782  	}
   783  	if port[0] != ':' {
   784  		return false
   785  	}
   786  	for _, b := range port[1:] {
   787  		if b < '0' || b > '9' {
   788  			return false
   789  		}
   790  	}
   791  	return true
   792  }
   793  
   794  // String reassembles the [URL] into a valid URL string.
   795  // The general form of the result is one of:
   796  //
   797  //	scheme:opaque?query#fragment
   798  //	scheme://userinfo@host/path?query#fragment
   799  //
   800  // If u.Opaque is non-empty, String uses the first form;
   801  // otherwise it uses the second form.
   802  // Any non-ASCII characters in host are escaped.
   803  // To obtain the path, String uses u.EscapedPath().
   804  //
   805  // In the second form, the following rules apply:
   806  //   - if u.Scheme is empty, scheme: is omitted.
   807  //   - if u.User is nil, userinfo@ is omitted.
   808  //   - if u.Host is empty, host/ is omitted.
   809  //   - if u.Scheme and u.Host are empty and u.User is nil,
   810  //     the entire scheme://userinfo@host/ is omitted.
   811  //   - if u.Host is non-empty and u.Path begins with a /,
   812  //     the form host/path does not add its own /.
   813  //   - if u.RawQuery is empty, ?query is omitted.
   814  //   - if u.Fragment is empty, #fragment is omitted.
   815  func (u *URL) String() string {
   816  	var buf strings.Builder
   817  	if u.Scheme != "" {
   818  		buf.WriteString(u.Scheme)
   819  		buf.WriteByte(':')
   820  	}
   821  	if u.Opaque != "" {
   822  		buf.WriteString(u.Opaque)
   823  	} else {
   824  		if u.Scheme != "" || u.Host != "" || u.User != nil {
   825  			if u.OmitHost && u.Host == "" && u.User == nil {
   826  				// omit empty host
   827  			} else {
   828  				if u.Host != "" || u.Path != "" || u.User != nil {
   829  					buf.WriteString("//")
   830  				}
   831  				if ui := u.User; ui != nil {
   832  					buf.WriteString(ui.String())
   833  					buf.WriteByte('@')
   834  				}
   835  				if h := u.Host; h != "" {
   836  					buf.WriteString(escape(h, encodeHost))
   837  				}
   838  			}
   839  		}
   840  		path := u.EscapedPath()
   841  		if path != "" && path[0] != '/' && u.Host != "" {
   842  			buf.WriteByte('/')
   843  		}
   844  		if buf.Len() == 0 {
   845  			// RFC 3986 §4.2
   846  			// A path segment that contains a colon character (e.g., "this:that")
   847  			// cannot be used as the first segment of a relative-path reference, as
   848  			// it would be mistaken for a scheme name. Such a segment must be
   849  			// preceded by a dot-segment (e.g., "./this:that") to make a relative-
   850  			// path reference.
   851  			if segment, _, _ := strings.Cut(path, "/"); strings.Contains(segment, ":") {
   852  				buf.WriteString("./")
   853  			}
   854  		}
   855  		buf.WriteString(path)
   856  	}
   857  	if u.ForceQuery || u.RawQuery != "" {
   858  		buf.WriteByte('?')
   859  		buf.WriteString(u.RawQuery)
   860  	}
   861  	if u.Fragment != "" {
   862  		buf.WriteByte('#')
   863  		buf.WriteString(u.EscapedFragment())
   864  	}
   865  	return buf.String()
   866  }
   867  
   868  // Redacted is like [URL.String] but replaces any password with "xxxxx".
   869  // Only the password in u.User is redacted.
   870  func (u *URL) Redacted() string {
   871  	if u == nil {
   872  		return ""
   873  	}
   874  
   875  	ru := *u
   876  	if _, has := ru.User.Password(); has {
   877  		ru.User = UserPassword(ru.User.Username(), "xxxxx")
   878  	}
   879  	return ru.String()
   880  }
   881  
   882  // Values maps a string key to a list of values.
   883  // It is typically used for query parameters and form values.
   884  // Unlike in the http.Header map, the keys in a Values map
   885  // are case-sensitive.
   886  type Values map[string][]string
   887  
   888  // Get gets the first value associated with the given key.
   889  // If there are no values associated with the key, Get returns
   890  // the empty string. To access multiple values, use the map
   891  // directly.
   892  func (v Values) Get(key string) string {
   893  	vs := v[key]
   894  	if len(vs) == 0 {
   895  		return ""
   896  	}
   897  	return vs[0]
   898  }
   899  
   900  // Set sets the key to value. It replaces any existing
   901  // values.
   902  func (v Values) Set(key, value string) {
   903  	v[key] = []string{value}
   904  }
   905  
   906  // Add adds the value to key. It appends to any existing
   907  // values associated with key.
   908  func (v Values) Add(key, value string) {
   909  	v[key] = append(v[key], value)
   910  }
   911  
   912  // Del deletes the values associated with key.
   913  func (v Values) Del(key string) {
   914  	delete(v, key)
   915  }
   916  
   917  // Has checks whether a given key is set.
   918  func (v Values) Has(key string) bool {
   919  	_, ok := v[key]
   920  	return ok
   921  }
   922  
   923  // ParseQuery parses the URL-encoded query string and returns
   924  // a map listing the values specified for each key.
   925  // ParseQuery always returns a non-nil map containing all the
   926  // valid query parameters found; err describes the first decoding error
   927  // encountered, if any.
   928  //
   929  // Query is expected to be a list of key=value settings separated by ampersands.
   930  // A setting without an equals sign is interpreted as a key set to an empty
   931  // value.
   932  // Settings containing a non-URL-encoded semicolon are considered invalid.
   933  func ParseQuery(query string) (Values, error) {
   934  	m := make(Values)
   935  	err := parseQuery(m, query)
   936  	return m, err
   937  }
   938  
   939  func parseQuery(m Values, query string) (err error) {
   940  	for query != "" {
   941  		var key string
   942  		key, query, _ = strings.Cut(query, "&")
   943  		if strings.Contains(key, ";") {
   944  			err = fmt.Errorf("invalid semicolon separator in query")
   945  			continue
   946  		}
   947  		if key == "" {
   948  			continue
   949  		}
   950  		key, value, _ := strings.Cut(key, "=")
   951  		key, err1 := QueryUnescape(key)
   952  		if err1 != nil {
   953  			if err == nil {
   954  				err = err1
   955  			}
   956  			continue
   957  		}
   958  		value, err1 = QueryUnescape(value)
   959  		if err1 != nil {
   960  			if err == nil {
   961  				err = err1
   962  			}
   963  			continue
   964  		}
   965  		m[key] = append(m[key], value)
   966  	}
   967  	return err
   968  }
   969  
   970  // Encode encodes the values into “URL encoded” form
   971  // ("bar=baz&foo=quux") sorted by key.
   972  func (v Values) Encode() string {
   973  	if len(v) == 0 {
   974  		return ""
   975  	}
   976  	var buf strings.Builder
   977  	keys := make([]string, 0, len(v))
   978  	for k := range v {
   979  		keys = append(keys, k)
   980  	}
   981  	sort.Strings(keys)
   982  	for _, k := range keys {
   983  		vs := v[k]
   984  		keyEscaped := QueryEscape(k)
   985  		for _, v := range vs {
   986  			if buf.Len() > 0 {
   987  				buf.WriteByte('&')
   988  			}
   989  			buf.WriteString(keyEscaped)
   990  			buf.WriteByte('=')
   991  			buf.WriteString(QueryEscape(v))
   992  		}
   993  	}
   994  	return buf.String()
   995  }
   996  
   997  // resolvePath applies special path segments from refs and applies
   998  // them to base, per RFC 3986.
   999  func resolvePath(base, ref string) string {
  1000  	var full string
  1001  	if ref == "" {
  1002  		full = base
  1003  	} else if ref[0] != '/' {
  1004  		i := strings.LastIndex(base, "/")
  1005  		full = base[:i+1] + ref
  1006  	} else {
  1007  		full = ref
  1008  	}
  1009  	if full == "" {
  1010  		return ""
  1011  	}
  1012  
  1013  	var (
  1014  		elem string
  1015  		dst  strings.Builder
  1016  	)
  1017  	first := true
  1018  	remaining := full
  1019  	// We want to return a leading '/', so write it now.
  1020  	dst.WriteByte('/')
  1021  	found := true
  1022  	for found {
  1023  		elem, remaining, found = strings.Cut(remaining, "/")
  1024  		if elem == "." {
  1025  			first = false
  1026  			// drop
  1027  			continue
  1028  		}
  1029  
  1030  		if elem == ".." {
  1031  			// Ignore the leading '/' we already wrote.
  1032  			str := dst.String()[1:]
  1033  			index := strings.LastIndexByte(str, '/')
  1034  
  1035  			dst.Reset()
  1036  			dst.WriteByte('/')
  1037  			if index == -1 {
  1038  				first = true
  1039  			} else {
  1040  				dst.WriteString(str[:index])
  1041  			}
  1042  		} else {
  1043  			if !first {
  1044  				dst.WriteByte('/')
  1045  			}
  1046  			dst.WriteString(elem)
  1047  			first = false
  1048  		}
  1049  	}
  1050  
  1051  	if elem == "." || elem == ".." {
  1052  		dst.WriteByte('/')
  1053  	}
  1054  
  1055  	// We wrote an initial '/', but we don't want two.
  1056  	r := dst.String()
  1057  	if len(r) > 1 && r[1] == '/' {
  1058  		r = r[1:]
  1059  	}
  1060  	return r
  1061  }
  1062  
  1063  // IsAbs reports whether the [URL] is absolute.
  1064  // Absolute means that it has a non-empty scheme.
  1065  func (u *URL) IsAbs() bool {
  1066  	return u.Scheme != ""
  1067  }
  1068  
  1069  // Parse parses a [URL] in the context of the receiver. The provided URL
  1070  // may be relative or absolute. Parse returns nil, err on parse
  1071  // failure, otherwise its return value is the same as [URL.ResolveReference].
  1072  func (u *URL) Parse(ref string) (*URL, error) {
  1073  	refURL, err := Parse(ref)
  1074  	if err != nil {
  1075  		return nil, err
  1076  	}
  1077  	return u.ResolveReference(refURL), nil
  1078  }
  1079  
  1080  // ResolveReference resolves a URI reference to an absolute URI from
  1081  // an absolute base URI u, per RFC 3986 Section 5.2. The URI reference
  1082  // may be relative or absolute. ResolveReference always returns a new
  1083  // [URL] instance, even if the returned URL is identical to either the
  1084  // base or reference. If ref is an absolute URL, then ResolveReference
  1085  // ignores base and returns a copy of ref.
  1086  func (u *URL) ResolveReference(ref *URL) *URL {
  1087  	url := *ref
  1088  	if ref.Scheme == "" {
  1089  		url.Scheme = u.Scheme
  1090  	}
  1091  	if ref.Scheme != "" || ref.Host != "" || ref.User != nil {
  1092  		// The "absoluteURI" or "net_path" cases.
  1093  		// We can ignore the error from setPath since we know we provided a
  1094  		// validly-escaped path.
  1095  		url.setPath(resolvePath(ref.EscapedPath(), ""))
  1096  		return &url
  1097  	}
  1098  	if ref.Opaque != "" {
  1099  		url.User = nil
  1100  		url.Host = ""
  1101  		url.Path = ""
  1102  		return &url
  1103  	}
  1104  	if ref.Path == "" && !ref.ForceQuery && ref.RawQuery == "" {
  1105  		url.RawQuery = u.RawQuery
  1106  		if ref.Fragment == "" {
  1107  			url.Fragment = u.Fragment
  1108  			url.RawFragment = u.RawFragment
  1109  		}
  1110  	}
  1111  	// The "abs_path" or "rel_path" cases.
  1112  	url.Host = u.Host
  1113  	url.User = u.User
  1114  	url.setPath(resolvePath(u.EscapedPath(), ref.EscapedPath()))
  1115  	return &url
  1116  }
  1117  
  1118  // Query parses RawQuery and returns the corresponding values.
  1119  // It silently discards malformed value pairs.
  1120  // To check errors use [ParseQuery].
  1121  func (u *URL) Query() Values {
  1122  	v, _ := ParseQuery(u.RawQuery)
  1123  	return v
  1124  }
  1125  
  1126  // RequestURI returns the encoded path?query or opaque?query
  1127  // string that would be used in an HTTP request for u.
  1128  func (u *URL) RequestURI() string {
  1129  	result := u.Opaque
  1130  	if result == "" {
  1131  		result = u.EscapedPath()
  1132  		if result == "" {
  1133  			result = "/"
  1134  		}
  1135  	} else {
  1136  		if strings.HasPrefix(result, "//") {
  1137  			result = u.Scheme + ":" + result
  1138  		}
  1139  	}
  1140  	if u.ForceQuery || u.RawQuery != "" {
  1141  		result += "?" + u.RawQuery
  1142  	}
  1143  	return result
  1144  }
  1145  
  1146  // Hostname returns u.Host, stripping any valid port number if present.
  1147  //
  1148  // If the result is enclosed in square brackets, as literal IPv6 addresses are,
  1149  // the square brackets are removed from the result.
  1150  func (u *URL) Hostname() string {
  1151  	host, _ := splitHostPort(u.Host)
  1152  	return host
  1153  }
  1154  
  1155  // Port returns the port part of u.Host, without the leading colon.
  1156  //
  1157  // If u.Host doesn't contain a valid numeric port, Port returns an empty string.
  1158  func (u *URL) Port() string {
  1159  	_, port := splitHostPort(u.Host)
  1160  	return port
  1161  }
  1162  
  1163  // splitHostPort separates host and port. If the port is not valid, it returns
  1164  // the entire input as host, and it doesn't check the validity of the host.
  1165  // Unlike net.SplitHostPort, but per RFC 3986, it requires ports to be numeric.
  1166  func splitHostPort(hostPort string) (host, port string) {
  1167  	host = hostPort
  1168  
  1169  	colon := strings.LastIndexByte(host, ':')
  1170  	if colon != -1 && validOptionalPort(host[colon:]) {
  1171  		host, port = host[:colon], host[colon+1:]
  1172  	}
  1173  
  1174  	if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
  1175  		host = host[1 : len(host)-1]
  1176  	}
  1177  
  1178  	return
  1179  }
  1180  
  1181  // Marshaling interface implementations.
  1182  // Would like to implement MarshalText/UnmarshalText but that will change the JSON representation of URLs.
  1183  
  1184  func (u *URL) MarshalBinary() (text []byte, err error) {
  1185  	return []byte(u.String()), nil
  1186  }
  1187  
  1188  func (u *URL) UnmarshalBinary(text []byte) error {
  1189  	u1, err := Parse(string(text))
  1190  	if err != nil {
  1191  		return err
  1192  	}
  1193  	*u = *u1
  1194  	return nil
  1195  }
  1196  
  1197  // JoinPath returns a new [URL] with the provided path elements joined to
  1198  // any existing path and the resulting path cleaned of any ./ or ../ elements.
  1199  // Any sequences of multiple / characters will be reduced to a single /.
  1200  func (u *URL) JoinPath(elem ...string) *URL {
  1201  	elem = append([]string{u.EscapedPath()}, elem...)
  1202  	var p string
  1203  	if !strings.HasPrefix(elem[0], "/") {
  1204  		// Return a relative path if u is relative,
  1205  		// but ensure that it contains no ../ elements.
  1206  		elem[0] = "/" + elem[0]
  1207  		p = path.Join(elem...)[1:]
  1208  	} else {
  1209  		p = path.Join(elem...)
  1210  	}
  1211  	// path.Join will remove any trailing slashes.
  1212  	// Preserve at least one.
  1213  	if strings.HasSuffix(elem[len(elem)-1], "/") && !strings.HasSuffix(p, "/") {
  1214  		p += "/"
  1215  	}
  1216  	url := *u
  1217  	url.setPath(p)
  1218  	return &url
  1219  }
  1220  
  1221  // validUserinfo reports whether s is a valid userinfo string per RFC 3986
  1222  // Section 3.2.1:
  1223  //
  1224  //	userinfo    = *( unreserved / pct-encoded / sub-delims / ":" )
  1225  //	unreserved  = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1226  //	sub-delims  = "!" / "$" / "&" / "'" / "(" / ")"
  1227  //	              / "*" / "+" / "," / ";" / "="
  1228  //
  1229  // It doesn't validate pct-encoded. The caller does that via func unescape.
  1230  func validUserinfo(s string) bool {
  1231  	for _, r := range s {
  1232  		if 'A' <= r && r <= 'Z' {
  1233  			continue
  1234  		}
  1235  		if 'a' <= r && r <= 'z' {
  1236  			continue
  1237  		}
  1238  		if '0' <= r && r <= '9' {
  1239  			continue
  1240  		}
  1241  		switch r {
  1242  		case '-', '.', '_', ':', '~', '!', '$', '&', '\'',
  1243  			'(', ')', '*', '+', ',', ';', '=', '%', '@':
  1244  			continue
  1245  		default:
  1246  			return false
  1247  		}
  1248  	}
  1249  	return true
  1250  }
  1251  
  1252  // stringContainsCTLByte reports whether s contains any ASCII control character.
  1253  func stringContainsCTLByte(s string) bool {
  1254  	for i := 0; i < len(s); i++ {
  1255  		b := s[i]
  1256  		if b < ' ' || b == 0x7f {
  1257  			return true
  1258  		}
  1259  	}
  1260  	return false
  1261  }
  1262  
  1263  // JoinPath returns a [URL] string with the provided path elements joined to
  1264  // the existing path of base and the resulting path cleaned of any ./ or ../ elements.
  1265  func JoinPath(base string, elem ...string) (result string, err error) {
  1266  	url, err := Parse(base)
  1267  	if err != nil {
  1268  		return
  1269  	}
  1270  	result = url.JoinPath(elem...).String()
  1271  	return
  1272  }
  1273  

View as plain text