Debian Codegraph @

docs/core/examples/tls_alpn_client.py

raw
1 #!/usr/bin/env python
2 # Copyright (c) Twisted Matrix Laboratories.
3 # See LICENSE for details.
4 """
5 tls_alpn_client
6 ~~~~~~~~~~~~~~~~~~~
7
8 This test script demonstrates the usage of the acceptableProtocols API as a
9 client peer.
10
11 It performs next protocol negotiation using ALPN.
12
13 It will print what protocol was negotiated and exit.
14 The global variables are provided as input values.
15
16 This is set up to run against the server from
17 tls_alpn_server.py from the directory that contains this example.
18
19 It assumes that you have a self-signed server certificate, named
20 `server-cert.pem` and located in the working directory.
21 """
22
23 from twisted.internet import defer, endpoints, protocol, ssl, task
24 from twisted.python.filepath import FilePath
25
26 # The hostname the remote server to contact.
27 TARGET_HOST = "localhost"
28
29 # The port to contact.
30 TARGET_PORT = 8080
31
32 # The list of protocols we'd be prepared to speak after the TLS negotiation is
33 # complete.
34 # The order of the protocols here is an order of preference: most servers will
35 # attempt to respect our preferences when doing the negotiation. This indicates
36 # that we'd prefer to use HTTP/2 if possible (where HTTP/2 is using the token
37 # 'h2'), but would also accept HTTP/1.1.
38 # The bytes here are sent literally on the wire, and so there is no room for
39 # ambiguity about text encodings.
40 # Try changing this list by adding, removing, and reordering protocols to see
41 # how it affects the result.
42 ACCEPTABLE_PROTOCOLS = [b"h2", b"http/1.1"]
43
44 # Some safe initial data to send. This data is specific to HTTP/2: it is part
45 # of the HTTP/2 client preface (see RFC 7540 Section 3.5). This is used to
46 # signal to the remote server that it is aiming to speak HTTP/2, and to prevent
47 # a remote HTTP/1.1 server from expecting a 'proper' HTTP/1.1 request.
48 #
49 # FIXME: https://twistedmatrix.com/trac/ticket/6024
50 # This is only required because there is no event that fires when the TLS
51 # handshake is done. Instead, we wait for one that is implicitly after the
52 # TLS handshake is done: dataReceived. To trigger the remote peer to send data,
53 # we send some ourselves.
54 TLS_TRIGGER_DATA = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
55
56
57 def main(reactor):
58 certData = FilePath("server-cert.pem").getContent()
59 serverCertificate = ssl.Certificate.loadPEM(certData)
60 options = ssl.optionsForClientTLS(
61 hostname=TARGET_HOST,
62 trustRoot=serverCertificate,
63 # `acceptableProtocols` is the targeted option for this example.
64 acceptableProtocols=ACCEPTABLE_PROTOCOLS,
65 )
66
67 class BasicH2Request(protocol.Protocol):
68 def connectionMade(self):
69 print("Connection made")
70 # Add a deferred that fires where we're done with the connection.
71 # This deferred is returned to the reactor, and when we call it
72 # back the reactor will clean up the protocol.
73 self.complete = defer.Deferred()
74
75 # Write some data to trigger the SSL handshake.
76 self.transport.write(TLS_TRIGGER_DATA)
77
78 def dataReceived(self, data):
79 # We can only safely be sure what the next protocol is when we know
80 # the TLS handshake is over. This is generally *not* in the call to
81 # connectionMade, but instead only when we've received some data
82 # back.
83 print(f"Next protocol is: {self.transport.negotiatedProtocol}")
84 self.transport.loseConnection()
85
86 # If this is the first data write, we can tell the reactor we're
87 # done here by firing the callback we gave it.
88 if self.complete is not None:
89 self.complete.callback(None)
90 self.complete = None
91
92 def connectionLost(self, reason):
93 # If we haven't received any data, an error occurred. Otherwise,
94 # we lost the connection on purpose.
95 if self.complete is not None:
96 print(f"Connection lost due to error {reason}")
97 self.complete.callback(None)
98 else:
99 print("Connection closed cleanly")
100
101 return endpoints.connectProtocol(
102 endpoints.SSL4ClientEndpoint(reactor, TARGET_HOST, TARGET_PORT, options),
103 BasicH2Request(),
104 ).addCallback(lambda protocol: protocol.complete)
105
106
107 task.react(main)