[Twisted-web] Nginx vs Twisted Web

Glyph glyph at twistedmatrix.com
Tue Oct 7 22:53:53 MDT 2014


On Oct 7, 2014, at 3:21 PM, Carl D'Halluin <carl at amplidata.com> wrote:

> 
>> Another problem is that Twisted doesn't yet support SSL on adopted sockets.
> 
> I did this by hand:
> 
> # Suppose your create/bind/list your listen_socket, and
> # its file descriptor is listen_socket_fd
> 
> 
> site = server.Site(MyHttpsSite())
> 
> cert = '/path/to/my/cert'
> key = '/path/to/my/key'
> 
> ctx = DefaultOpenSSLContextFactory(key, cert)
> tlsFactory = tls.TLSMemoryBIOFactory(ctx, False, site)
> p = tcp.Port._fromListeningDescriptor(reactor,
>                                             listen_socket_fd,
>                                             socket.AF_INET,
>                                             tlsFactory)
> p._type = 'TLS'
> p.startListening()
> 
> os.close(listen_socket_fd)
> reactor.run()

There is work underway for addressing this particular use-case (endpoint composition) via string endpoints:

<https://twistedmatrix.com/trac/ticket/5642>

But even today you don't have to touch unsupported private APIs to do this.

As per <https://twistedmatrix.com/trac/wiki/CompatibilityPolicy> we really like to discourage people from touching private (i.e. underscore-prefixed or imported-from-another-module) API, because it may well break in the next release and you'll have no recourse.

(Plus, you should really be using CertificateOptions, not DefaultOpenSSLContextFactory, either via PrivateCertificate(...).options() or directly constructed.)

from twisted.python.filepath import FilePath
site = server.Site(MyHttpsSite())

cert = FilePath('/path/to/my/cert').getContent()
key = FilePath('/path/to/my/key').getContent()

from twisted.internet.ssl import PrivateCertificate
certificateWithKey = PrivateCertificate.loadPEM(b"\n".join([cert, key]))

tlsFactory = tls.TLSMemoryBIOFactory(certificateWithKey.options(), False, site)

import socket
from twisted.internet import reactor
reactor.adoptStreamPort(listen_socket_fd, socket.AF_INET, tlsFactory)
import os
os.close(listen_socket_fd)
reactor.run()

This code hasn't been tested, but no underscores should be necessary!

-glyph

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://twistedmatrix.com/pipermail/twisted-web/attachments/20141007/eaf9df04/attachment.html>


More information about the Twisted-web mailing list