Example #1
0
 def testModedUNIX(self):
     self.assertEqual(
         strports.parse('unix:/var/run/finger:mode=0660', self.f),
         ('UNIX', ('/var/run/finger', self.f), {
             'mode': 0660,
             'backlog': 50
         }))
Example #2
0
def makeService(config):
	from twisted.internet import reactor, task

	multi = service.MultiService()

	domain = config['domain']
	mutils.maybeWarnAboutDomain(reactor, domain)

	closureLibrary = FilePath(config['closure-library'])
	mutils.maybeWarnAboutClosureLibrary(reactor, closureLibrary)

	socketPorts = []
	for minervaStrport in config['minerva']:
		_, _args, _ = strports.parse(minervaStrport, object())
		socketPorts.append(_args[0])

	doReloading = bool(int(os.environ.get('PYRELOADING', '0')))
	fileCache = FileCache(lambda: reactor.seconds(), 0.1 if doReloading else -1)
	stf, httpSite = demosminerva_site.makeMinervaAndHttp(
		reactor, fileCache, socketPorts, domain, closureLibrary)
	httpSite.displayTracebacks = not config["no-tracebacks"]

	for httpStrport in config['http']:
		httpServer = strports.service(httpStrport, httpSite)
		httpServer.setServiceParent(multi)

	for minervaStrport in config['minerva']:
		minervaServer = strports.service(minervaStrport, stf)
		minervaServer.setServiceParent(multi)

	if doReloading:
		mutils.enablePyquitter(reactor)

	return multi
Example #3
0
 def testImpliedEscape(self):
     self.assertEqual(strports.parse(r'unix:address=foo=bar', self.f),
                      ('UNIX', ('foo=bar', self.f), {
                          'mode': 0666,
                          'backlog': 50,
                          'wantPID': True
                      }))
Example #4
0
 def testNonstandardDefault(self):
     self.assertEqual(strports.parse('filename', self.f, 'unix'),
                      ('UNIX', ('filename', self.f), {
                          'mode': 0666,
                          'backlog': 50,
                          'wantPID': True
                      }))
Example #5
0
def makeService(config):
    from twisted.internet import reactor

    multi = service.MultiService()

    domain = config['domain']
    mutils.maybeWarnAboutDomain(reactor, domain)

    closureLibrary = FilePath(config['closure-library'])
    mutils.maybeWarnAboutClosureLibrary(reactor, closureLibrary)

    socketPorts = []
    for minervaStrport in config['minerva']:
            _, _args, _ = strports.parse(minervaStrport, object())
            socketPorts.append(_args[0])

    fileCache = FileCache(lambda: reactor.seconds(), -1)
    stf, httpSite = site.setupMinerva(
            reactor, fileCache, socketPorts, domain, closureLibrary
    )
    httpSite.displayTracebacks = not config["no-tracebacks"]

    for httpStrport in config['http']:
            httpServer = strports.service(httpStrport, httpSite)
            httpServer.setServiceParent(multi)

    for minervaStrport in config['minerva']:
            minervaServer = strports.service(minervaStrport, stf)
            minervaServer.setServiceParent(multi)

    return multi
Example #6
0
 def testEscape(self):
     self.assertEqual(strports.parse(r'unix:foo\:bar\=baz\:qux\\', self.f),
                      ('UNIX', ('foo:bar=baz:qux\\', self.f), {
                          'mode': 0666,
                          'backlog': 50,
                          'wantPID': True
                      }))
Example #7
0
 def test_modeUNIX(self):
     """
     C{mode} can be set by including C{"mode=<some integer>"}.
     """
     self.assertEqual(
         strports.parse('unix:/var/run/finger:mode=0660', self.f),
         ('UNIX', ('/var/run/finger', self.f),
          {'mode': 0660, 'backlog': 50, 'wantPID': True}))
Example #8
0
 def test_wantPIDUNIX(self):
     """
     C{wantPID} can be set to false by included C{"lockfile=0"}.
     """
     self.assertEqual(
         strports.parse('unix:/var/run/finger:lockfile=0', self.f),
         ('UNIX', ('/var/run/finger', self.f),
          {'mode': 0666, 'backlog': 50, 'wantPID': False}))
