【问题标题】:cURL: Malformed encoding found in chunked-encoding, why?cURL:在分块编码中发现格式错误的编码,为什么?
【发布时间】:2015-11-29 02:39:09
【问题描述】:

我正在尝试使用 CGI 和分块编码(“Transfer-Encoding: chunked”HTTP 标头字段。)这种方式可以在没有内容长度标头的情况下发送文件。我用 Ruby 编写了一个简约的 CGI 应用程序来尝试一下。我的代码如下(chunked.rb):

#!/usr/bin/ruby

puts "Date: Fri, 28 Nov 2015 09:59:59 GMT"
puts "Content-Type: application/octet-stream; charset=\"ASCII-8BIT\""
puts "Content-Disposition: attachment; filename=image.jpg"
puts "Transfer-Encoding: chunked"
puts

File.open("image.jpg","rb"){|f|
 while data=f.read(32)
   STDOUT.puts data.size.to_s(16)
   STDOUT.puts data
 end
 STDOUT.puts "0"
 STDOUT.puts
}

我从这里获取了想法和分块格式示例:https://www.jmarshall.com/easy/http/

HTTP/1.1 200 OK
Date: Fri, 31 Dec 1999 23:59:59 GMT
Content-Type: text/plain
Transfer-Encoding: chunked

1a; ignore-stuff-here
abcdefghijklmnopqrstuvwxyz
10
1234567890abcdef
0
some-footer: some-value
another-footer: another-value
[blank line here]

由于我的 CGI 应用程序位于 Apache cgi-bin 目录中,我可以发出 cURL:

curl  http://example.com/cgi-bin/chunked.rb -O -J

cURL 应该从块中重新组合原始 image.jpg 文件,但不幸的是保存的文件不完整,它比原始文件小,并且我也从 cURL 收到错误消息:

curl: (56) Malformed encoding found in chunked-encoding

但是,当我将行 data=f.read(32) 更改为 data=f.read(1024*50) 之类的内容时,文件会正确保存。使用来自服务器的另一个更大的文件使 CGI 应用程序再次无用,我再次收到相同的错误消息。我该怎么做才能使我的 CGI 应用程序正常工作并正确发送文件?

【问题讨论】:

  • 在长度和数据之后,分隔符应该是CRLF (\r\n)。 puts 只是附加了一个 LF (\n) 所以这可能是问题所在。如果在每个长度和数据块后面加上\r\n,它是否有效?
  • 事实上它也应该工作 "\r\n" 和 "\n"。但问题解决了,这是一个 Ruby “陷阱”。而不是“STDOUT.puts data”,我不得不使用“STDOUT.print data”,然后是“puts”。这是因为当数据意外以“\n”结尾时,ruby 不会添加额外的“\n”。有时会发生这种情况,当块大小干扰二进制文件中的“\n”字节时。
  • 很高兴你走上了正确的道路 - 做得很好。

标签: ruby apache curl cgi chunked-encoding


【解决方案1】:

所以工作示例:

    puts "Date: Fri, 28 Nov 2015 09:59:59 GMT"
    puts "Content-Type: application/octet-stream; charset=\"ASCII-8BIT\""
    puts "Content-Disposition: attachment; filename=image.jpg"
    puts "Transfer-Encoding: chunked"
    puts

    File.open("image.jpg","rb"){|f|
     while data=f.read(32)
       STDOUT.puts data.size.to_s(16)
       STDOUT.print data
       STDOUT.puts
     end
     STDOUT.puts "0"
     STDOUT.puts
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-22
    • 1970-01-01
    相关资源
    最近更新 更多