guts.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright 2018 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. // Package httpguts provides functions implementing various details
  5. // of the HTTP specification.
  6. //
  7. // This package is shared by the standard library (which vendors it)
  8. // and x/net/http2. It comes with no API stability promise.
  9. package httpguts
  10. import (
  11. "net/textproto"
  12. "strings"
  13. )
  14. // SniffedContentType reports whether ct is a Content-Type that is known
  15. // to cause client-side content sniffing.
  16. //
  17. // This provides just a partial implementation of mime.ParseMediaType
  18. // with the assumption that the Content-Type is not attacker controlled.
  19. func SniffedContentType(ct string) bool {
  20. if i := strings.Index(ct, ";"); i != -1 {
  21. ct = ct[:i]
  22. }
  23. ct = strings.ToLower(strings.TrimSpace(ct))
  24. return ct == "text/plain" || ct == "application/octet-stream" ||
  25. ct == "application/unknown" || ct == "unknown/unknown" || ct == "*/*" ||
  26. !strings.Contains(ct, "/")
  27. }
  28. // ValidTrailerHeader reports whether name is a valid header field name to appear
  29. // in trailers.
  30. // See RFC 7230, Section 4.1.2
  31. func ValidTrailerHeader(name string) bool {
  32. name = textproto.CanonicalMIMEHeaderKey(name)
  33. if strings.HasPrefix(name, "If-") || badTrailer[name] {
  34. return false
  35. }
  36. return true
  37. }
  38. var badTrailer = map[string]bool{
  39. "Authorization": true,
  40. "Cache-Control": true,
  41. "Connection": true,
  42. "Content-Encoding": true,
  43. "Content-Length": true,
  44. "Content-Range": true,
  45. "Content-Type": true,
  46. "Expect": true,
  47. "Host": true,
  48. "Keep-Alive": true,
  49. "Max-Forwards": true,
  50. "Pragma": true,
  51. "Proxy-Authenticate": true,
  52. "Proxy-Authorization": true,
  53. "Proxy-Connection": true,
  54. "Range": true,
  55. "Realm": true,
  56. "Te": true,
  57. "Trailer": true,
  58. "Transfer-Encoding": true,
  59. "Www-Authenticate": true,
  60. }