Here are the examples of the python api twisted.internet.protocol.ServerFactory taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
75 Examples
3
Source : test_posixbase.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_connectionLostFailed(self):
"""
L{Port.stopListening} returns a L{Deferred} which errbacks if
L{Port.connectionLost} raises an exception.
"""
port = Port(12345, ServerFactory())
port.connected = True
port.connectionLost = lambda reason: 1 // 0
return self.assertFailure(port.stopListening(), ZeroDivisionError)
class TimeoutReportReactor(PosixReactorBase):
3
Source : test_tcp.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_allNewStyle(self):
"""
The L{IListeningPort} object is an instance of a class with no
classic classes in its hierarchy.
"""
reactor = self.buildReactor()
port = self.getListeningPort(reactor, ServerFactory())
self.assertFullyNewStyle(port)
def test_closePeerOnEMFILE(self):
3
Source : test_tcp.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_portGetHostOnIPv4(self):
"""
When no interface is passed to L{IReactorTCP.listenTCP}, the returned
listening port listens on an IPv4 address.
"""
reactor = self.buildReactor()
port = self.getListeningPort(reactor, ServerFactory())
address = port.getHost()
self.assertIsInstance(address, IPv4Address)
def test_portGetHostOnIPv6(self):
3
Source : test_tcp.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_portGetHostOnIPv6(self):
"""
When listening on an IPv6 address, L{IListeningPort.getHost} returns
an L{IPv6Address} with C{host} and C{port} attributes reflecting the
address the port is bound to.
"""
reactor = self.buildReactor()
host, portNumber = findFreePort(
family=socket.AF_INET6, interface='::1')[:2]
port = self.getListeningPort(
reactor, ServerFactory(), portNumber, host)
address = port.getHost()
self.assertIsInstance(address, IPv6Address)
self.assertEqual('::1', address.host)
self.assertEqual(portNumber, address.port)
if ipv6Skip:
3
Source : test_tcp.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_portGetHostOnIPv6ScopeID(self):
"""
When a link-local IPv6 address including a scope identifier is passed as
the C{interface} argument to L{IReactorTCP.listenTCP}, the resulting
L{IListeningPort} reports its address as an L{IPv6Address} with a host
value that includes the scope identifier.
"""
linkLocal = getLinkLocalIPv6Address()
reactor = self.buildReactor()
port = self.getListeningPort(reactor, ServerFactory(), 0, linkLocal)
address = port.getHost()
self.assertIsInstance(address, IPv6Address)
self.assertEqual(linkLocal, address.host)
if ipv6Skip:
3
Source : test_tls.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_badContext(self):
"""
If the context factory passed to L{IReactorSSL.listenSSL} raises an
exception from its C{getContext} method, that exception is raised by
L{IReactorSSL.listenSSL}.
"""
def useIt(reactor, contextFactory):
return reactor.listenSSL(0, ServerFactory(), contextFactory)
self._testBadContext(useIt)
def connectToListener(self, reactor, address, factory):
3
Source : test_unix.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_mode(self):
"""
The UNIX socket created by L{IReactorUNIX.listenUNIX} is created with
the mode specified.
"""
self._modeTest('listenUNIX', self.mktemp(), ServerFactory())
def test_listenOnLinuxAbstractNamespace(self):
3
Source : test_unix.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_listenOnLinuxAbstractNamespace(self):
"""
On Linux, a UNIX socket path may begin with C{'\0'} to indicate a socket
in the abstract namespace. L{IReactorUNIX.listenUNIX} accepts such a
path.
"""
# Don't listen on a path longer than the maximum allowed.
path = _abstractPath(self)
reactor = self.buildReactor()
port = reactor.listenUNIX('\0' + path, ServerFactory())
self.assertEqual(port.getHost(), UNIXAddress('\0' + path))
if not platform.isLinux():
3
Source : test_unix.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_listenFailure(self):
"""
L{IReactorUNIX.listenUNIX} raises L{CannotListenError} if the
underlying port's createInternetSocket raises a socket error.
"""
def raiseSocketError(self):
raise error('FakeBasePort forced socket.error')
self.patch(base.BasePort, "createInternetSocket", raiseSocketError)
reactor = self.buildReactor()
with self.assertRaises(CannotListenError):
reactor.listenUNIX('not-used', ServerFactory())
def test_connectToLinuxAbstractNamespace(self):
3
Source : test_tls.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_logPrefix(self):
"""
L{TLSMemoryBIOFactory.logPrefix} amends the wrapped factory's log prefix
with a short string (C{"TLS"}) indicating the wrapping, rather than its
full class name.
"""
contextFactory = ServerTLSContext()
factory = TLSMemoryBIOFactory(contextFactory, False, ServerFactory())
self.assertEqual("ServerFactory (TLS)", factory.logPrefix())
def test_logPrefixFallback(self):
3
Source : test_application.py
with MIT License
from autofelix
with MIT License
from autofelix
def testConnectionGettingRefused(self):
factory = protocol.ServerFactory()
factory.protocol = wire.Echo
t = internet.TCPServer(0, factory)
t.startService()
num = t._port.getHost().port
t.stopService()
d = defer.Deferred()
factory = protocol.ClientFactory()
factory.clientConnectionFailed = lambda *args: d.callback(None)
c = internet.TCPClient('127.0.0.1', num, factory)
c.startService()
return d
def testUNIX(self):
3
Source : test_application.py
with MIT License
from autofelix
with MIT License
from autofelix
def testStoppingServer(self):
factory = protocol.ServerFactory()
factory.protocol = wire.Echo
t = internet.UNIXServer('echo.skt', factory)
t.startService()
t.stopService()
self.assertFalse(t.running)
factory = protocol.ClientFactory()
d = defer.Deferred()
factory.clientConnectionFailed = lambda *args: d.callback(None)
reactor.connectUNIX('echo.skt', factory)
return d
if not interfaces.IReactorUNIX(reactor, None):
3
Source : test_ftp.py
with MIT License
from autofelix
with MIT License
from autofelix
def _makeDataConnection(self, ignored=None):
# Establish an active data connection (i.e. server connecting to
# client).
deferred = defer.Deferred()
class DataFactory(protocol.ServerFactory):
protocol = _BufferingProtocol
def buildProtocol(self, addr):
p = protocol.ServerFactory.buildProtocol(self, addr)
reactor.callLater(0, deferred.callback, p)
return p
dataPort = reactor.listenTCP(0, DataFactory(), interface='127.0.0.1')
self.dataPorts.append(dataPort)
cmd = 'PORT ' + ftp.encodeHostPort('127.0.0.1',
dataPort.getHost().port)
self.client.queueStringCommand(cmd)
return deferred
def tearDown(self):
3
Source : test_internet.py
with MIT License
from autofelix
with MIT License
from autofelix
def testTCP(self):
p = reactor.listenTCP(0, protocol.ServerFactory())
portNo = p.getHost().port
self.assertNotEqual(str(p).find(str(portNo)), -1,
"%d not found in %s" % (portNo, p))
return p.stopListening()
if interfaces.IReactorUDP(reactor, None) is not None:
3
Source : test_internet.py
with MIT License
from autofelix
with MIT License
from autofelix
def testSSL(self, ssl=ssl):
pem = util.sibpath(__file__, 'server.pem')
p = reactor.listenSSL(0, protocol.ServerFactory(), ssl.DefaultOpenSSLContextFactory(pem, pem))
portNo = p.getHost().port
self.assertNotEqual(str(p).find(str(portNo)), -1,
"%d not found in %s" % (portNo, p))
return p.stopListening()
if _PY3:
3
Source : test_policies.py
with MIT License
from autofelix
with MIT License
from autofelix
def setUp(self):
"""
Create a testable, deterministic clock, and a set of
server factory/protocol/transport.
"""
self.clock = task.Clock()
wrappedFactory = protocol.ServerFactory()
wrappedFactory.protocol = SimpleProtocol
self.factory = TestableTimeoutFactory(self.clock, wrappedFactory, 3)
self.proto = self.factory.buildProtocol(
address.IPv4Address('TCP', '127.0.0.1', 12345))
self.transport = StringTransportWithDisconnection()
self.transport.protocol = self.proto
self.proto.makeConnection(self.transport)
self.wrappedProto = self.proto.wrappedProtocol
def test_timeout(self):
3
Source : snippet.py
with Apache License 2.0
from dockerizeme
with Apache License 2.0
from dockerizeme
def main():
listening_port = 443
factory = protocol.ServerFactory()
factory.protocol = ServerProtocol
# Start the proxy server listener
logger.info("Starting SNI proxy server on port {}.".format(listening_port))
reactor.listenTCP(listening_port, factory)
reactor.run()
if __name__ == '__main__':
3
Source : test_spinner.py
with MIT License
from fbla-competitive-events
with MIT License
from fbla-competitive-events
def test_clean_selectables(self):
# If there's still a selectable (e.g. a listening socket), then
# clean() removes it from the reactor's registry.
#
# Note that the socket is left open. This emulates a bug in trial.
from twisted.internet.protocol import ServerFactory
reactor = self.make_reactor()
spinner = self.make_spinner(reactor)
port = reactor.listenTCP(0, ServerFactory(), interface='127.0.0.1')
spinner.run(self.make_timeout(), lambda: None)
results = spinner.get_junk()
self.assertThat(results, Equals([port]))
def test_clean_running_threads(self):
3
Source : test_spinner.py
with MIT License
from fbla-competitive-events
with MIT License
from fbla-competitive-events
def test_leftover_junk_available(self):
# If 'run' is given a function that leaves the reactor dirty in some
# way, 'run' will clean up the reactor and then store information
# about the junk. This information can be got using get_junk.
from twisted.internet.protocol import ServerFactory
reactor = self.make_reactor()
spinner = self.make_spinner(reactor)
port = spinner.run(
self.make_timeout(), reactor.listenTCP, 0, ServerFactory(),
interface='127.0.0.1')
self.assertThat(spinner.get_junk(), Equals([port]))
def test_will_not_run_with_previous_junk(self):
3
Source : test_spinner.py
with MIT License
from fbla-competitive-events
with MIT License
from fbla-competitive-events
def test_will_not_run_with_previous_junk(self):
# If 'run' is called and there's still junk in the spinner's junk
# list, then the spinner will refuse to run.
from twisted.internet.protocol import ServerFactory
reactor = self.make_reactor()
spinner = self.make_spinner(reactor)
timeout = self.make_timeout()
spinner.run(timeout, reactor.listenTCP, 0, ServerFactory(), interface='127.0.0.1')
self.assertThat(lambda: spinner.run(timeout, lambda: None),
Raises(MatchesException(_spinner.StaleJunkError)))
def test_clear_junk_clears_previous_junk(self):
3
Source : test_spinner.py
with MIT License
from fbla-competitive-events
with MIT License
from fbla-competitive-events
def test_clear_junk_clears_previous_junk(self):
# If 'run' is called and there's still junk in the spinner's junk
# list, then the spinner will refuse to run.
from twisted.internet.protocol import ServerFactory
reactor = self.make_reactor()
spinner = self.make_spinner(reactor)
timeout = self.make_timeout()
port = spinner.run(timeout, reactor.listenTCP, 0, ServerFactory(),
interface='127.0.0.1')
junk = spinner.clear_junk()
self.assertThat(junk, Equals([port]))
self.assertThat(spinner.get_junk(), Equals([]))
@skipIf(os.name != "posix", "Sending SIGINT with os.kill is posix only")
3
Source : test_socket.py
with MIT License
from fbla-competitive-events
with MIT License
from fbla-competitive-events
def test_invalidDescriptor(self):
"""
An implementation of L{IReactorSocket.adoptStreamPort} raises
L{socket.error} if passed an integer which is not associated with a
socket.
"""
reactor = self.buildReactor()
probe = socket.socket()
fileno = probe.fileno()
probe.close()
exc = self.assertRaises(
socket.error,
reactor.adoptStreamPort, fileno, socket.AF_INET, ServerFactory())
self.assertEqual(exc.args[0], errno.EBADF)
def test_invalidAddressFamily(self):
3
Source : test_tcp.py
with MIT License
from fbla-competitive-events
with MIT License
from fbla-competitive-events
def test_allNewStyle(self):
"""
The L{IListeningPort} object is an instance of a class with no
classic classes in its hierarchy.
"""
reactor = self.buildReactor()
port = self.getListeningPort(reactor, ServerFactory())
self.assertFullyNewStyle(port)
class ListenTCPMixin(object):
3
Source : test_tls.py
with MIT License
from fbla-competitive-events
with MIT License
from fbla-competitive-events
def test_badContext(self):
"""
If the context factory passed to L{IReactorSSL.listenSSL} raises an
exception from its C{getContext} method, that exception is raised by
L{IReactorSSL.listenSSL}.
"""
def useIt(reactor, contextFactory):
return reactor.listenSSL(0, ServerFactory(), contextFactory)
self._testBadContext(useIt)
globals().update(SSLClientTestsMixin.makeTestCaseClasses())
3
Source : test_mail.py
with MIT License
from fbla-competitive-events
with MIT License
from fbla-competitive-events
def testFactories(self):
f = self.service.getPOP3Factory()
self.assertTrue(isinstance(f, protocol.ServerFactory))
self.assertTrue(f.buildProtocol(('127.0.0.1', 12345)), pop3.POP3)
f = self.service.getSMTPFactory()
self.assertTrue(isinstance(f, protocol.ServerFactory))
self.assertTrue(f.buildProtocol(('127.0.0.1', 12345)), smtp.SMTP)
f = self.service.getESMTPFactory()
self.assertTrue(isinstance(f, protocol.ServerFactory))
self.assertTrue(f.buildProtocol(('127.0.0.1', 12345)), smtp.ESMTP)
def testPortals(self):
3
Source : test_ftp.py
with MIT License
from fbla-competitive-events
with MIT License
from fbla-competitive-events
def _makeDataConnection(self, ignored=None):
# Establish an active data connection (i.e. server connecting to
# client).
deferred = defer.Deferred()
class DataFactory(protocol.ServerFactory):
protocol = _BufferingProtocol
def buildProtocol(self, addr):
p = protocol.ServerFactory.buildProtocol(self, addr)
reactor.callLater(0, deferred.callback, p)
return p
dataPort = reactor.listenTCP(0, DataFactory(), interface='127.0.0.1')
self.dataPorts.append(dataPort)
cmd = 'PORT ' + ftp.encodeHostPort('127.0.0.1', dataPort.getHost().port)
self.client.queueStringCommand(cmd)
return deferred
def tearDown(self):
3
Source : test_policies.py
with MIT License
from fbla-competitive-events
with MIT License
from fbla-competitive-events
def setUp(self):
"""
Create a testable, deterministic clock, and a set of
server factory/protocol/transport.
"""
self.clock = task.Clock()
wrappedFactory = protocol.ServerFactory()
wrappedFactory.protocol = SimpleProtocol
self.factory = TestableTimeoutFactory(self.clock, wrappedFactory, 3)
self.proto = self.factory.buildProtocol(
address.IPv4Address('TCP', '127.0.0.1', 12345))
self.transport = StringTransportWithDisconnection()
self.transport.protocol = self.proto
self.proto.makeConnection(self.transport)
def test_timeout(self):
3
Source : socketmon.py
with Apache License 2.0
from google
with Apache License 2.0
from google
def run(self):
self._factory = protocol.ServerFactory()
self._factory.protocol = Listener
if self._protocol.lower() == "tcp":
reactor.listenTCP(int(self._port), self._factory)
else:
reactor.listenUDP(int(self._port), self._factory)
reactor.run(installSignalHandlers=0)
class Listener(protocol.Protocol):
3
Source : telnet.py
with MIT License
from jarret
with MIT License
from jarret
def run_interface(config):
factory = ServerFactory()
factory.protocol = lambda: TelnetTransport(JunctionTelnetInterface)
port = int(config['App']['TelnetInterfacePort'])
logging.info("starting telnet cli interface on port %d" % port)
service = TCPServer(port, factory)
service.startService()
def prep_parser(self):
3
Source : telnet.py
with MIT License
from jarret
with MIT License
from jarret
def run_interface(config):
factory = ServerFactory()
factory.protocol = lambda: TelnetTransport(TerminusTelnetInterface)
port = int(config['App']['TelnetInterfacePort'])
logging.info("starting telnet cli interface on port %d" % port)
service = TCPServer(port, factory)
service.startService()
def prep_parser(self):
0
Source : manhole_tap.py
with MIT License
from autofelix
with MIT License
from autofelix
def makeService(options):
"""
Create a manhole server service.
@type options: L{dict}
@param options: A mapping describing the configuration of
the desired service. Recognized key/value pairs are::
"telnetPort": strports description of the address on which
to listen for telnet connections. If None,
no telnet service will be started.
"sshPort": strports description of the address on which to
listen for ssh connections. If None, no ssh
service will be started.
"namespace": dictionary containing desired initial locals
for manhole connections. If None, an empty
dictionary will be used.
"passwd": Name of a passwd(5)-format username/password file.
"sshKeyDir": The folder that the SSH server key will be kept in.
"sshKeyName": The filename of the key.
"sshKeySize": The size of the key, in bits. Default is 4096.
@rtype: L{twisted.application.service.IService}
@return: A manhole service.
"""
svc = service.MultiService()
namespace = options['namespace']
if namespace is None:
namespace = {}
checker = checkers.FilePasswordDB(options['passwd'])
if options['telnetPort']:
telnetRealm = _StupidRealm(telnet.TelnetBootstrapProtocol,
insults.ServerProtocol,
manhole.ColoredManhole,
namespace)
telnetPortal = portal.Portal(telnetRealm, [checker])
telnetFactory = protocol.ServerFactory()
telnetFactory.protocol = makeTelnetProtocol(telnetPortal)
telnetService = strports.service(options['telnetPort'],
telnetFactory)
telnetService.setServiceParent(svc)
if options['sshPort']:
sshRealm = manhole_ssh.TerminalRealm()
sshRealm.chainedProtocolFactory = chainedProtocolFactory(namespace)
sshPortal = portal.Portal(sshRealm, [checker])
sshFactory = manhole_ssh.ConchFactory(sshPortal)
if options['sshKeyDir'] != " < USER DATA DIR>":
keyDir = options['sshKeyDir']
else:
from twisted.python._appdirs import getDataDirectory
keyDir = getDataDirectory()
keyLocation = filepath.FilePath(keyDir).child(options['sshKeyName'])
sshKey = keys._getPersistentRSAKey(keyLocation,
int(options['sshKeySize']))
sshFactory.publicKeys[b"ssh-rsa"] = sshKey
sshFactory.privateKeys[b"ssh-rsa"] = sshKey
sshService = strports.service(options['sshPort'], sshFactory)
sshService.setServiceParent(svc)
return svc
0
Source : test_socket.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_invalidDescriptor(self):
"""
An implementation of L{IReactorSocket.adoptStreamPort} raises
L{socket.error} if passed an integer which is not associated with a
socket.
"""
reactor = self.buildReactor()
probe = socket.socket()
fileno = probe.fileno()
probe.close()
exc = self.assertRaises(
socket.error,
reactor.adoptStreamPort, fileno, socket.AF_INET, ServerFactory())
if platform.isWindows() and _PY3:
self.assertEqual(exc.args[0], errno.WSAENOTSOCK)
else:
self.assertEqual(exc.args[0], errno.EBADF)
def test_invalidAddressFamily(self):
0
Source : test_socket.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_invalidAddressFamily(self):
"""
An implementation of L{IReactorSocket.adoptStreamPort} raises
L{UnsupportedAddressFamily} if passed an address family it does not
support.
"""
reactor = self.buildReactor()
port = socket.socket()
port.bind(("127.0.0.1", 0))
port.listen(1)
self.addCleanup(port.close)
arbitrary = 2 ** 16 + 7
self.assertRaises(
UnsupportedAddressFamily,
reactor.adoptStreamPort, port.fileno(), arbitrary, ServerFactory())
def test_stopOnlyCloses(self):
0
Source : test_socket.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_stopOnlyCloses(self):
"""
When the L{IListeningPort} returned by
L{IReactorSocket.adoptStreamPort} is stopped using
C{stopListening}, the underlying socket is closed but not
shutdown. This allows another process which still has a
reference to it to continue accepting connections over it.
"""
reactor = self.buildReactor()
portSocket = socket.socket()
self.addCleanup(portSocket.close)
portSocket.bind(("127.0.0.1", 0))
portSocket.listen(1)
portSocket.setblocking(False)
# The file descriptor is duplicated by adoptStreamPort
port = reactor.adoptStreamPort(
portSocket.fileno(), portSocket.family, ServerFactory())
d = port.stopListening()
def stopped(ignored):
# Should still be possible to accept a connection on
# portSocket. If it was shutdown, the exception would be
# EINVAL instead.
exc = self.assertRaises(socket.error, portSocket.accept)
if platform.isWindows() and _PY3:
self.assertEqual(exc.args[0], errno.WSAEWOULDBLOCK)
else:
self.assertEqual(exc.args[0], errno.EAGAIN)
d.addCallback(stopped)
d.addErrback(err, "Failed to accept on original port.")
needsRunningReactor(
reactor,
lambda: d.addCallback(lambda ignored: reactor.stop()))
reactor.run()
class AdoptStreamConnectionErrorsTestsBuilder(ReactorBuilder):
0
Source : test_socket.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_invalidAddressFamily(self):
"""
An implementation of L{IReactorSocket.adoptStreamConnection} raises
L{UnsupportedAddressFamily} if passed an address family it does not
support.
"""
reactor = self.buildReactor()
connection = socket.socket()
self.addCleanup(connection.close)
arbitrary = 2 ** 16 + 7
self.assertRaises(
UnsupportedAddressFamily,
reactor.adoptStreamConnection, connection.fileno(), arbitrary,
ServerFactory())
class AdoptDatagramPortErrorsTestsBuilder(ReactorBuilder):
0
Source : test_tcp.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_connectionLostLogMsg(self):
"""
When a connection is lost, an informative message should be logged
(see L{getExpectedConnectionLostLogMsg}): an address identifying
the port and the fact that it was closed.
"""
loggedMessages = []
def logConnectionLostMsg(eventDict):
loggedMessages.append(log.textFromEventDict(eventDict))
reactor = self.buildReactor()
p = self.getListeningPort(reactor, ServerFactory())
expectedMessage = self.getExpectedConnectionLostLogMsg(p)
log.addObserver(logConnectionLostMsg)
def stopReactor(ignored):
log.removeObserver(logConnectionLostMsg)
reactor.stop()
def doStopListening():
log.addObserver(logConnectionLostMsg)
maybeDeferred(p.stopListening).addCallback(stopReactor)
reactor.callWhenRunning(doStopListening)
reactor.run()
self.assertIn(expectedMessage, loggedMessages)
def test_allNewStyle(self):
0
Source : test_tcp.py
with MIT License
from autofelix
with MIT License
from autofelix
def _serverGetConnectionAddressTest(self, client, interface, which):
"""
Connect C{client} to a server listening on C{interface} started with
L{IReactorTCP.listenTCP} and return the address returned by one of the
server transport's address lookup methods, C{getHost} or C{getPeer}.
@param client: A C{SOCK_STREAM} L{socket.socket} created with an address
family such that it will be able to connect to a server listening on
C{interface}.
@param interface: A C{str} giving an address for a server to listen on.
This should almost certainly be the loopback address for some
address family supported by L{IReactorTCP.listenTCP}.
@param which: A C{str} equal to either C{"getHost"} or C{"getPeer"}
determining which address will be returned.
@return: Whatever object, probably an L{IAddress} provider, is returned
from the method indicated by C{which}.
"""
class ObserveAddress(Protocol):
def makeConnection(self, transport):
reactor.stop()
self.factory.address = getattr(transport, which)()
reactor = self.buildReactor()
factory = ServerFactory()
factory.protocol = ObserveAddress
port = self.getListeningPort(reactor, factory, 0, interface)
client.setblocking(False)
try:
connect(client, (port.getHost().host, port.getHost().port))
except socket.error as e:
self.assertIn(e.errno, (errno.EINPROGRESS, errno.EWOULDBLOCK))
self.runReactor(reactor)
return factory.address
def test_serverGetHostOnIPv4(self):
0
Source : test_tcp.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_stopStartReading(self):
"""
This test verifies transport socket read state after multiple
pause/resumeProducing calls.
"""
sf = ServerFactory()
reactor = sf.reactor = self.buildReactor()
skippedReactors = ["Glib2Reactor", "Gtk2Reactor"]
reactorClassName = reactor.__class__.__name__
if reactorClassName in skippedReactors and platform.isWindows():
raise SkipTest(
"This test is broken on gtk/glib under Windows.")
sf.protocol = StopStartReadingProtocol
sf.ready = Deferred()
sf.stop = Deferred()
p = reactor.listenTCP(0, sf)
port = p.getHost().port
def proceed(protos, port):
"""
Send several IOCPReactor's buffers' worth of data.
"""
self.assertTrue(protos[0])
self.assertTrue(protos[1])
protos = protos[0][1], protos[1][1]
protos[0].transport.write(b'x' * (2 * 4096) + b'y' * (2 * 4096))
return (sf.stop.addCallback(cleanup, protos, port)
.addCallback(lambda ign: reactor.stop()))
def cleanup(data, protos, port):
"""
Make sure IOCPReactor didn't start several WSARecv operations
that clobbered each other's results.
"""
self.assertEqual(data, b'x'*(2*4096) + b'y'*(2*4096),
'did not get the right data')
return DeferredList([
maybeDeferred(protos[0].transport.loseConnection),
maybeDeferred(protos[1].transport.loseConnection),
maybeDeferred(port.stopListening)])
cc = TCP4ClientEndpoint(reactor, '127.0.0.1', port)
cf = ClientFactory()
cf.protocol = Protocol
d = DeferredList([cc.connect(cf), sf.ready]).addCallback(proceed, p)
d.addErrback(log.err)
self.runReactor(reactor)
@oneTransportTest
0
Source : test_tls.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_disconnectAfterWriteAfterStartTLS(self):
"""
L{ITCPTransport.loseConnection} ends a connection which was set up with
L{ITLSTransport.startTLS} and which has recently been written to. This
is intended to verify that a socket send error masked by the TLS
implementation doesn't prevent the connection from being reported as
closed.
"""
class ShortProtocol(Protocol):
def connectionMade(self):
if not ITLSTransport.providedBy(self.transport):
# Functionality isn't available to be tested.
finished = self.factory.finished
self.factory.finished = None
finished.errback(SkipTest("No ITLSTransport support"))
return
# Switch the transport to TLS.
self.transport.startTLS(self.factory.context)
# Force TLS to really get negotiated. If nobody talks, nothing
# will happen.
self.transport.write(b"x")
def dataReceived(self, data):
# Stuff some bytes into the socket. This mostly has the effect
# of causing the next write to fail with ENOTCONN or EPIPE.
# With the pyOpenSSL implementation of ITLSTransport, the error
# is swallowed outside of the control of Twisted.
self.transport.write(b"y")
# Now close the connection, which requires a TLS close alert to
# be sent.
self.transport.loseConnection()
def connectionLost(self, reason):
# This is the success case. The client and the server want to
# get here.
finished = self.factory.finished
if finished is not None:
self.factory.finished = None
finished.callback(reason)
reactor = self.buildReactor()
serverFactory = ServerFactory()
serverFactory.finished = Deferred()
serverFactory.protocol = ShortProtocol
serverFactory.context = self.getServerContext()
clientFactory = ClientFactory()
clientFactory.finished = Deferred()
clientFactory.protocol = ShortProtocol
clientFactory.context = self.getClientContext()
clientFactory.context.method = serverFactory.context.method
lostConnectionResults = []
finished = DeferredList(
[serverFactory.finished, clientFactory.finished],
consumeErrors=True)
def cbFinished(results):
lostConnectionResults.extend([results[0][1], results[1][1]])
finished.addCallback(cbFinished)
port = reactor.listenTCP(0, serverFactory, interface='127.0.0.1')
self.addCleanup(port.stopListening)
connector = reactor.connectTCP(
port.getHost().host, port.getHost().port, clientFactory)
self.addCleanup(connector.disconnect)
finished.addCallback(lambda ign: reactor.stop())
self.runReactor(reactor)
lostConnectionResults[0].trap(ConnectionClosed)
lostConnectionResults[1].trap(ConnectionClosed)
class TLSPortTestsBuilder(TLSMixin, ContextGeneratingMixin,
0
Source : test_tls.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_quiet(self):
"""
L{TLSMemoryBIOFactory.doStart} and L{TLSMemoryBIOFactory.doStop} do
not log any messages.
"""
contextFactory = ServerTLSContext()
logs = []
logger = logs.append
log.addObserver(logger)
self.addCleanup(log.removeObserver, logger)
wrappedFactory = ServerFactory()
# Disable logging on the wrapped factory:
wrappedFactory.doStart = lambda: None
wrappedFactory.doStop = lambda: None
factory = TLSMemoryBIOFactory(contextFactory, False, wrappedFactory)
factory.doStart()
factory.doStop()
self.assertEqual(logs, [])
def test_logPrefix(self):
0
Source : test_tls.py
with MIT License
from autofelix
with MIT License
from autofelix
def handshakeProtocols(self):
"""
Start handshake between TLS client and server.
"""
clientFactory = ClientFactory()
clientFactory.protocol = Protocol
clientContextFactory, handshakeDeferred = (
HandshakeCallbackContextFactory.factoryAndDeferred())
wrapperFactory = TLSMemoryBIOFactory(
clientContextFactory, True, clientFactory)
sslClientProtocol = wrapperFactory.buildProtocol(None)
serverFactory = ServerFactory()
serverFactory.protocol = Protocol
serverContextFactory = ServerTLSContext()
wrapperFactory = TLSMemoryBIOFactory(
serverContextFactory, False, serverFactory)
sslServerProtocol = wrapperFactory.buildProtocol(None)
connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol)
return (sslClientProtocol, sslServerProtocol, handshakeDeferred,
connectionDeferred)
def test_handshake(self):
0
Source : test_tls.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_handshakeFailure(self):
"""
L{TLSMemoryBIOProtocol} reports errors in the handshake process to the
application-level protocol object using its C{connectionLost} method
and disconnects the underlying transport.
"""
clientConnectionLost = Deferred()
clientFactory = ClientFactory()
clientFactory.protocol = (
lambda: ConnectionLostNotifyingProtocol(
clientConnectionLost))
clientContextFactory = HandshakeCallbackContextFactory()
wrapperFactory = TLSMemoryBIOFactory(
clientContextFactory, True, clientFactory)
sslClientProtocol = wrapperFactory.buildProtocol(None)
serverConnectionLost = Deferred()
serverFactory = ServerFactory()
serverFactory.protocol = (
lambda: ConnectionLostNotifyingProtocol(
serverConnectionLost))
# This context factory rejects any clients which do not present a
# certificate.
certificateData = FilePath(certPath).getContent()
certificate = PrivateCertificate.loadPEM(certificateData)
serverContextFactory = certificate.options(certificate)
wrapperFactory = TLSMemoryBIOFactory(
serverContextFactory, False, serverFactory)
sslServerProtocol = wrapperFactory.buildProtocol(None)
connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol)
def cbConnectionLost(protocol):
# The connection should close on its own in response to the error
# induced by the client not supplying the required certificate.
# After that, check to make sure the protocol's connectionLost was
# called with the right thing.
protocol.lostConnectionReason.trap(Error)
clientConnectionLost.addCallback(cbConnectionLost)
serverConnectionLost.addCallback(cbConnectionLost)
# Additionally, the underlying transport should have been told to
# go away.
return gatherResults([
clientConnectionLost, serverConnectionLost,
connectionDeferred])
def test_getPeerCertificate(self):
0
Source : test_tls.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_getPeerCertificate(self):
"""
L{TLSMemoryBIOProtocol.getPeerCertificate} returns the
L{OpenSSL.crypto.X509Type} instance representing the peer's
certificate.
"""
# Set up a client and server so there's a certificate to grab.
clientFactory = ClientFactory()
clientFactory.protocol = Protocol
clientContextFactory, handshakeDeferred = (
HandshakeCallbackContextFactory.factoryAndDeferred())
wrapperFactory = TLSMemoryBIOFactory(
clientContextFactory, True, clientFactory)
sslClientProtocol = wrapperFactory.buildProtocol(None)
serverFactory = ServerFactory()
serverFactory.protocol = Protocol
serverContextFactory = ServerTLSContext()
wrapperFactory = TLSMemoryBIOFactory(
serverContextFactory, False, serverFactory)
sslServerProtocol = wrapperFactory.buildProtocol(None)
loopbackAsync(sslServerProtocol, sslClientProtocol)
# Wait for the handshake
def cbHandshook(ignored):
# Grab the server's certificate and check it out
cert = sslClientProtocol.getPeerCertificate()
self.assertIsInstance(cert, X509Type)
self.assertEqual(
cert.digest('sha1'),
# openssl x509 -noout -sha1 -fingerprint -in server.pem
b'23:4B:72:99:2E:5D:5E:2B:02:C3:BC:1B:7C:50:67:05:4F:60:FF:C9')
handshakeDeferred.addCallback(cbHandshook)
return handshakeDeferred
def test_writeAfterHandshake(self):
0
Source : test_tls.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_writeAfterHandshake(self):
"""
Bytes written to L{TLSMemoryBIOProtocol} before the handshake is
complete are received by the protocol on the other side of the
connection once the handshake succeeds.
"""
data = b"some bytes"
clientProtocol = Protocol()
clientFactory = ClientFactory()
clientFactory.protocol = lambda: clientProtocol
clientContextFactory, handshakeDeferred = (
HandshakeCallbackContextFactory.factoryAndDeferred())
wrapperFactory = TLSMemoryBIOFactory(
clientContextFactory, True, clientFactory)
sslClientProtocol = wrapperFactory.buildProtocol(None)
serverProtocol = AccumulatingProtocol(len(data))
serverFactory = ServerFactory()
serverFactory.protocol = lambda: serverProtocol
serverContextFactory = ServerTLSContext()
wrapperFactory = TLSMemoryBIOFactory(
serverContextFactory, False, serverFactory)
sslServerProtocol = wrapperFactory.buildProtocol(None)
connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol)
# Wait for the handshake to finish before writing anything.
def cbHandshook(ignored):
clientProtocol.transport.write(data)
# The server will drop the connection once it gets the bytes.
return connectionDeferred
handshakeDeferred.addCallback(cbHandshook)
# Once the connection is lost, make sure the server received the
# expected bytes.
def cbDisconnected(ignored):
self.assertEqual(b"".join(serverProtocol.received), data)
handshakeDeferred.addCallback(cbDisconnected)
return handshakeDeferred
def writeBeforeHandshakeTest(self, sendingProtocol, data):
0
Source : test_tls.py
with MIT License
from autofelix
with MIT License
from autofelix
def writeBeforeHandshakeTest(self, sendingProtocol, data):
"""
Run test where client sends data before handshake, given the sending
protocol and expected bytes.
"""
clientFactory = ClientFactory()
clientFactory.protocol = sendingProtocol
clientContextFactory, handshakeDeferred = (
HandshakeCallbackContextFactory.factoryAndDeferred())
wrapperFactory = TLSMemoryBIOFactory(
clientContextFactory, True, clientFactory)
sslClientProtocol = wrapperFactory.buildProtocol(None)
serverProtocol = AccumulatingProtocol(len(data))
serverFactory = ServerFactory()
serverFactory.protocol = lambda: serverProtocol
serverContextFactory = ServerTLSContext()
wrapperFactory = TLSMemoryBIOFactory(
serverContextFactory, False, serverFactory)
sslServerProtocol = wrapperFactory.buildProtocol(None)
connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol)
# Wait for the connection to end, then make sure the server received
# the bytes sent by the client.
def cbConnectionDone(ignored):
self.assertEqual(b"".join(serverProtocol.received), data)
connectionDeferred.addCallback(cbConnectionDone)
return connectionDeferred
def test_writeBeforeHandshake(self):
0
Source : test_tls.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_multipleWrites(self):
"""
If multiple separate TLS messages are received in a single chunk from
the underlying transport, all of the application bytes from each
message are delivered to the application-level protocol.
"""
data = [b'a', b'b', b'c', b'd', b'e', b'f', b'g', b'h', b'i']
class SimpleSendingProtocol(Protocol):
def connectionMade(self):
for b in data:
self.transport.write(b)
clientFactory = ClientFactory()
clientFactory.protocol = SimpleSendingProtocol
clientContextFactory = HandshakeCallbackContextFactory()
wrapperFactory = TLSMemoryBIOFactory(
clientContextFactory, True, clientFactory)
sslClientProtocol = wrapperFactory.buildProtocol(None)
serverProtocol = AccumulatingProtocol(sum(map(len, data)))
serverFactory = ServerFactory()
serverFactory.protocol = lambda: serverProtocol
serverContextFactory = ServerTLSContext()
wrapperFactory = TLSMemoryBIOFactory(
serverContextFactory, False, serverFactory)
sslServerProtocol = wrapperFactory.buildProtocol(None)
connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol, collapsingPumpPolicy)
# Wait for the connection to end, then make sure the server received
# the bytes sent by the client.
def cbConnectionDone(ignored):
self.assertEqual(b"".join(serverProtocol.received), b''.join(data))
connectionDeferred.addCallback(cbConnectionDone)
return connectionDeferred
def hugeWrite(self, method=TLSv1_METHOD):
0
Source : test_tls.py
with MIT License
from autofelix
with MIT License
from autofelix
def hugeWrite(self, method=TLSv1_METHOD):
"""
If a very long string is passed to L{TLSMemoryBIOProtocol.write}, any
trailing part of it which cannot be send immediately is buffered and
sent later.
"""
data = b"some bytes"
factor = 2 ** 20
class SimpleSendingProtocol(Protocol):
def connectionMade(self):
self.transport.write(data * factor)
clientFactory = ClientFactory()
clientFactory.protocol = SimpleSendingProtocol
clientContextFactory = HandshakeCallbackContextFactory(method=method)
wrapperFactory = TLSMemoryBIOFactory(
clientContextFactory, True, clientFactory)
sslClientProtocol = wrapperFactory.buildProtocol(None)
serverProtocol = AccumulatingProtocol(len(data) * factor)
serverFactory = ServerFactory()
serverFactory.protocol = lambda: serverProtocol
serverContextFactory = ServerTLSContext(method=method)
wrapperFactory = TLSMemoryBIOFactory(
serverContextFactory, False, serverFactory)
sslServerProtocol = wrapperFactory.buildProtocol(None)
connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol)
# Wait for the connection to end, then make sure the server received
# the bytes sent by the client.
def cbConnectionDone(ignored):
self.assertEqual(b"".join(serverProtocol.received), data * factor)
connectionDeferred.addCallback(cbConnectionDone)
return connectionDeferred
def test_hugeWrite_TLSv1(self):
0
Source : test_tls.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_loseConnectionAfterHandshake(self):
"""
L{TLSMemoryBIOProtocol.loseConnection} sends a TLS close alert and
shuts down the underlying connection cleanly on both sides, after
transmitting all buffered data.
"""
class NotifyingProtocol(ConnectionLostNotifyingProtocol):
def __init__(self, onConnectionLost):
ConnectionLostNotifyingProtocol.__init__(self,
onConnectionLost)
self.data = []
def dataReceived(self, data):
self.data.append(data)
clientConnectionLost = Deferred()
clientFactory = ClientFactory()
clientProtocol = NotifyingProtocol(clientConnectionLost)
clientFactory.protocol = lambda: clientProtocol
clientContextFactory, handshakeDeferred = (
HandshakeCallbackContextFactory.factoryAndDeferred())
wrapperFactory = TLSMemoryBIOFactory(
clientContextFactory, True, clientFactory)
sslClientProtocol = wrapperFactory.buildProtocol(None)
serverConnectionLost = Deferred()
serverProtocol = NotifyingProtocol(serverConnectionLost)
serverFactory = ServerFactory()
serverFactory.protocol = lambda: serverProtocol
serverContextFactory = ServerTLSContext()
wrapperFactory = TLSMemoryBIOFactory(
serverContextFactory, False, serverFactory)
sslServerProtocol = wrapperFactory.buildProtocol(None)
loopbackAsync(sslServerProtocol, sslClientProtocol)
chunkOfBytes = b"123456890" * 100000
# Wait for the handshake before dropping the connection.
def cbHandshake(ignored):
# Write more than a single bio_read, to ensure client will still
# have some data it needs to write when it receives the TLS close
# alert, and that simply doing a single bio_read won't be
# sufficient. Thus we will verify that any amount of buffered data
# will be written out before the connection is closed, rather than
# just small amounts that can be returned in a single bio_read:
clientProtocol.transport.write(chunkOfBytes)
serverProtocol.transport.write(b'x')
serverProtocol.transport.loseConnection()
# Now wait for the client and server to notice.
return gatherResults([clientConnectionLost, serverConnectionLost])
handshakeDeferred.addCallback(cbHandshake)
# Wait for the connection to end, then make sure the client and server
# weren't notified of a handshake failure that would cause the test to
# fail.
def cbConnectionDone(result):
(clientProtocol, serverProtocol) = result
clientProtocol.lostConnectionReason.trap(ConnectionDone)
serverProtocol.lostConnectionReason.trap(ConnectionDone)
# The server should have received all bytes sent by the client:
self.assertEqual(b"".join(serverProtocol.data), chunkOfBytes)
# The server should have closed its underlying transport, in
# addition to whatever it did to shut down the TLS layer.
self.assertTrue(serverProtocol.transport.q.disconnect)
# The client should also have closed its underlying transport once
# it saw the server shut down the TLS layer, so as to avoid relying
# on the server to close the underlying connection.
self.assertTrue(clientProtocol.transport.q.disconnect)
handshakeDeferred.addCallback(cbConnectionDone)
return handshakeDeferred
def test_connectionLostOnlyAfterUnderlyingCloses(self):
0
Source : inetdtap.py
with MIT License
from autofelix
with MIT License
from autofelix
def makeService(config):
s = appservice.MultiService()
conf = inetdconf.InetdConf()
with open(config['file']) as f:
conf.parseFile(f)
for service in conf.services:
protocol = service.protocol
if service.protocol.startswith('rpc/'):
log.msg('Skipping rpc service due to lack of rpc support')
continue
if (protocol, service.socketType) not in [('tcp', 'stream'),
('udp', 'dgram')]:
log.msg('Skipping unsupported type/protocol: %s/%s'
% (service.socketType, service.protocol))
continue
# Convert the username into a uid (if necessary)
try:
service.user = int(service.user)
except ValueError:
try:
service.user = pwd.getpwnam(service.user)[2]
except KeyError:
log.msg('Unknown user: ' + service.user)
continue
# Convert the group name into a gid (if necessary)
if service.group is None:
# If no group was specified, use the user's primary group
service.group = pwd.getpwuid(service.user)[3]
else:
try:
service.group = int(service.group)
except ValueError:
try:
service.group = grp.getgrnam(service.group)[2]
except KeyError:
log.msg('Unknown group: ' + service.group)
continue
if service.program == 'internal':
if config['nointernal']:
continue
# Internal services can use a standard ServerFactory
if service.name not in inetd.internalProtocols:
log.msg('Unknown internal service: ' + service.name)
continue
factory = ServerFactory()
factory.protocol = inetd.internalProtocols[service.name]
else:
factory = inetd.InetdFactory(service)
if protocol == 'tcp':
internet.TCPServer(service.port, factory).setServiceParent(s)
elif protocol == 'udp':
raise RuntimeError("not supporting UDP")
return s
0
Source : test_amp.py
with MIT License
from autofelix
with MIT License
from autofelix
def setUp(self):
"""
Create an amp server and connect a client to it.
"""
from twisted.internet import reactor
self.serverFactory = protocol.ServerFactory()
self.serverFactory.protocol = self.serverProto
self.clientFactory = protocol.ClientFactory()
self.clientFactory.protocol = self.clientProto
self.clientFactory.onMade = defer.Deferred()
self.serverFactory.onMade = defer.Deferred()
self.serverPort = reactor.listenTCP(0, self.serverFactory)
self.addCleanup(self.serverPort.stopListening)
self.clientConn = reactor.connectTCP(
'127.0.0.1', self.serverPort.getHost().port,
self.clientFactory)
self.addCleanup(self.clientConn.disconnect)
def getProtos(rlst):
self.cli = self.clientFactory.theProto
self.svr = self.serverFactory.theProto
dl = defer.DeferredList([self.clientFactory.onMade,
self.serverFactory.onMade])
return dl.addCallback(getProtos)
def tearDown(self):
See More Examples