我正在尝试在 twisted 中创建一个基本的 SSL 服务器。我从 Twisted 的官方网站上找到了以下示例:
from twisted.internet import ssl, reactor
from twisted.internet.protocol import Factory, Protocol
class Echo(Protocol):
def dataReceived(self, data):
"""As soon as any data is received, write it back."""
print "dataReceived: %s" % data
self.transport.write(data)
if __name__ == '__main__':
factory = Factory()
factory.protocol = Echo
print "running reactor"
reactor.listenSSL(8080, factory,
ssl.DefaultOpenSSLContextFactory(
"./test/privatekey.pem", "./test/cacert.pem"))
reactor.run()
然后,我试图通过将 URL 设置为 https://localhost:8080 在 Firefox 中访问此服务器,但没有收到任何响应。但是,我确实可以看到数据到达了服务器。请问为什么我没有收到任何响应?
2、解决方案
- 您没有向浏览器发送 HTTP 头,也没有关闭连接。
要解决此问题,您需要在向浏览器发送数据之前向其发送 HTTP 头。您还应该在向浏览器发送完所有数据后关闭连接。
您可以通过在 dataReceived 方法中添加以下代码来发送 HTTP 头:
self.transport.write("HTTP/1.1 200 OK\r\n")
self.transport.write("Content-Length: %d\r\n" % len(data))
self.transport.write("Connection: close\r\n")
self.transport.write("\r\n")
您还可以通过在 connectionLost 方法中添加以下代码来关闭连接:
self.transport.loseConnection()
- 您在此处实现了一个 SSL 回声服务器,而不是一个 HTTPS 服务器。
要解决此问题,您需要使用 openssl s_client 命令以交互方式对其进行测试,而不是 firefox(或任何其他 HTTP 客户端)。
您可以通过运行以下命令来使用 openssl s_client 命令测试您的服务器:
openssl s_client -connect localhost:8080
如果您的服务器正常工作,您应该会看到类似以下内容的输出:
CONNECTED(00000003)
depth=1 C = US, ST = California, L = Mountain View, O = Google Inc, CN = localhost
verify error:num=20:unable to get local issuer certificate
verify return:1
depth=0 C = US, ST = California, L = Mountain View, O = Google Inc, CN = localhost
verify error:num=20:unable to get local issuer certificate
verify return:1
---
Certificate chain
0 s:/CN=localhost
i:/C=US/ST=California/L=Mountain View/O=Google Inc/CN=localhost
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
1 s:/C=US/ST=California/L=Mountain View/O=Google Inc/CN=localhost
i:/C=US/ST=California/L=Mountain View/O=Google Inc/CN=localhost
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
---
Server certificate
subject=/C=US/ST=California/L=Mountain View/O=Google Inc/CN=localhost
issuer=/C=US/ST=California/L=Mountain View/O=Google Inc/CN=localhost
---
Acceptable client certificate CA names
...
---
SSL handshake has read 2564 bytes and written 2656 bytes
New, TLSv1/SSLv3, Cipher is RC4-MD5
Server public key is 2048 bit
Compression: NONE
Expansion: NONE
SSL-Session:
Protocol : TLSv1/SSLv3
Cipher : RC4-MD5
Session-ID: ...
Session-ID-ctx:
Master-Key: ...
Key-Arg : None
PSK identity: None
PSK identity hint: None
SRP username: None
Start Time: 1367950592
Timeout : 7200 (sec)
Verify return code: 0 (ok)
---
如果看不到类似的输出,则说明您的服务器配置不正确。