Example #9
0
 def test_defaultPort(self):
     """
     If the I{--port} option is not specified, L{Options} defaults the port
     to C{8080}.
     """
     options = Options()
     options.parseOptions([])
     self.assertEqual(strports.parse(options["port"], None)[:2], ("TCP", (8080, None)))
Example #10
0
 def test_defaultPort(self):
     """
     If the I{--port} option is not specified, L{Options} defaults the port
     to C{8080}.
     """
     options = Options()
     options.parseOptions([])
     self.assertEqual(
         strports.parse(options['port'], None)[:2], ('TCP', (8080, None)))
Example #11
0
 def parse(self, *a, **kw):
     result = strports.parse(*a, **kw)
     warnings = self.flushWarnings([self.parse])
     self.assertEqual(len(warnings), 1)
     self.assertEqual(
         warnings[0]['message'],
         "twisted.application.strports.parse was deprecated "
         "in Twisted 10.2.0: in favor of twisted.internet.endpoints.serverFromString")
     return result
Example #12
0
 def test_simpleUNIX(self):
     """
     L{strports.parse} returns a C{'UNIX'} port description with defaults
     for C{'mode'}, C{'backlog'}, and C{'wantPID'} when passed a string with
     the C{'unix:'} prefix and no other parameter values.
     """
     self.assertEqual(
         strports.parse('unix:/var/run/finger', self.f),
         ('UNIX', ('/var/run/finger', self.f),
          {'mode': 0666, 'backlog': 50, 'wantPID': True}))
Example #13
0
 def test_defaultPersonalPath(self):
     """
     If the I{--port} option not specified but the I{--personal} option is,
     L{Options} defaults the port to C{UserDirectory.userSocketName} in the
     user's home directory.
     """
     options = Options()
     options.parseOptions(["--personal"])
     path = os.path.expanduser(os.path.join("~", UserDirectory.userSocketName))
     self.assertEqual(strports.parse(options["port"], None)[:2], ("UNIX", (path, None)))
Example #14
0
 def parse(self, *a, **kw):
     result = strports.parse(*a, **kw)
     warnings = self.flushWarnings([self.parse])
     self.assertEqual(len(warnings), 1)
     self.assertEqual(
         warnings[0]['message'],
         "twisted.application.strports.parse was deprecated "
         "in Twisted 10.2.0: in favor of twisted.internet.endpoints.serverFromString"
     )
     return result
Example #15
0
 def test_modeUNIX(self):
     """
     C{mode} can be set by including C{"mode=<some integer>"}.
     """
     self.assertEqual(
         strports.parse('unix:/var/run/finger:mode=0660', self.f),
         ('UNIX', ('/var/run/finger', self.f), {
             'mode': 0660,
             'backlog': 50,
             'wantPID': True
         }))
Example #16
0
 def test_wantPIDUNIX(self):
     """
     C{wantPID} can be set to false by included C{"lockfile=0"}.
     """
     self.assertEqual(
         strports.parse('unix:/var/run/finger:lockfile=0', self.f),
         ('UNIX', ('/var/run/finger', self.f), {
             'mode': 0666,
             'backlog': 50,
             'wantPID': False
         }))
Example #17
0
 def test_simpleUNIX(self):
     """
     L{strports.parse} returns a C{'UNIX'} port description with defaults
     for C{'mode'}, C{'backlog'}, and C{'wantPID'} when passed a string with
     the C{'unix:'} prefix and no other parameter values.
     """
     self.assertEqual(strports.parse('unix:/var/run/finger', self.f),
                      ('UNIX', ('/var/run/finger', self.f), {
                          'mode': 0666,
                          'backlog': 50,
                          'wantPID': True
                      }))
Example #18
0
 def test_defaultPersonalPath(self):
     """
     If the I{--port} option not specified but the I{--personal} option is,
     L{Options} defaults the port to C{UserDirectory.userSocketName} in the
     user's home directory.
     """
     options = Options()
     options.parseOptions(['--personal'])
     path = os.path.expanduser(
         os.path.join('~', UserDirectory.userSocketName))
     self.assertEqual(
         strports.parse(options['port'], None)[:2], ('UNIX', (path, None)))
