[Twisted-Python] Twisted + tlslite

Trevor Perrin trevp at trevp.net
Fri Mar 12 23:51:41 MST 2004


At 12:25 AM 3/12/2004 -0500, Itamar Shtull-Trauring wrote:

>On Thu, 2004-03-11 at 02:38, Trevor Perrin wrote:
>
> > One thing I'm not sure about is exception handling.  When TLS Lite throws
> > an exception, is there anywhere I can plug-in a handler or something?
>
>Typically we have callbacks for error conditions. For TLS you usually
>want to close the connection, no? So you'd pass the exception to
>connectionLost wrapped in a Failure, perhaps.

Hi Itamar,

Thanks.  I think I managed to implement this, but I'm unsure if I'm trying 
to accomplish the right thing, and if I did it properly.  If you or anyone 
could glance over this, I'd really appreciate it.

Background:  there's a class which subclasses ProtocolWrapper.  It 
overrides dataReceived and does "TLS stuff".  The "TLS stuff" will call 
ProtocolWrapper.dataReceived when it's processed a whole record.

What I'm trying to do:  If the "TLS stuff" raises an exception, the 
connection should be closed and the exception should be made available to 
the wrapped protocol via connectionLost.  If a TLS exception isn't raised, 
connectionLost should be called normally, when the connection is shut 
down.  connectionLost should only be called once when a TLS exception is 
raised; i.e., if it's called with a TLS exception, then it *should not* be 
called when the TCP connection is closed.

How I'm doing it:  I catch TLS exceptions in dataReceived, and then call 
through to ProtocolWrapper.connectionLost() with a wrapped error.  I keep a 
flag to indicate whether connectionLost was called, and only let it be 
called once:

def dataReceived(self, data):
     try:
         #TLS STUFF
     except tlsErrors, e:
         self.connectionLost(Failure(e))
         ProtocolWrapper.loseConnection(self)

def connectionLost(self, reason):
     if not self.connectionLostCalled:
         ProtocolWrapper.connectionLost(self, reason)
         self.connectionLostCalled = True


How does this look?

Trevor

(the whole thing is here, fwiw: http://trevp.net/tlslite/) 





More information about the Twisted-Python mailing list