Python twisted.application.internet.TCPServer() Examples

The following are 30 code examples of twisted.application.internet.TCPServer(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module twisted.application.internet , or try the search function .
Example #1
Source File: server.py    From worker with GNU General Public License v3.0 7 votes vote down vote up
def run():

    config.read()
    logs.api()

    top_service = service.MultiService()

    db = Db()
    datalib.db = db
    db.setServiceParent(top_service)

    http_service = internet.TCPServer(config.HTTP_PORT, Site(db), interface=config.HTTP_ADDR)
    http_service.setServiceParent(top_service)

    top_service.startService()

    reactor.addSystemEventTrigger('before', 'shutdown', top_service.stopService)

    reactor.run() 
Example #2
Source File: test_application.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def testSimpleInternet(self):
        # XXX - replace this test with one that does the same thing, but
        # with no web dependencies.
        if not gotMicrodom:
            raise unittest.SkipTest("Need twisted.web to run this test.")
        s = "(dp0\nS'udpConnectors'\np1\n(lp2\nsS'unixConnectors'\np3\n(lp4\nsS'twisted.internet.app.Application.persistenceVersion'\np5\nI12\nsS'name'\np6\nS'web'\np7\nsS'sslConnectors'\np8\n(lp9\nsS'sslPorts'\np10\n(lp11\nsS'tcpPorts'\np12\n(lp13\n(I8080\n(itwisted.web.server\nSite\np14\n(dp16\nS'resource'\np17\n(itwisted.web.demo\nTest\np18\n(dp19\nS'files'\np20\n(lp21\nsS'paths'\np22\n(dp23\nsS'tmpl'\np24\n(lp25\nS'\\n    Congratulations, twisted.web appears to work!\\n    <ul>\\n    <li>Funky Form:\\n    '\np26\naS'self.funkyForm()'\np27\naS'\\n    <li>Exception Handling:\\n    '\np28\naS'self.raiseHell()'\np29\naS'\\n    </ul>\\n    '\np30\nasS'widgets'\np31\n(dp32\nsS'variables'\np33\n(dp34\nsS'modules'\np35\n(lp36\nsS'children'\np37\n(dp38\nsbsS'logPath'\np39\nNsS'timeOut'\np40\nI43200\nsS'sessions'\np41\n(dp42\nsbI5\nS''\np43\ntp44\nasS'unixPorts'\np45\n(lp46\nsS'services'\np47\n(dp48\nsS'gid'\np49\nI1000\nsS'tcpConnectors'\np50\n(lp51\nsS'extraConnectors'\np52\n(lp53\nsS'udpPorts'\np54\n(lp55\nsS'extraPorts'\np56\n(lp57\nsS'persistStyle'\np58\nS'pickle'\np59\nsS'uid'\np60\nI1000\ns."
        d = pickle.loads(s)
        a = Dummy()
        a.__dict__ = d
        appl = compat.convert(a)
        self.assertEqual(service.IProcess(appl).uid, 1000)
        self.assertEqual(service.IProcess(appl).gid, 1000)
        self.assertEqual(service.IService(appl).name, "web")
        services = list(service.IServiceCollection(appl))
        self.assertEqual(len(services), 1)
        s = services[0]
        self.assertEqual(s.parent, service.IServiceCollection(appl))
        self.assert_(s.privileged)
        self.assert_(isinstance(s, internet.TCPServer))
        args = s.args
        self.assertEqual(args[0], 8080)
        self.assertEqual(args[3], '') 
Example #3
Source File: __init__.py    From opencanary with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def getService(self):
        """Return service to be run

        This handles the easy case where the CanaryService class is
        also the Factory/Datagram class. Subclasses should override
        this if more intricracy is needed.
        """
        if isinstance(self, Factory):
            return internet.TCPServer(self.port, self)
        elif isinstance(self, DatagramProtocol):
            return internet.UDPServer(self.port, self)

        err = 'The class %s does not inherit from either Factory or DatagramProtocol.' % (
            self.__class__.__name__
            )
        raise Exception(err) 
Example #4
Source File: test_application.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def testTCP(self):
        s = service.MultiService()
        s.startService()
        factory = protocol.ServerFactory()
        factory.protocol = TestEcho
        TestEcho.d = defer.Deferred()
        t = internet.TCPServer(0, factory)
        t.setServiceParent(s)
        num = t._port.getHost().port
        factory = protocol.ClientFactory()
        factory.d = defer.Deferred()
        factory.protocol = Foo
        factory.line = None
        internet.TCPClient('127.0.0.1', num, factory).setServiceParent(s)
        factory.d.addCallback(self.assertEqual, 'lalala')
        factory.d.addCallback(lambda x : s.stopService())
        factory.d.addCallback(lambda x : TestEcho.d)
        return factory.d 
Example #5
Source File: test_application.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def testPrivileged(self):
        factory = protocol.ServerFactory()
        factory.protocol = TestEcho
        TestEcho.d = defer.Deferred()
        t = internet.TCPServer(0, factory)
        t.privileged = 1
        t.privilegedStartService()
        num = t._port.getHost().port
        factory = protocol.ClientFactory()
        factory.d = defer.Deferred()
        factory.protocol = Foo
        factory.line = None
        c = internet.TCPClient('127.0.0.1', num, factory)
        c.startService()
        factory.d.addCallback(self.assertEqual, b'lalala')
        factory.d.addCallback(lambda x : c.stopService())
        factory.d.addCallback(lambda x : t.stopService())
        factory.d.addCallback(lambda x : TestEcho.d)
        return factory.d 
Example #6
Source File: test_application.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def testTCP(self):
        s = service.MultiService()
        s.startService()
        factory = protocol.ServerFactory()
        factory.protocol = TestEcho
        TestEcho.d = defer.Deferred()
        t = internet.TCPServer(0, factory)
        t.setServiceParent(s)
        num = t._port.getHost().port
        factory = protocol.ClientFactory()
        factory.d = defer.Deferred()
        factory.protocol = Foo
        factory.line = None
        internet.TCPClient('127.0.0.1', num, factory).setServiceParent(s)
        factory.d.addCallback(self.assertEqual, b'lalala')
        factory.d.addCallback(lambda x : s.stopService())
        factory.d.addCallback(lambda x : TestEcho.d)
        return factory.d 
Example #7
Source File: ftp.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def makeService(config):
    f = ftp.FTPFactory()

    r = ftp.FTPRealm(config['root'])
    p = portal.Portal(r)
    p.registerChecker(checkers.AllowAnonymousAccess(), credentials.IAnonymous)

    if config['password-file'] is not None:
        p.registerChecker(checkers.FilePasswordDB(config['password-file'], cache=True))

    f.tld = config['root']
    f.userAnonymous = config['userAnonymous']
    f.portal = p
    f.protocol = ftp.FTP
    
    try:
        portno = int(config['port'])
    except KeyError:
        portno = 2121
    return internet.TCPServer(portno, f) 
Example #8
Source File: ftp.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def makeService(config):
    f = ftp.FTPFactory()

    r = ftp.FTPRealm(config['root'])
    p = portal.Portal(r, config.get('credCheckers', []))

    f.tld = config['root']
    f.userAnonymous = config['userAnonymous']
    f.portal = p
    f.protocol = ftp.FTP

    try:
        portno = int(config['port'])
    except KeyError:
        portno = 2121
    return internet.TCPServer(portno, f) 
Example #9
Source File: tap.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def makeService(config):
    import client, cache, hosts

    ca, cl = [], []
    if config['cache']:
        ca.append(cache.CacheResolver(verbose=config['verbose']))
    if config['recursive']:
        cl.append(client.createResolver(resolvconf=config['resolv-conf']))
    if config['hosts-file']:
        cl.append(hosts.Resolver(file=config['hosts-file']))

    f = server.DNSServerFactory(config.zones, ca, cl, config['verbose'])
    p = dns.DNSDatagramProtocol(f)
    f.noisy = 0
    ret = service.MultiService()
    for (klass, arg) in [(internet.TCPServer, f), (internet.UDPServer, p)]:
        s = klass(config['port'], arg, interface=config['interface'])
        s.setServiceParent(ret)
    for svc in config.svcs:
        svc.setServiceParent(ret)
    return ret 
Example #10
Source File: service.py    From Kenshin with Apache License 2.0 6 votes vote down vote up
def createCacheService(options):
    from rurouni.cache import MetricCache
    from rurouni.protocols import CacheManagementHandler

    MetricCache.init()
    state.events.metricReceived.addHandler(MetricCache.put)
    root_service = createBaseService(options)

    factory = ServerFactory()
    factory.protocol = CacheManagementHandler
    service = TCPServer(int(settings.CACHE_QUERY_PORT), factory,
                        interface=settings.CACHE_QUERY_INTERFACE)
    service.setServiceParent(root_service)

    from rurouni.writer import WriterService
    service = WriterService()
    service.setServiceParent(root_service)

    return root_service 
Example #11
Source File: ftp.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def makeService(config):
    f = ftp.FTPFactory()

    r = ftp.FTPRealm(config['root'])
    p = portal.Portal(r)
    p.registerChecker(checkers.AllowAnonymousAccess(), credentials.IAnonymous)

    if config['password-file'] is not None:
        p.registerChecker(checkers.FilePasswordDB(config['password-file'], cache=True))

    f.tld = config['root']
    f.userAnonymous = config['userAnonymous']
    f.portal = p
    f.protocol = ftp.FTP
    
    try:
        portno = int(config['port'])
    except KeyError:
        portno = 2121
    return internet.TCPServer(portno, f) 
Example #12
Source File: test_application.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def testTCP(self):
        s = service.MultiService()
        s.startService()
        factory = protocol.ServerFactory()
        factory.protocol = TestEcho
        TestEcho.d = defer.Deferred()
        t = internet.TCPServer(0, factory)
        t.setServiceParent(s)
        num = t._port.getHost().port
        factory = protocol.ClientFactory()
        factory.d = defer.Deferred()
        factory.protocol = Foo
        factory.line = None
        internet.TCPClient('127.0.0.1', num, factory).setServiceParent(s)
        factory.d.addCallback(self.assertEqual, 'lalala')
        factory.d.addCallback(lambda x : s.stopService())
        factory.d.addCallback(lambda x : TestEcho.d)
        return factory.d 
Example #13
Source File: tap.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def makeService(config):
    import client, cache, hosts

    ca, cl = [], []
    if config['cache']:
        ca.append(cache.CacheResolver(verbose=config['verbose']))
    if config['recursive']:
        cl.append(client.createResolver(resolvconf=config['resolv-conf']))
    if config['hosts-file']:
        cl.append(hosts.Resolver(file=config['hosts-file']))

    f = server.DNSServerFactory(config.zones, ca, cl, config['verbose'])
    p = dns.DNSDatagramProtocol(f)
    f.noisy = 0
    ret = service.MultiService()
    for (klass, arg) in [(internet.TCPServer, f), (internet.UDPServer, p)]:
        s = klass(config['port'], arg, interface=config['interface'])
        s.setServiceParent(ret)
    for svc in config.svcs:
        svc.setServiceParent(ret)
    return ret 
Example #14
Source File: test_application.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def testPrivileged(self):
        factory = protocol.ServerFactory()
        factory.protocol = TestEcho
        TestEcho.d = defer.Deferred()
        t = internet.TCPServer(0, factory)
        t.privileged = 1
        t.privilegedStartService()
        num = t._port.getHost().port
        factory = protocol.ClientFactory()
        factory.d = defer.Deferred()
        factory.protocol = Foo
        factory.line = None
        c = internet.TCPClient('127.0.0.1', num, factory)
        c.startService()
        factory.d.addCallback(self.assertEqual, 'lalala')
        factory.d.addCallback(lambda x : c.stopService())
        factory.d.addCallback(lambda x : t.stopService())
        factory.d.addCallback(lambda x : TestEcho.d)
        return factory.d 
Example #15
Source File: test_application.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def testPrivileged(self):
        factory = protocol.ServerFactory()
        factory.protocol = TestEcho
        TestEcho.d = defer.Deferred()
        t = internet.TCPServer(0, factory)
        t.privileged = 1
        t.privilegedStartService()
        num = t._port.getHost().port
        factory = protocol.ClientFactory()
        factory.d = defer.Deferred()
        factory.protocol = Foo
        factory.line = None
        c = internet.TCPClient('127.0.0.1', num, factory)
        c.startService()
        factory.d.addCallback(self.assertEqual, b'lalala')
        factory.d.addCallback(lambda x : c.stopService())
        factory.d.addCallback(lambda x : t.stopService())
        factory.d.addCallback(lambda x : TestEcho.d)
        return factory.d 
Example #16
Source File: test_application.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def testTCP(self):
        s = service.MultiService()
        s.startService()
        factory = protocol.ServerFactory()
        factory.protocol = TestEcho
        TestEcho.d = defer.Deferred()
        t = internet.TCPServer(0, factory)
        t.setServiceParent(s)
        num = t._port.getHost().port
        factory = protocol.ClientFactory()
        factory.d = defer.Deferred()
        factory.protocol = Foo
        factory.line = None
        internet.TCPClient('127.0.0.1', num, factory).setServiceParent(s)
        factory.d.addCallback(self.assertEqual, b'lalala')
        factory.d.addCallback(lambda x : s.stopService())
        factory.d.addCallback(lambda x : TestEcho.d)
        return factory.d 
Example #17
Source File: socksmon.py    From socksmon with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def main():
    with open('/tmp/server.pem', 'rb') as fp:
        certData = fp.read()
    sslcert = ssl.PrivateCertificate.loadPEM(certData)

    logging.basicConfig(level=logging.INFO)

    socks = MySOCKSv4Factory("http://127.0.0.1:2357", "http://127.0.0.1:8080", sslcert)
    socks.protocol = MySOCKSv4

    srv = service.MultiService()
    srv.addService(internet.TCPServer(9050, socks))
    srv.addService(internet.TCPServer(2357, server.Site(WebEchoService())))

    application = service.Application("Receive Request")
    srv.setServiceParent(application)
    srv.startService()
    reactor.run() 
Example #18
Source File: ftp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def makeService(config):
    f = ftp.FTPFactory()

    r = ftp.FTPRealm(config['root'])
    p = portal.Portal(r, config.get('credCheckers', []))

    f.tld = config['root']
    f.userAnonymous = config['userAnonymous']
    f.portal = p
    f.protocol = ftp.FTP

    try:
        portno = int(config['port'])
    except KeyError:
        portno = 2121
    return internet.TCPServer(portno, f) 
Example #19
Source File: twisted.py    From anchore-engine with Apache License 2.0 5 votes vote down vote up
def makeDebugCLIService(self, args):
        """
        This is dangerous, and should only ever be enabled by explicit user config and only for non-production use

        :param args:
        :return:
        """

        f = protocol.ServerFactory()
        f.protocol = lambda: TelnetTransport(TelnetBootstrapProtocol,
                                             insults.ServerProtocol,
                                             args['protocolFactory'],
                                             *args.get('protocolArgs', ()),
                                             **args.get('protocolKwArgs', {}))
        return internet.TCPServer(args['telnet'], f) 
Example #20
Source File: test_application.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def testUDP(self):
        if not interfaces.IReactorUDP(reactor, None):
            raise unittest.SkipTest, "This reactor does not support UDP sockets"
        p = protocol.DatagramProtocol()
        t = internet.TCPServer(0, p)
        t.startService()
        num = t._port.getHost().port
        def onStop(ignored):
            t = internet.TCPServer(num, p)
            t.startService()
            return t.stopService()
        return defer.maybeDeferred(t.stopService).addCallback(onStop) 
Example #21
Source File: inetdtap.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def startService(self):
        internet.TCPServer.startService(self)
        import portmap
        portNo = self._port.getHost()[2]
        service = self.service
        for version in rpcVersions:
            portmap.set(self.rpcConf.services[name], version, self.proto,
                        portNo)
            inetd.forkPassingFD(service.program, service.programArgs,
                                os.environ, service.user, service.group, p) 
Example #22
Source File: server.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def startService(self):
        internet.TCPServer.startService(self)
        self.update_nginx()
        signal.signal(signal.SIGUSR1, lambda signum, frame: reactor.callFromThread(self.on_SIGUSR1))
        port = reactor.listenTCP(0, CanvasManholeFactory())
        file('manhole.port', 'w').write(str(port.getHost().port)) 
Example #23
Source File: test_application.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #24
Source File: compat.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def listenTCP(self, port, factory, backlog=50, interface=''):
        s = internet.TCPServer(port, factory, backlog, interface)
        s.privileged = 1
        s.setServiceParent(self.app) 
Example #25
Source File: server.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self):
        port = 0 # Let the OS assign us a free port
        internet.TCPServer.__init__(self, port, get_site(production=settings.PRODUCTION)) 
