class WebServer(TCPApplication, _ConsumerMixin): """ Simple TCPApplication that act as a simple HTTP server """ disconnecting = False # Required by twisted connected = True disconnected = False def __init__(self): TCPApplication.__init__(self) _ConsumerMixin.__init__(self) self.app = Site(static.File(os.path.abspath("./stegano/sitetest"))).buildProtocol( "test" ) # Serve the given folder self.app.transport = ( self ) # Because we define self as transport we have to implement function normally called by twisted for a transport class def packet_received( self, packet, **kwargs ): # Overwrite TCPApplication packet_received to call the dataReceived of twisted self.lastclient = kwargs["id"] try: print ("---- Request received ----\n" + packet + "\n------------") self.app.dataReceived( packet ) # TODO: A chaque fois qu'on fait un read write s'assurer que la connection existe toujours etc.. except Exception, e: print ("Something is wrong in the request:" + str(e))
class WebServer(TCPApplication, _ConsumerMixin): ''' Simple TCPApplication that act as a simple HTTP server ''' disconnecting = False #Required by twisted connected = True disconnected = False def __init__(self): TCPApplication.__init__(self) _ConsumerMixin.__init__(self) self.app = Site( static.File(os.path.abspath("./stegano/sitetest"))).buildProtocol( "test") #Serve the given folder self.app.transport = self #Because we define self as transport we have to implement function normally called by twisted for a transport class def packet_received( self, packet, **kwargs ): #Overwrite TCPApplication packet_received to call the dataReceived of twisted self.lastclient = kwargs["id"] try: print("---- Request received ----\n" + packet + "\n------------") self.app.dataReceived( packet ) #TODO: A chaque fois qu'on fait un read write s'assurer que la connection existe toujours etc.. except Exception, e: print("Something is wrong in the request:" + str(e))
def request(self, method, uri, headers=None, bodyProducer=None): """ Implement IAgent.request. """ # We want to use Agent to parse the HTTP response, so let's ask it to # make a request against our in-memory reactor. response = self._realAgent.request(method, uri, headers, bodyProducer) # That will try to establish an HTTP connection with the reactor's # connectTCP method, and MemoryReactor will place Agent's factory into # the tcpClients list. We'll extract that. host, port, factory, timeout, bindAddress = ( self._memoryReactor.tcpClients[0]) # Then we need to convince that factory it's connected to something and # it will give us a protocol for that connection. protocol = factory.buildProtocol(None) # We want to capture the output of that connection so we'll make an # in-memory transport. clientTransport = StringTransport() # When the protocol is connected to a transport, it ought to send the # whole request because callers of this should not use an asynchronous # bodyProducer. protocol.makeConnection(clientTransport) # Get the data from the request. requestData = clientTransport.io.getvalue() # Now time for the server to do its job. Ask it to build an HTTP # channel. channel = Site(self._rootResource).buildProtocol(None) # Connect the channel to another in-memory transport so we can collect # the response. serverTransport = StringTransport() serverTransport.hostAddr = IPv4Address('TCP', '127.0.0.1', 80) channel.makeConnection(serverTransport) # Feed it the data that the Agent synthesized. channel.dataReceived(requestData) # Tell it that the connection is now complete so it can clean up. channel.connectionLost(Failure(ConnectionDone())) # Now we have the response data, let's give it back to the Agent. protocol.dataReceived(serverTransport.io.getvalue()) # By now the Agent should have all it needs to parse a response. protocol.connectionLost(Failure(ConnectionDone())) # Return the response in the accepted format (Deferred firing # IResponse). This should be synchronously fired, and if not, it's the # system under test's problem. return response
def request(self, method, uri, headers=None, bodyProducer=None): """ Implement IAgent.request. """ # We want to use Agent to parse the HTTP response, so let's ask it to # make a request against our in-memory reactor. response = self._realAgent.request(method, uri, headers, bodyProducer) # That will try to establish an HTTP connection with the reactor's # connectTCP method, and MemoryReactor will place Agent's factory into # the tcpClients list. We'll extract that. host, port, factory, timeout, bindAddress = ( self._memoryReactor.tcpClients[0]) # Then we need to convince that factory it's connected to something and # it will give us a protocol for that connection. protocol = factory.buildProtocol(None) # We want to capture the output of that connection so we'll make an # in-memory transport. clientTransport = AbortableStringTransport() # When the protocol is connected to a transport, it ought to send the # whole request because callers of this should not use an asynchronous # bodyProducer. protocol.makeConnection(clientTransport) # Get the data from the request. requestData = clientTransport.io.getvalue() # Now time for the server to do its job. Ask it to build an HTTP # channel. channel = Site(self._rootResource).buildProtocol(None) # Connect the channel to another in-memory transport so we can collect # the response. serverTransport = StringTransport() serverTransport.hostAddr = IPv4Address('TCP', '127.0.0.1', 80) channel.makeConnection(serverTransport) # Feed it the data that the Agent synthesized. channel.dataReceived(requestData) # Tell it that the connection is now complete so it can clean up. channel.connectionLost(Failure(ConnectionDone())) # Now we have the response data, let's give it back to the Agent. protocol.dataReceived(serverTransport.io.getvalue()) # By now the Agent should have all it needs to parse a response. protocol.connectionLost(Failure(ConnectionDone())) # Return the response in the accepted format (Deferred firing # IResponse). This should be synchronously fired, and if not, it's the # system under test's problem. return response
class TCPServerProtocol(TCPConnectionProtocol): disconnecting = False def setup(self): self.state = TCPState_LISTEN(self) self.localPort = 8000 def connectionEstablished(self): self.sshServer() def webServer(self): from twisted.web.server import Site from twisted.web import demo, static self.app = Site(demo.Test()).buildProtocol("lala") self.app = Site(static.File( os.path.abspath("."))).buildProtocol("lala") self.app.transport = self def sshServer(self): from twisted.conch import checkers, unix from twisted.conch.openssh_compat import factory from twisted.cred import portal from twisted.python import usage from twisted.application import strports t = factory.OpenSSHFactory() t.portal = portal.Portal(unix.UnixSSHRealm()) t.portal.registerChecker(checkers.UNIXPasswordDatabase()) t.portal.registerChecker(checkers.SSHPublicKeyDatabase()) if checkers.pamauth: t.portal.registerChecker( checkers.PluggableAuthenticationModulesChecker()) t.dataRoot = '/etc/ssh' t.moduliRoot = '/etc/ssh' t.startFactory() self.app = t.buildProtocol("lala") self.app.transport = self self.app.connectionMade() def dataReceived(self, data): try: self.app.dataReceived(data) except Exception, e: print "some noise", e
class TCPServerProtocol(TCPConnectionProtocol): disconnecting = False def setup(self): self.state = TCPState_LISTEN(self) self.localPort = 8000 def connectionEstablished(self): self.sshServer() def webServer(self): from twisted.web.server import Site from twisted.web import demo, static self.app = Site(demo.Test()).buildProtocol("lala") self.app = Site(static.File(os.path.abspath("."))).buildProtocol("lala") self.app.transport = self def sshServer(self): from twisted.conch import checkers, unix from twisted.conch.openssh_compat import factory from twisted.cred import portal from twisted.python import usage from twisted.application import strports t = factory.OpenSSHFactory() t.portal = portal.Portal(unix.UnixSSHRealm()) t.portal.registerChecker(checkers.UNIXPasswordDatabase()) t.portal.registerChecker(checkers.SSHPublicKeyDatabase()) if checkers.pamauth: t.portal.registerChecker(checkers.PluggableAuthenticationModulesChecker()) t.dataRoot = '/etc/ssh' t.moduliRoot = '/etc/ssh' t.startFactory() self.app = t.buildProtocol("lala") self.app.transport = self self.app.connectionMade() def dataReceived(self, data): try: self.app.dataReceived(data) except Exception, e: print "some noise", e
class WebServer(_ConsumerMixin): ''' Class that allow to server a HTTP server on the given directory ''' disconnecting = False #Required by twisted connected = True disconnected = False def __init__(self,tcpapp, path): _ConsumerMixin.__init__(self) self.app = Site(static.File(os.path.abspath(path))).buildProtocol("test") self.app.transport = self #Because we define self as transport we have to implement function normally called by twisted for a transport class self.tcpapp = tcpapp #tcpapp contain the TCPApplication ! def packet_received(self, packet, **kwargs): #Will be called by the TCPApplication with genuine requests #self.lastclient = kwargs["id"] try: print("Request received") self.app.dataReceived(packet) except Exception, e: print("Something is wrong in the request:"+ str(e))
class WebServer(_ConsumerMixin): ''' Class that allow to server a HTTP server on the given directory ''' disconnecting = False #Required by twisted connected = True disconnected = False def __init__(self, tcpapp, path): _ConsumerMixin.__init__(self) self.app = Site(static.File( os.path.abspath(path))).buildProtocol("test") self.app.transport = self #Because we define self as transport we have to implement function normally called by twisted for a transport class self.tcpapp = tcpapp #tcpapp contain the TCPApplication ! def packet_received( self, packet, **kwargs ): #Will be called by the TCPApplication with genuine requests #self.lastclient = kwargs["id"] try: print("Request received") self.app.dataReceived(packet) except Exception, e: print("Something is wrong in the request:" + str(e))
def request(self, method, uri, headers=None, bodyProducer=None): """ Implement IAgent.request. """ # We want to use Agent to parse the HTTP response, so let's ask it to # make a request against our in-memory reactor. response = self._realAgent.request(method, uri, headers, bodyProducer) # If the request has already finished, just propagate the result. In # reality this would only happen in failure, but if the agent ever adds # a local cache this might be a success. already_called = [] def check_already_called(r): already_called.append(r) return r response.addBoth(check_already_called) if already_called: return response # That will try to establish an HTTP connection with the reactor's # connectTCP method, and MemoryReactor will place Agent's factory into # the tcpClients list. Alternately, it will try to establish an HTTPS # connection with the reactor's connectSSL method, and MemoryReactor # will place it into the sslClients list. We'll extract that. scheme = URLPath.fromString(uri).scheme if scheme == "https": host, port, factory, context_factory, timeout, bindAddress = ( self._memoryReactor.sslClients[-1]) else: host, port, factory, timeout, bindAddress = ( self._memoryReactor.tcpClients[-1]) # Then we need to convince that factory it's connected to something and # it will give us a protocol for that connection. protocol = factory.buildProtocol(None) # We want to capture the output of that connection so we'll make an # in-memory transport. clientTransport = AbortableStringTransport() if scheme == "https": directlyProvides(clientTransport, ISSLTransport) # When the protocol is connected to a transport, it ought to send the # whole request because callers of this should not use an asynchronous # bodyProducer. protocol.makeConnection(clientTransport) # Get the data from the request. requestData = clientTransport.io.getvalue() # Now time for the server to do its job. Ask it to build an HTTP # channel. channel = Site(self._rootResource).buildProtocol(None) # Connect the channel to another in-memory transport so we can collect # the response. serverTransport = AbortableStringTransport() if scheme == "https": directlyProvides(serverTransport, ISSLTransport) serverTransport.hostAddr = IPv4Address('TCP', '127.0.0.1', port) channel.makeConnection(serverTransport) # Feed it the data that the Agent synthesized. channel.dataReceived(requestData) # Now we have the response data, let's give it back to the Agent. protocol.dataReceived(serverTransport.io.getvalue()) def finish(r): # By now the Agent should have all it needs to parse a response. protocol.connectionLost(Failure(ConnectionDone())) # Tell it that the connection is now complete so it can clean up. channel.connectionLost(Failure(ConnectionDone())) # Propogate the response. return r # Return the response in the accepted format (Deferred firing # IResponse). This should be synchronously fired, and if not, it's the # system under test's problem. return response.addBoth(finish)