Debian Codegraph @

src/net/url/url.go

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