我想手动(使用socket和ssl模块)HTTPS
通过代理发出请求,该代理本身使用HTTPS
.
CONNECT
我可以很好地执行初始交换:
import ssl, socket
PROXY_ADDR = ("proxy-addr", 443)
CONNECT = "CONNECT example.com:443 HTTP/1.1\r\n\r\n"
sock = socket.create_connection(PROXY_ADDR)
sock = ssl.wrap_socket(sock)
sock.sendall(CONNECT)
s = ""
while s[-4:] != "\r\n\r\n":
s += sock.recv(1)
print repr(s)
上面的代码打印HTTP/1.1 200 Connection established
加上一些标题,这是我所期望的。所以现在我应该准备好提出请求了,例如
sock.sendall("GET / HTTP/1.1\r\n\r\n")
但上面的代码返回
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
Reason: You're speaking plain HTTP to an SSL-enabled server port.<br />
Instead use the HTTPS scheme to access this URL, please.<br />
</body></html>
这也是有道理的,因为我仍然需要与example.com
要通过隧道连接的服务器进行 SSL 握手。但是,如果不是立即发送GET
请求,我会说
sock = ssl.wrap_socket(sock)
与远程服务器握手,然后我得到一个异常:
Traceback (most recent call last):
File "so_test.py", line 18, in <module>
ssl.wrap_socket(sock)
File "/usr/lib/python2.6/ssl.py", line 350, in wrap_socket
suppress_ragged_eofs=suppress_ragged_eofs)
File "/usr/lib/python2.6/ssl.py", line 118, in __init__
self.do_handshake()
File "/usr/lib/python2.6/ssl.py", line 293, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
那么如何与远程example.com
服务器进行 SSL 握手呢?
编辑:我很确定在我第二次调用之前没有其他数据可用,wrap_socket
因为调用会sock.recv(1)
无限期地阻塞。