【发布时间】:2011-02-10 08:50:38
【问题描述】:
我开始使用 Ruby 编写 HTTP 拦截代理:
require 'socket' # Get sockets from stdlib
server = TCPServer.open(8080) # Socket to listen on port 8080
loop { # Servers run forever
Thread.start(server.accept) do |client|
puts "** Got connection!"
@output = ""
@host = ""
@port = 80
while line = client.gets
line.chomp!
if (line =~ /^(GET|CONNECT) .*(\.com|\.net):(.*) (HTTP\/1.1|HTTP\/1.0)$/)
@port = $3
elsif (line =~ /^Host: (.*)$/ && @host == "")
@host = $1
end
print line + "\n"
@output += line + "\n"
# This *may* cause problems with not getting full requests,
# but without this, the loop never returns.
break if line == ""
end
if (@host != "")
puts "** Got host! (#{@host}:#{@port})"
out = TCPSocket.open(@host, @port)
puts "** Got destination!"
out.print(@output)
while line = out.gets
line.chomp!
if (line =~ /^<proxyinfo>.*<\/proxyinfo>$/)
# Logic is done here.
end
print line + "\n"
client.print(line + "\n")
end
out.close
end
client.close
end
}
我制作的这个简单代理从 HTTP 请求中解析出目标,然后读取 HTTP 响应并根据特殊的 HTML 标签执行逻辑。代理在大部分情况下都能正常工作,但似乎在处理二进制数据和 HTTPS 连接时遇到了问题。
我该如何解决这些问题?
【问题讨论】:
标签: html ruby http proxy https