Example #19
0
def _strport_to_url(desc, scheme='http', path='/'):
	'''Construct a URL from a twisted.application.strports string.'''
	# TODO: need to know canonical domain name, not localhost; can we extract from the ssl cert?
	# TODO: strports.parse is deprecated
	(method, args, kwargs) = strports.parse(desc, None)
	if method == 'TCP':
		return scheme + '://localhost:' + str(args[0]) + path
	elif method == 'SSL':
		return scheme + 's://localhost:' + str(args[0]) + path
	else:
		# TODO better error return
		return '???'
Example #20
0
def strport_to_url(desc, scheme='http', hostname='localhost', path='/', socket_port=0):
    """Construct a URL from a twisted.application.strports string."""
    # TODO: strports.parse is deprecated but nothing seems to replace it for this purpose
    (method, args, _) = strports.parse(desc, None)
    if socket_port == 0:
        socket_port = args[0]
    if method == 'TCP':
        return scheme + '://' + hostname + ':' + str(socket_port) + path
    elif method == 'SSL':
        return scheme + 's://' + hostname + ':' + str(socket_port) + path
    else:
        # TODO better error return
        return '???'
Example #21
0
def strport_to_url(desc, scheme='http', hostname='localhost', path='/', socket_port=0):
    """Construct a URL from a twisted.application.strports string."""
    # TODO: strports.parse is deprecated but nothing seems to replace it for this purpose
    (method, args, _) = strports.parse(desc, None)
    if socket_port == 0:
        socket_port = args[0]
    if method == 'TCP':
        return scheme + '://' + hostname + ':' + str(socket_port) + path
    elif method == 'SSL':
        return scheme + 's://' + hostname + ':' + str(socket_port) + path
    else:
        # TODO better error return
        return '???'
Example #22
0
 def __init__(self, port, options={}):
     """
     @type port: string
     @param port: a L{twisted.application.strports} -style description.
     """
     name, args, kw = strports.parse(port, None)
     assert name in ("TCP", "UNIX")  # TODO: IPv6
     self.port = port
     self.options = options
     self.parentTub = None
     self.tubs = {}
     self.redirects = {}
     self.s = strports.service(port, self)
     Listeners.append(self)
Example #23
0
 def __init__(self, port, options={}):
     """
     @type port: string
     @param port: a L{twisted.application.strports} -style description.
     """
     name, args, kw = strports.parse(port, None)
     assert name in ("TCP", "UNIX")  # TODO: IPv6
     self.port = port
     self.options = options
     self.parentTub = None
     self.tubs = {}
     self.redirects = {}
     self.s = strports.service(port, self)
     Listeners.append(self)
Example #24
0
def _strport_to_url(desc, scheme='http', path='/', socket_port=0):
    '''Construct a URL from a twisted.application.strports string.'''
    # TODO: need to know canonical domain name, not localhost; can we extract from the ssl cert?
    # TODO: strports.parse is deprecated
    (method, args, _) = strports.parse(desc, None)
    if socket_port == 0:
        socket_port = args[0]
    if method == 'TCP':
        return scheme + '://localhost:' + str(socket_port) + path
    elif method == 'SSL':
        return scheme + 's://localhost:' + str(socket_port) + path
    else:
        # TODO better error return
        return '???'
Example #25
0
    def getPortnum(self):
        """When this Listener was created with a strport string of '0' or
        'tcp:0' (meaning 'please allocate me something'), and if the Listener
        is active (it is attached to a Tub which is in the 'running' state),
        this method will return the port number that was allocated. This is
        useful for the following pattern:

         t = PBService()
         l = t.listenOn('tcp:0')
         t.setLocation('localhost:%d' % l.getPortnum())
        """

        assert self.s.running
        name, args, kw = strports.parse(self.port, None)
        assert name in ("TCP", )
        return self.s._port.getHost().port
Example #26
0
    def getPortnum(self):
        """When this Listener was created with a strport string of '0' or
        'tcp:0' (meaning 'please allocate me something'), and if the Listener
        is active (it is attached to a Tub which is in the 'running' state),
        this method will return the port number that was allocated. This is
        useful for the following pattern:

         t = PBService()
         l = t.listenOn('tcp:0')
         t.setLocation('localhost:%d' % l.getPortnum())
        """

        assert self.s.running
        name, args, kw = strports.parse(self.port, None)
        assert name in ("TCP",)
        return self.s._port.getHost().port