Example #26
Source File: test_application.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
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 
Example #27
Source File: socks.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def makeService(config):
    if config["interface"] != "127.0.0.1":
        print
        print "WARNING:"
        print "  You have chosen to listen on a non-local interface."
        print "  This may allow intruders to access your local network"
        print "  if you run this on a firewall."
        print
    t = socks.SOCKSv4Factory(config['log'])
    portno = int(config['port'])
    return internet.TCPServer(portno, t, interface=config['interface']) 
Example #28
Source File: app.py    From scrapy-do with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _configure_web_server(self, config, controller):
        interfaces, https, key_file, cert_file, chain_file, _, _ = \
            self._validate_web_config(config)

        site = server.Site(get_web_app(config, controller))
        web_servers = []

        for interface, port in interfaces:
            if https:
                cf = SSLCertOptions(key_file, cert_file, chain_file)
                web_server = SSLServer(port, site, cf, interface=interface)
                method = 'https'
            else:
                web_server = TCPServer(port, site, interface=interface)
                method = 'http'

            web_servers.append(web_server)

            if ':' in interface:
                interface = '[{}]'.format(interface)
            log.msg(format="Scrapy-Do web interface is available at "
                           "%(method)s://%(interface)s:%(port)s/",
                    method=method, interface=interface, port=port)

        return web_servers

    #--------------------------------------------------------------------------- 
Example #29
Source File: pyrdp_plugin.py    From pyrdp with GNU General Public License v3.0 5 votes vote down vote up
def makeService(self, options):
        """
        Construct a TCPServer from a MITMServerFactory
        """
        config = options['config']
        return internet.TCPServer(config.listenPort, MITMServerFactory(config)) 
Example #30
Source File: test_caldav.py    From ccs-calendarserver with Apache License 2.0 5 votes vote down vote up
def test_listenBacklog(self):
        """
        Test that the backlog arguments is set in TCPServer and SSLServers
        """
        # Note: the listeners are bundled within a MultiService named "ConnectionService"
        service = CalDAVServiceMaker().makeService(self.options)
        service = service.getServiceNamed(CalDAVService.connectionServiceName)

        for s in service.services:
            if isinstance(s, (internet.TCPServer, internet.SSLServer)):
                self.assertEquals(s.kwargs["backlog"], 1024)