You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

80 lines
2.6 KiB

  1. // Copyright 2015 Google Inc. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package header
  15. import (
  16. "fmt"
  17. "net/http"
  18. "strings"
  19. "github.com/google/martian"
  20. )
  21. // NewBadFramingModifier makes a best effort to fix inconsistencies in the
  22. // request such as multiple Content-Lengths or the lack of Content-Length and
  23. // improper Transfer-Encoding. If it is unable to determine a proper resolution
  24. // it returns an error.
  25. //
  26. // http://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-14#section-3.3
  27. func NewBadFramingModifier() martian.RequestModifier {
  28. return martian.RequestModifierFunc(
  29. func(req *http.Request) error {
  30. cls := req.Header["Content-Length"]
  31. if len(cls) > 0 {
  32. var length string
  33. // Iterate over all Content-Length headers, splitting any we find with
  34. // commas, and check that all Content-Lengths are equal.
  35. for _, ls := range cls {
  36. for _, l := range strings.Split(ls, ",") {
  37. // First length, set it as the canonical Content-Length.
  38. if length == "" {
  39. length = strings.TrimSpace(l)
  40. continue
  41. }
  42. // Mismatched Content-Lengths.
  43. if length != strings.TrimSpace(l) {
  44. return fmt.Errorf(`bad request framing: multiple mismatched "Content-Length" headers: %v`, cls)
  45. }
  46. }
  47. }
  48. // All Content-Lengths are equal, remove extras and set it to the
  49. // canonical value.
  50. req.Header.Set("Content-Length", length)
  51. }
  52. tes := req.Header["Transfer-Encoding"]
  53. if len(tes) > 0 {
  54. // Extract the last Transfer-Encoding value, and split on commas.
  55. last := strings.Split(tes[len(tes)-1], ",")
  56. // Check that the last, potentially comma-delimited, value is
  57. // "chunked", else we have no way to determine when the request is
  58. // finished.
  59. if strings.TrimSpace(last[len(last)-1]) != "chunked" {
  60. return fmt.Errorf(`bad request framing: "Transfer-Encoding" header is present, but does not end in "chunked"`)
  61. }
  62. // Transfer-Encoding "chunked" takes precedence over
  63. // Content-Length.
  64. req.Header.Del("Content-Length")
  65. }
  66. return nil
  67. })
  68. }