Example #27
0
        def helper(name, config, transport_names):
            # Helper closure passed to / called by L{_loadItemsFromConfig}
            # This will keep track of configured transports in transport_names
            # and set up a transport if applicable
            transport_names.add(name)

            # If this transport (or another with this name, which would be a
            # configuration error) is already registered, just ignore this
            # configuration item
            if name in self.registered_transports:
                return None

            log.msg('[CONTROLLER] Configuring transport %s' % name)
            # Create a transport (L{ITransport}) using the given configuration
            transport = self.loadTransport(name, config)

            # If the transport is an L{IServerTransport}...
            if IServerTransport.providedBy(transport):
                # Create a L{twisted.application.service.IService} from it
                # using settings provided in C{config}. This is *not* an
                # applicationserver  service but a Twisted service, ie a
                # server handling incoming requests on a given socket.
                service = self.hookTransport(transport, config)
                # Set the IService name
                service.setName(name)
                # Set the IService parent to our MultiTransport
                service.setServiceParent(self.transports)

                # Parse the transport settings again so we can set up an
                # L{ITransportInfo} object for this transport
                port_info = strports.parse(config['transport'], transport)
                transport_info = transport.getTransportInfo(name, port_info)
                # Store the L{ITransportInfo}
                self.transport_info_map[name] = transport_info

                # Finally return the service
                return service
            else:
                # Set up the L{ITransportInfo} for the transport
                transport_info = transport.getTransportInfo(name)
                # Save it
                self.transport_info_map[name] = transport_info

                # And return it. We don't know how to handle this further,
                # since this is not an L{IServerTransport}, most likely the
                # 'mail' transport.
                return transport
Example #28
0
        def helper(name, config, transport_names):
            # Helper closure passed to / called by L{_loadItemsFromConfig}
            # This will keep track of configured transports in transport_names
            # and set up a transport if applicable
            transport_names.add(name)

            # If this transport (or another with this name, which would be a
            # configuration error) is already registered, just ignore this
            # configuration item
            if name in self.registered_transports:
                return None

            log.msg('[CONTROLLER] Configuring transport %s' % name)
            # Create a transport (L{ITransport}) using the given configuration
            transport = self.loadTransport(name, config)

            # If the transport is an L{IServerTransport}...
            if IServerTransport.providedBy(transport):
                # Create a L{twisted.application.service.IService} from it
                # using settings provided in C{config}. This is *not* an
                # applicationserver  service but a Twisted service, ie a 
                # server handling incoming requests on a given socket.
                service = self.hookTransport(transport, config)
                # Set the IService name
                service.setName(name)
                # Set the IService parent to our MultiTransport
                service.setServiceParent(self.transports)

                # Parse the transport settings again so we can set up an
                # L{ITransportInfo} object for this transport
                port_info = strports.parse(config['transport'], transport)
                transport_info = transport.getTransportInfo(name, port_info)
                # Store the L{ITransportInfo}
                self.transport_info_map[name] = transport_info

                # Finally return the service
                return service
            else:
                # Set up the L{ITransportInfo} for the transport
                transport_info = transport.getTransportInfo(name)
                # Save it
                self.transport_info_map[name] = transport_info

                # And return it. We don't know how to handle this further,
                # since this is not an L{IServerTransport}, most likely the
                # 'mail' transport.
                return transport
Example #29
0
    def postOptions(self):
        strport = self['strport']
        factoryIdentifier = self['factory-identifier']
        if strport is None or factoryIdentifier is None:
            self.opt_help()

        store = self.parent.parent.getStore()
        storeID = int(factoryIdentifier)
        try:
            factory = store.getItemByID(storeID)
        except KeyError:
            print "%d does not identify an item." % (storeID,)
            raise SystemExit(1)
        else:
            if not IProtocolFactoryFactory.providedBy(factory):
                print "%d does not identify a factory." % (storeID,)
                raise SystemExit(1)
            else:
                try:
                    kind, args, kwargs = parse(strport, factory)
                except ValueError:
                    print "%r is not a valid port description." % (strport,)
                    raise SystemExit(1)
                except KeyError:
                    print "Unrecognized port type."
                    raise SystemExit(1)
                except SSL.Error, e:
                    if self._pemFormatError in e.args[0]:
                        print 'Certificate file must use PEM format.'
                        raise SystemExit(1)
                    elif self._noSuchFileError in e.args[0]:
                        if self._certFileError in e.args[0]:
                            print "Specified certificate file does not exist."
                            raise SystemExit(1)
                        elif self._keyFileError in e.args[0]:
                            print "Specified private key file does not exist."
                            raise SystemExit(1)
                        else:
                            # Note, no test coverage.
                            raise
                    else:
                        # Note, no test coverage.
                        raise
                else:
                    try:
