- add sources.
[platform/framework/web/crosswalk.git] / src / third_party / tlslite / tlslite / integration / TLSSocketServerMixIn.py
1 """TLS Lite + SocketServer."""
2
3 from tlslite.TLSConnection import TLSConnection
4
5 class TLSSocketServerMixIn:
6     """
7     This class can be mixed in with any L{SocketServer.TCPServer} to
8     add TLS support.
9
10     To use this class, define a new class that inherits from it and
11     some L{SocketServer.TCPServer} (with the mix-in first). Then
12     implement the handshake() method, doing some sort of server
13     handshake on the connection argument.  If the handshake method
14     returns True, the RequestHandler will be triggered.  Below is a
15     complete example of a threaded HTTPS server::
16
17         from SocketServer import *
18         from BaseHTTPServer import *
19         from SimpleHTTPServer import *
20         from tlslite.api import *
21
22         s = open("./serverX509Cert.pem").read()
23         x509 = X509()
24         x509.parse(s)
25         certChain = X509CertChain([x509])
26
27         s = open("./serverX509Key.pem").read()
28         privateKey = parsePEMKey(s, private=True)
29
30         sessionCache = SessionCache()
31
32         class MyHTTPServer(ThreadingMixIn, TLSSocketServerMixIn,
33                            HTTPServer):
34           def handshake(self, tlsConnection):
35               try:
36                   tlsConnection.handshakeServer(certChain=certChain,
37                                                 privateKey=privateKey,
38                                                 sessionCache=sessionCache)
39                   tlsConnection.ignoreAbruptClose = True
40                   return True
41               except TLSError, error:
42                   print "Handshake failure:", str(error)
43                   return False
44
45         httpd = MyHTTPServer(('localhost', 443), SimpleHTTPRequestHandler)
46         httpd.serve_forever()
47     """
48
49
50     def finish_request(self, sock, client_address):
51         tlsConnection = TLSConnection(sock)
52         if self.handshake(tlsConnection) == True:
53             self.RequestHandlerClass(tlsConnection, client_address, self)
54             tlsConnection.close()
55
56     #Implement this method to do some form of handshaking.  Return True
57     #if the handshake finishes properly and the request is authorized.
58     def handshake(self, tlsConnection):
59         raise NotImplementedError()