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