Example #30
0
 def testModedUNIX(self):
     self.assertEqual(strports.parse('unix:/var/run/finger:mode=0660',
                                     self.f),
                      ('UNIX', ('/var/run/finger', self.f),
                              {'mode':0660, 'backlog':50}))
Example #31
0
 def testNonstandardDefault(self):
     self.assertEqual(
         strports.parse('filename', self.f, 'unix'),
         ('UNIX', ('filename', self.f),
          {'mode': 0666, 'backlog': 50, 'wantPID': True}))
Example #32
0
 def testImpliedEscape(self):
     self.assertEqual(
         strports.parse(r'unix:address=foo=bar', self.f),
         ('UNIX', ('foo=bar', self.f),
          {'mode': 0666, 'backlog': 50, 'wantPID': True}))
Example #33
0
 def testEscape(self):
     self.assertEqual(
         strports.parse(r'unix:foo\:bar\=baz\:qux\\', self.f),
         ('UNIX', ('foo:bar=baz:qux\\', self.f),
          {'mode': 0666, 'backlog': 50, 'wantPID': True}))
Example #34
0
 def testAllKeywords(self):
     self.assertEqual(strports.parse('port=80', self.f),
                      ('TCP', (80, self.f), {'interface':'', 'backlog':50}))
Example #35
0
 def testSimpleTCP(self):
     self.assertEqual(strports.parse('tcp:80', self.f),
                      ('TCP', (80, self.f), {
                          'interface': '',
                          'backlog': 50
                      }))
Example #36
0
 def testSimpleUnix(self):
     self.assertEqual(strports.parse('unix:/var/run/finger', self.f),
                      ('UNIX', ('/var/run/finger', self.f),
                              {'mode':0666, 'backlog':50}))
Example #37
0
 def testBacklogTCP(self):
     self.assertEqual(strports.parse('tcp:80:backlog=6', self.f),
                      ('TCP', (80, self.f), {
                          'interface': '',
                          'backlog': 6
                      }))
Example #38
0
 def testBacklogTCP(self):
     self.assertEqual(strports.parse('tcp:80:backlog=6', self.f),
                      ('TCP', (80, self.f),
                              {'interface':'', 'backlog':6}))
Example #39
0
 def testSimpleTCP(self):
     self.assertEqual(strports.parse('tcp:80', self.f),
                      ('TCP', (80, self.f), {'interface':'', 'backlog':50}))
Example #40
0
 def testAllKeywords(self):
     self.assertEqual(strports.parse('port=80', self.f),
                      ('TCP', (80, self.f), {
                          'interface': '',
                          'backlog': 50
                      }))
Example #41
0
def valid_strport(value):
    try:
        strports.parse( value, default='tcp:5775' )
    except (ValueError, KeyError) as err:
        raise argparse.ArgumentTypeError(*err.args)
    return value 
Example #42
0
 def testInterfaceTCP(self):
     self.assertEqual(strports.parse('tcp:80:interface=127.0.0.1', self.f),
                      ('TCP', (80, self.f), {
                          'interface': '127.0.0.1',
                          'backlog': 50
                      }))
Example #43
0
 def testInterfaceTCP(self):
     self.assertEqual(strports.parse('tcp:80:interface=127.0.0.1', self.f),
                      ('TCP', (80, self.f),
                              {'interface':'127.0.0.1', 'backlog':50}))
Example #44
0
 def testSimpleUnix(self):
     self.assertEqual(strports.parse('unix:/var/run/finger', self.f),
                      ('UNIX', ('/var/run/finger', self.f), {
                          'mode': 0666,
                          'backlog': 50
                      }))