Example #1
0
 def _startTLS(self):
     self.TLS = 1
     klass = self.__class__
     class TLSConnection(_TLSMixin, klass):
         implements(interfaces.ISSLTransport)
     components.backwardsCompatImplements(TLSConnection)
     self.__class__ = TLSConnection
Example #2
0
def _getTLSClass(klass, _existing={}):
    if klass not in _existing:
        class TLSConnection(_TLSMixin, klass):
            implements(interfaces.ISSLTransport)
        components.backwardsCompatImplements(TLSConnection)
        _existing[klass] = TLSConnection
    return _existing[klass]
Example #3
0
def _getTLSClass(klass, _existing={}):
    if klass not in _existing:

        class TLSConnection(_TLSMixin, klass):
            implements(interfaces.ISSLTransport)

        components.backwardsCompatImplements(TLSConnection)
        _existing[klass] = TLSConnection
    return _existing[klass]
    def testClassIsGCd(self):
        import weakref, gc
        class Test(object):
            zinterface.implements(IZope)
        # Do some stuff with it
        components.backwardsCompatImplements(Test)
        IZope(Test())

        # Make a weakref to it, then ensure the weakref goes away
        r = weakref.ref(Test)
        del Test
        gc.collect()
        self.assertEquals(r(), None)
Example #5
0
          def removeAll(self):
              return self._removeAll(reads, writes)
        where reads, writes are iterables.
        """
        readers = [reader for reader in readers if 
                   reader is not self.waker]

        readers_dict = {}
        for reader in readers:
            readers_dict[reader] = 1
            
        for reader in readers:
            self.removeReader(reader)
            self.removeWriter(reader)

        writers = [writer for writer in writers if
                   writer not in readers_dict]
        for writer in writers:
            self.removeWriter(writer)
        
        return readers+writers


if sslEnabled:
    classImplements(PosixReactorBase, IReactorSSL)
if unixEnabled:
    classImplements(PosixReactorBase, IReactorUNIX, IReactorUNIXDatagram, IReactorProcess)
components.backwardsCompatImplements(PosixReactorBase)

__all__ = ["PosixReactorBase"]
Example #6
0
    def registerProducer(self, producer, streaming):
        self.producer = producer
        self.producerIsStreaming = streaming

    def unregisterProducer(self):
        if self.producer is not None:
            del self.producer
            del self.producerIsStreaming
        if self.consumer:
            self.consumer.unregisterProducer()

    def __repr__(self):
        return '<%s@%x around %s>' % (self.__class__, id(self), self.consumer)

components.backwardsCompatImplements(BasicProducerConsumerProxy)


class ProducerConsumerProxy(BasicProducerConsumerProxy):
    """ProducerConsumerProxy with a finite buffer.

    When my buffer fills up, I have my parent Producer pause until my buffer
    has room in it again.
    """
    # Copies much from abstract.FileDescriptor
    bufferSize = 2**2**2**2

    producerPaused = False
    unregistered = False

    def pauseProducing(self):
Example #7
0
        for text in self.inputCache:
            self.pushThroughInputConduit(text)
        self.inputCache = []
        print "DONE HOOKING", self.inputCache

    def pushThroughInputConduit(self, inp):
        """Push some text through the input conduit.
        """
        print "PUSHING INPUT", inp
        if self.input is None:
            self.inputCache.append(inp)
        else:
            self.input(inp)


components.backwardsCompatImplements(WovenLivePage)


class Stack:
    def __init__(self, stack=None):
        if stack is None:
            self.stack = []
        else:
            self.stack = stack

    def push(self, item):
        self.stack.insert(0, item)

    def pop(self):
        if self.stack:
            return self.stack.pop(0)
Example #8
0
    def registerProducer(self, producer, streaming):
        self.producer = producer
        self.producerIsStreaming = streaming

    def unregisterProducer(self):
        if self.producer is not None:
            del self.producer
            del self.producerIsStreaming
        if self.consumer:
            self.consumer.unregisterProducer()

    def __repr__(self):
        return '<%s@%x around %s>' % (self.__class__, id(self), self.consumer)


components.backwardsCompatImplements(BasicProducerConsumerProxy)


class ProducerConsumerProxy(BasicProducerConsumerProxy):
    """ProducerConsumerProxy with a finite buffer.

    When my buffer fills up, I have my parent Producer pause until my buffer
    has room in it again.
    """
    # Copies much from abstract.FileDescriptor
    bufferSize = 2**2**2**2

    producerPaused = False
    unregistered = False

    def pauseProducing(self):
Example #9
0
    def getTcpNoDelay(self):
        return operator.truth(self.socket.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY))

    def setTcpNoDelay(self, enabled):
        self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, enabled)

    def getTcpKeepAlive(self):
        return operator.truth(self.socket.getsockopt(socket.SOL_SOCKET,
                                                     socket.SO_KEEPALIVE))

    def setTcpKeepAlive(self, enabled):
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, enabled)

if SSL:
    classImplements(Connection, interfaces.ITLSTransport)
components.backwardsCompatImplements(Connection)


class BaseClient(Connection):
    """A base class for client TCP (and similiar) sockets.
    """
    addressFamily = socket.AF_INET
    socketType = socket.SOCK_STREAM

    def _finishInit(self, whenDone, skt, error, reactor):
        """Called by base classes to continue to next stage of initialization."""
        if whenDone:
            Connection.__init__(self, skt, None, reactor)
            self.doWrite = self.doConnect
            self.doRead = self.doConnect
            reactor.callLater(0, whenDone)
Example #10
0
        self.services = {}
    def getServiceNamed(self, serviceName):
        """Retrieve the named service from this application.
        Raise a KeyError if there is no such service name.
        """
        return self.services[serviceName]
    def addService(self, service):
        """Add a service to this collection.
        """
        if self.services.has_key(service.serviceName):
            self.removeService(service)
        self.services[service.serviceName] = service
    def removeService(self, service):
        """Remove a service from this collection."""
        del self.services[service.serviceName]
components.backwardsCompatImplements(_AbstractServiceCollection)
class ApplicationService(Accessor, styles.Versioned):
    """I am a service you can add to an application.
    I represent some chunk of functionality which may be bound to many or no
    event sources.  By adding an ApplicationService to an L{Application}, it
    will be notified when the Application starts and stops (or removes/shuts
    down the service).  See the L{startService} and L{stopService} calls.
    Since services may want to incorporate certain other elements,
    notably Perspective Broker (remote invocation) accessibility
    and authentication, derivatives of ApplicationService exist
    in L{twisted.cred.service<twisted.cred.service.Service>} and
    L{twisted.spread.pb<twisted.spread.pb.Service>}.  These may be more
    suitable for your service than directly subclassing ApplicationService.
    """
    serviceType = None
    serviceName = None
Example #11
0
        t = time.time()
        self.challenge = '<%d.%d@%s>' % (r, t, self.host)
        return self.challenge

    def setResponse(self, response):
        self.username, self.response = response.split(None, 1)

    def moreChallenges(self):
        return False

    def checkPassword(self, password):
        verify = hmac.HMAC(password, self.challenge).hexdigest()
        return verify == self.response


components.backwardsCompatImplements(CramMD5Credentials)


class UsernameHashedPassword:
    interface.implements(IUsernameHashedPassword)

    def __init__(self, username, hashed):
        self.username = username
        self.hashed = hashed

    def checkPassword(self, password):
        return self.hashed == password


components.backwardsCompatImplements(UsernameHashedPassword)
Example #12
0
    def simulate(self):
        """Run simulation loops and reschedule callbacks.
        """
        global _simtag
        if _simtag is not None:
            gobject.source_remove(_simtag)
        self.runUntilCurrent()
        timeout = min(self.timeout(), 0.1)
        if timeout is None:
            timeout = 0.1
        # grumble
        _simtag = gobject.timeout_add(int(timeout * 1010), self.simulate)


components.backwardsCompatImplements(Gtk2Reactor)


class PortableGtkReactor(selectreactor.SelectReactor):
    """Reactor that works on Windows.

    input_add is not supported on GTK+ for Win32, apparently.
    """
    def crash(self):
        import gtk
        # mainquit is deprecated in newer versions
        if hasattr(gtk, 'main_quit'):
            gtk.main_quit()
        else:
            gtk.mainquit()
Example #13
0
def loadApplication(filename, kind, passphrase=None):
    """Load Application from file

    @type filename: C{str}
    @type kind: C{str}
    @type passphrase: C{str}

    Load application from a given file. The serialization format it
    was saved in should be given as C{kind}, and is one of 'pickle', 'source',
    'xml' or 'python'. If C{passphrase} is given, the application was encrypted
    with the given passphrase.
    """
    if kind == 'python':
        application = sob.loadValueFromFile(filename, 'application', passphrase)
    else:
        application = sob.load(filename, kind, passphrase)
    if IService(application, None) is None:
        from twisted.application import compat
        application = compat.convert(application)
    return application


# add backwards compatible __implements__ attribute
components.backwardsCompatImplements(Service)
components.backwardsCompatImplements(MultiService)
components.backwardsCompatImplements(Process)


__all__ = ['IService', 'Service', 'IServiceCollection', 'MultiService',
           'IProcess', 'Process', 'Application', 'loadApplication']
Example #14
0
                request.write(
                    "<html><head><title>%s: %s</title></head><body>\n" %
                    (html.escape(str(
                        failure.type)), html.escape(str(failure.value))))
            else:
                request.write(
                    "<html><head><title>Failure!</title></head><body>\n")
            utils.renderFailure(failure, request)
            request.write("<h3>Here is the partially processed DOM:</h3>")
            request.write("\n<pre>\n")
            request.write(html.escape(xml))
            request.write("\n</pre>\n")
            request.write("</body></html>")
            request.finish()
        return failure
components.backwardsCompatImplements(View)


class LiveView(View):
    livePage = 1

    def wvfactory_webConduitGlue(self, request, node, m):
        if request.getHeader("user-agent").count("MSIE"):
            return View(m, templateFile="FlashConduitGlue.html")
        else:
            return View(m, templateFile="WebConduitGlue.html")

    def wvupdate_woven_flashConduitSessionView(self, request, wid, mod):
        #print "updating flash thingie"
        uid = request.getSession().uid
        n = wid.templateNode
Example #15
0
            self.protocol.doStop()
        self.connected = 0
        self.socket.close()
        del self.socket
        del self.fileno
        if hasattr(self, "d"):
            self.d.callback(None)
            del self.d

    def setLogStr(self):
        self.logstr = reflect.qual(self.protocol.__class__) + " (UDP)"

    def getHost(self):
        return address.UNIXAddress(self.socket.getsockname())

components.backwardsCompatImplements(DatagramPort)


class ConnectedDatagramPort(DatagramPort):
    """A connected datagram UNIX socket."""

    implementsOnly(interfaces.IUNIXDatagramConnectedTransport,
                   *(implementedBy(base.BasePort)))

    def __init__(self, addr, proto, maxPacketSize=8192, mode=0666, bindAddress=None, reactor=None):
        assert isinstance(proto, protocol.ConnectedDatagramProtocol)
        DatagramPort.__init__(self, bindAddress, proto, maxPacketSize, mode, reactor)
        self.remoteaddr = addr

    def startListening(self):
        try:
Example #16
0
        """
        pass

    def domChanged(self, request, widget, node):
        parent = getattr(self, '_parent', None)
        if parent is not None:
            parent.domChanged(request, widget, node)

    def pageRenderComplete(self, request):
        """Override this to recieve notification when the view rendering
        process is complete.
        """
        pass


components.backwardsCompatImplements(Controller)

WOVEN_PATH = os.path.split(woven.__file__)[0]


class LiveController(Controller):
    """A Controller that encapsulates logic that makes it possible for this
    page to be "Live". A live page can have it's content updated after the
    page has been sent to the browser, and can translate client-side
    javascript events into server-side events.
    """
    pageSession = None

    def render(self, request):
        """First, check to see if this request is attempting to hook up the
        output conduit. If so, do it. Otherwise, unlink the current session's
Example #17
0
    def spawnProcess(self,
                     processProtocol,
                     executable,
                     args=(),
                     env={},
                     path=None,
                     uid=None,
                     gid=None,
                     usePTY=0):
        """Spawn a process."""
        if uid is not None:
            raise ValueError("Setting UID is unsupported on this platform.")
        if gid is not None:
            raise ValueError("Setting GID is unsupported on this platform.")
        if usePTY:
            raise ValueError("PTYs are unsupported on this platform.")
        return Process(self, processProtocol, executable, args, env, path)


components.backwardsCompatImplements(Win32Reactor)


def install():
    threadable.init(1)
    r = Win32Reactor()
    import main
    main.installReactor(r)


__all__ = ["Win32Reactor", "install"]
Example #18
0
from twisted.plugin import IPlugin


class _Reporter(object):
    implements(IPlugin, IReporter)

    def __init__(self, name, module, description, longOpt, shortOpt, klass):
        self.name = name
        self.module = module
        self.description = description
        self.longOpt = longOpt
        self.shortOpt = shortOpt
        self.klass = klass


backwardsCompatImplements(_Reporter)

Tree = _Reporter("Tree Reporter",
                 "twisted.trial.reporter",
                 description="verbose color output (default reporter)",
                 longOpt="verbose",
                 shortOpt="v",
                 klass="TreeReporter")

BlackAndWhite = _Reporter("Black-And-White Reporter",
                          "twisted.trial.reporter",
                          description="Colorless verbose output",
                          longOpt="bwverbose",
                          shortOpt="o",
                          klass="VerboseTextReporter")
Example #19
0
    """
    def generate(self, request, node):
        """The generate method should do the work of mutating the DOM
        based on the object this adapter wraps.
        """
        pass


class NodeMutator:
    implements(INodeMutator)

    def __init__(self, data):
        self.data = data


components.backwardsCompatImplements(NodeMutator)


class NodeNodeMutator(NodeMutator):
    """A NodeNodeMutator replaces the node that is passed in to generate
    with the node it adapts.
    """
    def __init__(self, data):
        assert data is not None
        NodeMutator.__init__(self, data)

    def generate(self, request, node):
        if self.data is not node:
            parent = node.parentNode
            if parent:
                parent.replaceChild(self.data, node)
Example #20
0
    """Log pickles to DirDBM directory."""

    implements(base.ICommandLog)

    def __init__(self, logPath):
        self.db = dirdbm.Shelf(logPath)
        indexs = map(int, self.db.keys())
        if indexs:
            self.currentIndex = max(indexs)
        else:
            self.currentIndex = 0

    def logCommand(self, command, time):
        """Log a command."""
        self.currentIndex += 1
        self.db[str(self.currentIndex)] = (time, command)
        return defer.succeed(1)

    def getCurrentIndex(self):
        """Return index of last command logged."""
        return self.currentIndex

    def getCommandsSince(self, index):
        result = []
        for i in range(index, self.currentIndex + 1):
            result.append(self.db[str(i)])
        return result


backwardsCompatImplements(DirDBMLog)
Example #21
0
        will be the rendered page, unless the return value is
        twisted.web.server.NOT_DONE_YET, in which case it is this
        class's responsibility to write the results to
        request.write(data), then call request.finish().

        Old code that overrides render() directly is likewise expected
        to return a string or NOT_DONE_YET.
        """
        m = getattr(self, 'render_' + request.method, None)
        if not m:
            from twisted.web.server import UnsupportedMethod
            raise UnsupportedMethod(getattr(self, 'allowedMethods', ()))
        return m(request)

    def render_HEAD(self, request):
        """Default handling of HEAD method.
        
        I just return self.render_GET(request). When method is HEAD,
        the framework will handle this correctly.
        """
        return self.render_GET(request)


components.backwardsCompatImplements(Resource)

#t.w imports
#This is ugly, I know, but since error.py directly access resource.Resource
#during import-time (it subclasses it), the Resource class must be defined
#by the time error is imported.
import error
Example #22
0
"""
from twisted.persisted import dirdbm
from twisted.internet import defer
from twisted.python.components import backwardsCompatImplements
from zope.interface import implements
import base
class DirDBMLog:
    """Log pickles to DirDBM directory."""
    implements(base.ICommandLog)
    def __init__(self, logPath):
        self.db = dirdbm.Shelf(logPath)
        indexs = map(int, self.db.keys())
        if indexs:
            self.currentIndex = max(indexs)
        else:
            self.currentIndex = 0
    def logCommand(self, command, time):
        """Log a command."""
        self.currentIndex += 1
        self.db[str(self.currentIndex)] = (time, command)
        return defer.succeed(1)
    def getCurrentIndex(self):
        """Return index of last command logged."""
        return self.currentIndex
    def getCommandsSince(self, index):
        result = []
        for i in range(index, self.currentIndex + 1):
            result.append(self.db[str(i)])
        return result
backwardsCompatImplements(DirDBMLog)
Example #23
0
            self.cachedFor = id(request)
            self.dataWillChange()
            self.orig = self.original = self._getter(request)
        return self.original

    def setData(self, request, data):
        if self._setter is not None:
            self.cachedFor = None
            return self._setter(request, data)
        else:
            if hasattr(self, 'parent') and self.parent:
                self.parent.setSubmodel(request, self.name, data)
            self.orig = self.original = data


components.backwardsCompatImplements(Model)


class MethodModel(Model):
    """Look up submodels with wmfactory_* methods.
    """
    def submodelCheck(self, request, name):
        """Allow any submodel for which I have a submodel.
        """
        return hasattr(self, "wmfactory_" + name)

    def submodelFactory(self, request, name):
        """Call a wmfactory_name method on this model.
        """
        meth = getattr(self, "wmfactory_" + name)
        return meth(request)
Example #24
0
            if self.kw:
                L.append(", ".join([
                    '%s=%s' % (k, reflect.safe_repr(v))
                    for (k, v) in self.kw.iteritems()
                ]))
            L.append(")")

        if self.debug:
            L.append("\n\ntraceback at creation: \n\n%s" %
                     ('    '.join(self.creator)))
        L.append('>')

        return "".join(L)


components.backwardsCompatImplements(DelayedCall)


class ThreadedResolver:
    implements(IResolverSimple)

    def __init__(self, reactor):
        self.reactor = reactor
        self._runningQueries = {}

    def _fail(self, name, err):
        err = error.DNSLookupError("address %r not found: %s" % (name, err))
        return failure.Failure(err)

    def _cleanup(self, name, lookupDeferred):
        userDeferred, cancelCall = self._runningQueries[lookupDeferred]
Example #25
0
        return perspective

    def remote_console(self, messages):
        for kind, content in messages:
            if isinstance(content, types.StringTypes):
                self.original.output.append(content, kind)
            elif (kind == "exception") and isinstance(content,
                                                      failure.Failure):
                content.printTraceback(
                    _Notafile(self.original.output, "exception"))
            else:
                self.original.output.append(str(content), kind)

    def remote_receiveExplorer(self, xplorer):
        pass

    def remote_listCapabilities(self):
        return self.capabilities

    def _cbDisconnected(self, perspective):
        self.perspective = None

    def do(self, text):
        if self.perspective is None:
            raise OfflineError
        return self.perspective.callRemote("do", text)


components.backwardsCompatImplements(ManholeClient)
components.registerAdapter(ManholeClient, ManholeWindow, IManholeClient)
Example #26
0
        will be the rendered page, unless the return value is
        twisted.web.server.NOT_DONE_YET, in which case it is this
        class's responsibility to write the results to
        request.write(data), then call request.finish().

        Old code that overrides render() directly is likewise expected
        to return a string or NOT_DONE_YET.
        """
        m = getattr(self, 'render_' + request.method, None)
        if not m:
            from twisted.web.server import UnsupportedMethod
            raise UnsupportedMethod(getattr(self, 'allowedMethods', ()))
        return m(request)

    def render_HEAD(self, request):
        """Default handling of HEAD method.
        
        I just return self.render_GET(request). When method is HEAD,
        the framework will handle this correctly.
        """
        return self.render_GET(request)
components.backwardsCompatImplements(Resource)
        


#t.w imports
#This is ugly, I know, but since error.py directly access resource.Resource
#during import-time (it subclasses it), the Resource class must be defined
#by the time error is imported.
import error
Example #27
0
        self.host = host
    def getChallenge(self):
        if self.challenge:
            return self.challenge
        r = random.randrange(0x7fffffff)
        t = time.time()
        self.challenge = '<%d.%d@%s>' % (r, t, self.host)
        return self.challenge
    def setResponse(self, response):
        self.username, self.response = response.split(None, 1)
    def moreChallenges(self):
        return False
    def checkPassword(self, password):
        verify = hmac.HMAC(password, self.challenge).hexdigest()
        return verify == self.response
components.backwardsCompatImplements(CramMD5Credentials)
class UsernameHashedPassword:
    interface.implements(IUsernameHashedPassword)
    def __init__(self, username, hashed):
        self.username = username
        self.hashed = hashed
    def checkPassword(self, password):
        return self.hashed == password
components.backwardsCompatImplements(UsernameHashedPassword)
class UsernamePassword:
    interface.implements(IUsernamePassword)
    def __init__(self, username, password):
        self.username = username
        self.password = password
    def checkPassword(self, password):
        return self.password == password
Example #28
0
STOP_RENDERING = 1
RESTART_RENDERING = 2
class INodeMutator(components.Interface):
    """A component that implements NodeMutator knows how to mutate
    DOM based on the instructions in the object it wraps.
    """
    def generate(self, request, node):
        """The generate method should do the work of mutating the DOM
        based on the object this adapter wraps.
        """
        pass
class NodeMutator:
    implements(INodeMutator)
    def __init__(self, data):
        self.data = data
components.backwardsCompatImplements(NodeMutator)
class NodeNodeMutator(NodeMutator):
    """A NodeNodeMutator replaces the node that is passed in to generate
    with the node it adapts.
    """
    def __init__(self, data):
        assert data is not None
        NodeMutator.__init__(self, data)
    def generate(self, request, node):
        if self.data is not node:
            parent = node.parentNode
            if parent:
                parent.replaceChild(self.data, node)
            else:
                log.msg("Warning: There was no parent for node %s; node not mutated." % node)
        return self.data
Example #29
0
        Unless I'm overridden, everything gets the same bucket.

        @returns: something to be used as a key in the bucket cache.
        """
        return None

    def sweep(self):
        """I throw away references to empty buckets."""
        for key, bucket in self.buckets.items():
            if (bucket._refcount == 0) and bucket.drip():
                del self.buckets[key]

        self.lastSweep = time()

backwardsCompatImplements(HierarchicalBucketFilter)


class FilterByHost(HierarchicalBucketFilter):
    """A bucket filter with a bucket for each host.
    """
    sweepInterval = 60 * 20

    def getBucketKey(self, transport):
        return transport.getPeer()[1]


class FilterByServer(HierarchicalBucketFilter):
    """A bucket filter with a bucket for each service.
    """
    sweepInterval = None
Example #30
0
            log.deferr()

        if closed:
            self._disconnectSelectable(fd, closed, action == "doRead")

    doIteration = doWaitForMultipleEvents

    def spawnProcess(self, processProtocol, executable, args=(), env={}, path=None, uid=None, gid=None, usePTY=0):
        """Spawn a process."""
        if uid is not None:
            raise ValueError("Setting UID is unsupported on this platform.")
        if gid is not None:
            raise ValueError("Setting GID is unsupported on this platform.")
        if usePTY:
            raise ValueError("PTYs are unsupported on this platform.")
        return Process(self, processProtocol, executable, args, env, path)


components.backwardsCompatImplements(Win32Reactor)


def install():
    threadable.init(1)
    r = Win32Reactor()
    import main

    main.installReactor(r)


__all__ = ["Win32Reactor", "install"]
Example #31
0
        x = self
        while x.parent is not None:
            L.append(x.offset)
            x = x.parent
        L.reverse()
        return L
    def __getitem__(self, index):
        slot, o = self.get(index)
        n = INode(o, persist=False)
        n.postInit(index, self, slot)
        return n
    def origstr(self):
        return str(self.original)
    def format(self):
        return (self.slot, self.origstr())
components.backwardsCompatImplements(InspectorNode)
class ConstantNode(InspectorNode):
    def __len__(self):
        return 0
class DictionaryNode(InspectorNode):
    def get(self, index):
        L = self.original.items()
        L.sort()
        return L[index]
    def __len__(self):
        return len(self.original)
    def origstr(self):
        return "Dictionary"
class ListNode(InspectorNode):
    def get(self, index):
        return index, self.original[index]
Example #32
0
        self.service = service
        self._cache = {}

    def requestAvatar(self, avatarId, mind, *interfaces):
        if pb.IPerspective not in interfaces:
            raise NotImplementedError("no interface")
        if avatarId in self._cache:
            p = self._cache[avatarId]
        else:
            p = Perspective(self.service)
        p.attached(mind, avatarId)
        def detached():
            p.detached(mind, avatarId)
        return (pb.IPerspective, p, detached)

components.backwardsCompatImplements(Realm)


class Service(service.Service):

    welcomeMessage = (
        "\nHello %(you)s, welcome to Manhole "
        "on %(host)s.\n"
        "%(longversion)s.\n\n")

    def __init__(self, unsafeTracebacks=False, namespace=None):
        self.unsafeTracebacks = unsafeTracebacks
        self.namespace = {
            '__name__': '__manhole%x__' % (id(self),),
            'sys': sys
            }
Example #33
0
File: ssl.py Project: RichDijk/eXe
    def getHost(self):
        """Returns the address from which I am connecting."""
        h, p = self.socket.getsockname()
        return address.IPv4Address("TCP", h, p, "SSL")

    def getPeer(self):
        """Returns the address that I am connected."""
        return address.IPv4Address("TCP", self.addr[0], self.addr[1], "SSL")

    def _connectDone(self):
        self.startTLS(self.ctxFactory)
        self.startWriting()
        tcp.Client._connectDone(self)


components.backwardsCompatImplements(Client)


class Server(tcp.Server):
    """I am an SSL server.
    """

    implements(interfaces.ISSLTransport)

    def getHost(self):
        """Return server's address."""
        h, p = self.socket.getsockname()
        return address.IPv4Address("TCP", h, p, "SSL")

    def getPeer(self):
        """Return address of peer."""
Example #34
0
        self.service = service
        self._cache = {}

    def requestAvatar(self, avatarId, mind, *interfaces):
        if pb.IPerspective not in interfaces:
            raise NotImplementedError("no interface")
        if avatarId in self._cache:
            p = self._cache[avatarId]
        else:
            p = Perspective(self.service)
        p.attached(mind, avatarId)
        def detached():
            p.detached(mind, avatarId)
        return (pb.IPerspective, p, detached)

components.backwardsCompatImplements(Realm)


class Service(service.Service):

    welcomeMessage = (
        "\nHello %(you)s, welcome to Manhole "
        "on %(host)s.\n"
        "%(longversion)s.\n\n")

    def __init__(self, unsafeTracebacks=False, namespace=None):
        self.unsafeTracebacks = unsafeTracebacks
        self.namespace = {
            '__name__': '__manhole%x__' % (id(self),),
            'sys': sys
            }
Example #35
0
        for i in range(3):
            try:
                creds = (response + ('=' * i)).decode('base64')
            except:
                pass
            else:
                break
        else:
            # Totally bogus
            raise SIPError(400)
        p = creds.split(':', 1)
        if len(p) == 2:
            return cred.credentials.UsernamePassword(*p)
        raise SIPError(400)

components.backwardsCompatImplements(BasicAuthorizer)


class DigestedCredentials(cred.credentials.UsernameHashedPassword):
    """Yet Another Simple Digest-MD5 authentication scheme"""
    
    def __init__(self, username, fields, challenges):
        self.username = username
        self.fields = fields
        self.challenges = challenges
    
    def checkPassword(self, password):
        method = 'REGISTER'
        response = self.fields.get('response')
        uri = self.fields.get('uri')
        nonce = self.fields.get('nonce')
Example #36
0
    def logPrefix(self):
        """Returns the name of my class, to prefix log entries with.
        """
        return self.logstr

    def getHost(self):
        """
        Returns an IPv4Address.

        This indicates the address from which I am connecting.
        """
        return address.IPv4Address(
            'UDP', *(self.socket.getsockname() + ('INET_UDP', )))


components.backwardsCompatImplements(Port)


class ConnectedPort(Port):
    """DEPRECATED.

    A connected UDP socket."""

    implements(interfaces.IUDPConnectedTransport)

    def __init__(self,
                 (remotehost, remoteport),
                 port,
                 proto,
                 interface='',
                 maxPacketSize=8192,
Example #37
0
            a = 3
        self.assertEquals(IFoo.a, 3)


from zope import interface as zinterface

class IZope(zinterface.Interface):
    def amethod(a, b):
        pass

class Zopeable:
    pass

class Zoper:
    zinterface.implements(IZope, IAdder)
components.backwardsCompatImplements(Zoper) # add __implements__

components.registerAdapter(lambda o: id(o), Zopeable, IZope)

class SubZoper(Zoper):
    zinterface.implements(ISub)


class OldStyle:
    __implements__ = IAdder
class NewSubOfOldStyle(OldStyle):
    zinterface.implements(IZope)
components.backwardsCompatImplements(NewSubOfOldStyle)

class TestZope(unittest.TestCase):
Example #38
0
    def getChild(self, name, request):
        # Don't call the rememberURL if we already did once; That way
        # we can support an idiom of setting appName as a class
        # attribue *even if* the same class is used more than once in
        # a hierarchy of Pages.
        if self.appRoot and not request.getRootURL():
            request.rememberRootURL()
        return controller.Controller.getChild(self, name, request)

    def renderView(self, request):
        return view.View.render(self,
                                request,
                                doneCallback=self.gatheredControllers)


components.backwardsCompatImplements(Page)


class LivePage(model.MethodModel, controller.LiveController, view.LiveView):

    appRoot = False

    def __init__(self,
                 m=None,
                 templateFile=None,
                 inputhandlers=None,
                 templateDirectory=None,
                 controllers=None,
                 *args,
                 **kwargs):
        template = kwargs.setdefault('template', None)
Example #39
0
    isLeaf = False

    def __init__(self, resource, name):
        self.authenticated = Authenticated(name)
        self.resource = resource

    def render(self, request):
        request.setComponent(Authenticated, self.authenticated)
        return self.resource.render(request)

    def getChildWithDefault(self, path, request):
        request.setComponent(Authenticated, self.authenticated)
        return self.resource.getChildWithDefault(path, request)


components.backwardsCompatImplements(MarkAuthenticatedResource)


class MarkingRealm:

    implements(portal.IRealm)

    def __init__(self, resource, nonauthenticated=None):
        self.resource = resource
        self.nonauthenticated = (nonauthenticated
                                 or MarkAuthenticatedResource(resource, None))

    def requestAvatar(self, avatarId, mind, *interfaces):
        if resource.IResource not in interfaces:
            raise NotImplementedError("no interface")
        if avatarId:
Example #40
0
        """
        return self.getPerspectiveRequest(name)

    def getPerspectiveRequest(self, name):
        """Return a Deferred which is a request for a perspective on this service.
        """
        try:
            p = self.getPerspectiveNamed(name)
        except KeyError:
            return self.loadPerspective(name)
        else:
            return defer.succeed(p)

    def getServiceName(self):
        """The name of this service.
        """
        return self.serviceName or self.getServiceType()

    def getServiceType(self):
        """Get a string describing the type of this service.
        """
        return self.serviceType or reflect.qual(self.__class__)

    def setServiceParent(self, parent):
        app.ApplicationService.setServiceParent(self, parent)
        if self.authorizer is not None:
            self.authorizer.setServiceCollection(parent)


components.backwardsCompatImplements(Service)
Example #41
0
        self.perspective = perspective
        perspective.notifyOnDisconnect(self._cbDisconnected)
        return perspective

    def remote_console(self, messages):
        for kind, content in messages:
            if isinstance(content, types.StringTypes):
                self.original.output.append(content, kind)
            elif (kind == "exception") and isinstance(content, failure.Failure):
                content.printTraceback(_Notafile(self.original.output,
                                                 "exception"))
            else:
                self.original.output.append(str(content), kind)

    def remote_receiveExplorer(self, xplorer):
        pass

    def remote_listCapabilities(self):
        return self.capabilities

    def _cbDisconnected(self, perspective):
        self.perspective = None

    def do(self, text):
        if self.perspective is None:
            raise OfflineError
        return self.perspective.callRemote("do", text)

components.backwardsCompatImplements(ManholeClient)
components.registerAdapter(ManholeClient, ManholeWindow, IManholeClient)
Example #42
0
    def pauseProducing(self):
        self.stopReading()

    def stopProducing(self):
        self.loseConnection()

    def fileno(self):
        """File Descriptor number for select().

        This method must be overridden or assigned in subclasses to
        indicate a valid file descriptor for the operating system.
        """
        return -1


components.backwardsCompatImplements(FileDescriptor)


def isIPAddress(addr):
    parts = string.split(addr, '.')
    if len(parts) == 4:
        try:
            for part in map(int, parts):
                if not (0 <= part < 256):
                    break
            else:
                return 1
        except ValueError:
            pass
    return 0
Example #43
0
        getPerspectiveRequest provides management of caching perspectives.
        @returntype: Deferred Perspective
        """
        return defer.fail("No such perspective %s" % name)
    def getPerspectiveForIdentity(self, name, identity):
        """A hook to use if the identity is required when getting the perspective.
        """
        return self.getPerspectiveRequest(name)
    def getPerspectiveRequest(self, name):
        """Return a Deferred which is a request for a perspective on this service.
        """
        try:
            p = self.getPerspectiveNamed(name)
        except KeyError:
            return self.loadPerspective(name)
        else:
            return defer.succeed(p)
    def getServiceName(self):
        """The name of this service.
        """
        return self.serviceName or self.getServiceType()
    def getServiceType(self):
        """Get a string describing the type of this service.
        """
        return self.serviceType or reflect.qual(self.__class__)
    def setServiceParent(self, parent):
        app.ApplicationService.setServiceParent(self, parent)
        if self.authorizer is not None:
            self.authorizer.setServiceCollection(parent)
components.backwardsCompatImplements(Service)
Example #44
0
from twisted.python.components import backwardsCompatImplements
from twisted.plugin import IPlugin, ITestPlugin, ITestPlugin2


class TestPlugin:
    """A plugin used solely for testing purposes.
    """
    classProvides(ITestPlugin, IPlugin)

    def test1():
        pass

    test1 = staticmethod(test1)


backwardsCompatImplements(TestPlugin)


class AnotherTestPlugin:
    """Another plugin used solely for testing purposes.
    """
    classProvides(ITestPlugin2, IPlugin)

    def test():
        pass

    test = staticmethod(test)


backwardsCompatImplements(AnotherTestPlugin)
Example #45
0
            self.socket.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY))

    def setTcpNoDelay(self, enabled):
        self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, enabled)

    def getTcpKeepAlive(self):
        return operator.truth(
            self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE))

    def setTcpKeepAlive(self, enabled):
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, enabled)


if SSL:
    classImplements(Connection, interfaces.ITLSTransport)
components.backwardsCompatImplements(Connection)


class BaseClient(Connection):
    """A base class for client TCP (and similiar) sockets.
    """
    addressFamily = socket.AF_INET
    socketType = socket.SOCK_STREAM

    def _finishInit(self, whenDone, skt, error, reactor):
        """Called by base classes to continue to next stage of initialization."""
        if whenDone:
            Connection.__init__(self, skt, None, reactor)
            self.doWrite = self.doConnect
            self.doRead = self.doConnect
            reactor.callLater(0, whenDone)
Example #46
0
"""
I'm a test drop-in.  The plugin system's unit tests use me.  No one
else should.
"""
from zope.interface import classProvides
from twisted.python.components import backwardsCompatImplements
from twisted.plugin import IPlugin, ITestPlugin, ITestPlugin2
class TestPlugin:
    """A plugin used solely for testing purposes.
    """
    classProvides(ITestPlugin,
                  IPlugin)
    def test1():
        pass
    test1 = staticmethod(test1)
backwardsCompatImplements(TestPlugin)
class AnotherTestPlugin:
    """Another plugin used solely for testing purposes.
    """
    classProvides(ITestPlugin2,
                  IPlugin)
    def test():
        pass
    test = staticmethod(test)
backwardsCompatImplements(AnotherTestPlugin)
class ThirdTestPlugin:
    """Another plugin used solely for testing purposes.
    """
    classProvides(ITestPlugin2,
                  IPlugin)
    def test():
Example #47
0
        """
        ext, dumpFunc = self._getStyle()
        if passphrase:
            ext = 'e' + ext
        finalname, filename = self._getFilename(filename, ext, tag)
        log.msg("Saving " + self.name + " application to " + finalname + "...")
        self._saveTemp(filename, passphrase, dumpFunc)
        if runtime.platformType == "win32" and os.path.isfile(finalname):
            os.remove(finalname)
        os.rename(filename, finalname)
        log.msg("Saved.")


# "Persistant" has been present since 1.0.7, so retain it for compatibility
Persistant = Persistent
components.backwardsCompatImplements(Persistent)


class _EverythingEphemeral(styles.Ephemeral):

    initRun = 0

    def __getattr__(self, key):
        try:
            return getattr(mainMod, key)
        except AttributeError:
            if self.initRun:
                raise
            else:
                log.msg("Warning!  Loading from __main__: %s" % key)
                return styles.Ephemeral()
Example #48
0
        if self.client[0] not in ('INET', 'SSL'):
            return None
        host = self.client[1]
        try:
            name, names, addresses = socket.gethostbyaddr(host)
        except socket.error:
            return host
        names.insert(0, name)
        for name in names:
            if '.' in name:
                return name
        return names[0]
    def connectionLost(self, reason):
        """connection was lost"""
        pass
components.backwardsCompatImplements(Request)
class HTTPChannel(basic.LineReceiver, policies.TimeoutMixin):
    """A receiver for HTTP requests."""
    maxHeaders = 500 # max number of headers allowed per request
    length = 0
    persistent = 1
    __header = ''
    __first_line = 1
    __content = None
    requestFactory = Request
    _savedTimeOut = None
    def __init__(self):
        self.requests = []
    def connectionMade(self):
        self.setTimeout(self.timeOut)
    def lineReceived(self, line):
Example #49
0
class IChangeNotified:
    pass


class BaseChangeNotified:

    implements(IChangeNotified)

    def reportChange(self, old, new):
        pass

    def reportNoChange(self):
        pass


components.backwardsCompatImplements(BaseChangeNotified)


class ChangeChecker:

    working = 0
    call = None

    def __init__(self, notified, url, delay=60):
        self.notified = notified
        self.url = url
        self.md5 = None
        self.delay = delay

    def start(self):
        self.working = 1
Example #50
0
        """
        ext, dumpFunc = self._getStyle()
        if passphrase:
            ext = "e" + ext
        finalname, filename = self._getFilename(filename, ext, tag)
        log.msg("Saving " + self.name + " application to " + finalname + "...")
        self._saveTemp(filename, passphrase, dumpFunc)
        if runtime.platformType == "win32" and os.path.isfile(finalname):
            os.remove(finalname)
        os.rename(filename, finalname)
        log.msg("Saved.")


# "Persistant" has been present since 1.0.7, so retain it for compatibility
Persistant = Persistent
components.backwardsCompatImplements(Persistent)


class _EverythingEphemeral(styles.Ephemeral):

    initRun = 0

    def __getattr__(self, key):
        try:
            return getattr(mainMod, key)
        except AttributeError:
            if self.initRun:
                raise
            else:
                log.msg("Warning!  Loading from __main__: %s" % key)
                return styles.Ephemeral()
Example #51
0
    Internal utility class to simplify the definition of \"new-style\"
    mktap plugins based on existing, \"classic\" mktap plugins.
    """

    implements(IPlugin, IServiceMaker)

    def __init__(self, name, module, description, tapname):
        self.name = name
        self.module = module
        self.description = description
        self.tapname = tapname

    def options():
        def get(self):
            return namedAny(self.module).Options

        return get,

    options = property(*options())

    def makeService():
        def get(self):
            return namedAny(self.module).makeService

        return get,

    makeService = property(*makeService())


backwardsCompatImplements(_tapHelper)
Example #52
0
        self.args = args
        self.kwargs = kwargs

    def execute(self, svc, commandTime):
        if not hasattr(self, "obj"):
            obj = svc.loadObject(self.objType, self.objId)
        else:
            obj = self.obj
        return getattr(obj, self.methodName)(*self.args, **self.kwargs)

    def __getstate__(self):
        d = self.__dict__.copy()
        del d["obj"]
        return d

components.backwardsCompatImplements(WrapperCommand)


def command(methodName, cmdClass=WrapperCommand):
    """Wrap a method so it gets turned into command automatically.

    For use with Wrappables.

    Usage::

        | class Foo(Wrappable):
        |     objectType = "foo"
        |     def getUid(self):
        |         return self.id
        |     def _bar(self, x):
        |         return x + 1
Example #53
0
        return 'loopback'

    def getPeer(self):
        return 'loopback'

    def registerProducer(self, producer, streaming):
        self.producer = producer

    def unregisterProducer(self):
        self.producer = None

    def logPrefix(self):
        return 'Loopback(%r)' % (self.target.__class__.__name__, )


components.backwardsCompatImplements(LoopbackRelay)


def loopback(server, client, logFile=None):
    """Run session between server and client.
    """
    from twisted.internet import reactor
    serverToClient = LoopbackRelay(client, logFile)
    clientToServer = LoopbackRelay(server, logFile)
    server.makeConnection(serverToClient)
    client.makeConnection(clientToServer)
    while 1:
        reactor.iterate(0.01)  # this is to clear any deferreds
        serverToClient.clearBuffer()
        clientToServer.clearBuffer()
        if serverToClient.shouldLose:
Example #54
0
from twisted.trial.itrial import IReporter
from twisted.plugin import IPlugin

class _Reporter(object):
    implements(IPlugin, IReporter)

    def __init__(self, name, module, description, longOpt, shortOpt, klass):
        self.name = name
        self.module = module
        self.description = description
        self.longOpt = longOpt
        self.shortOpt = shortOpt
        self.klass = klass

backwardsCompatImplements(_Reporter)

Tree = _Reporter("Tree Reporter",
                 "twisted.trial.reporter",
                 description="verbose color output (default reporter)",
                 longOpt="verbose",
                 shortOpt="v",
                 klass="TreeReporter")

BlackAndWhite = _Reporter("Black-And-White Reporter",
                          "twisted.trial.reporter",
                          description="Colorless verbose output",
                          longOpt="bwverbose",
                          shortOpt="o",
                          klass="VerboseTextReporter")
Example #55
0
    def unregisterProducer(self):
        self.producer = None

    def write(self, chunk):
        self.chunks.append(chunk)

    def sendNextPage(self):
        if self.pointer >= len(self.chunks):
            return
        val = self.chunks[self.pointer]
        self.pointer += 1
        self.producer.resumeProducing()
        self.collector.callRemote("gotPage", val)

components.backwardsCompatImplements(FilePager)


### Utility paging stuff.
from twisted.spread import pb
class CallbackPageCollector(pb.Referenceable):
    """I receive pages from the peer. You may instantiate a Pager with a
    remote reference to me. I will call the callback with a list of pages
    once they are all received."""
    def __init__(self, callback):
        self.pages = []
        self.callback = callback
    def remote_gotPage(self, page):
        self.pages.append(page)
    def remote_endedPaging(self):
        self.callback(self.pages)
Example #56
0
        return (self._bwHack, self.name)[start:stop]

    def __eq__(self, other):
        if isinstance(other, tuple):
            return tuple(self) == other
        elif isinstance(other, UNIXAddress):
            try:
                return os.path.samefile(self.name, other.name)
            except OSError:
                pass
        return False

    def __str__(self):
        return 'UNIXSocket(%r)' % (self.name,)

components.backwardsCompatImplements(IPv4Address)
components.backwardsCompatImplements(UNIXAddress)


# These are for buildFactory backwards compatability due to
# stupidity-induced inconsistency.

class _ServerFactoryIPv4Address(IPv4Address):
    """Backwards compatability hack. Just like IPv4Address in practice."""
    
    def __eq__(self, other):
        if isinstance(other, tuple):
            warnings.warn("IPv4Address.__getitem__ is deprecated.  Use attributes instead.",
                          category=DeprecationWarning, stacklevel=2)
            return (self.host, self.port) == other
        elif isinstance(other, IPv4Address):
Example #57
0
        It will be called, for example, before an application shuts down,
        if it was connected to a port. User code should not call this function
        directly.
        """
    def buildProtocol(self, addr):
        """Create an instance of a subclass of Protocol.
        The returned instance will handle input on an incoming server
        connection, and an attribute \"factory\" pointing to the creating
        factory.
        Override this method to alter how Protocol instances get created.
        @param addr: an object implementing L{twisted.internet.interfaces.IAddress}
        """
        p = self.protocol()
        p.factory = self
        return p
components.backwardsCompatImplements(Factory)
class ClientFactory(Factory):
    """A Protocol factory for clients.
    This can be used together with the various connectXXX methods in
    reactors.
    """
    def startedConnecting(self, connector):
        """Called when a connection has been started.
        You can call connector.stopConnecting() to stop the connection attempt.
        @param connector: a Connector object.
        """
    def clientConnectionFailed(self, connector, reason):
        """Called when a connection has failed to connect.
        It may be useful to call connector.connect() - this will reconnect.
        @type reason: L{twisted.python.failure.Failure}
        """
Example #58
0
        """
        log.msg('attached [%s]' % reflect.qual(self.__class__))
        self._attachedCount = self._attachedCount + 1
        if self._attachedCount == 1:
            self.service.cachePerspective(self)
        else:
            log.msg(" (multiple references attached: %s)" % self._attachedCount)
        return self

    def detached(self, reference, identity):
        """Called when a broker is 'detached' from me.

        See 'attached'.

        When a remote actor disconnects (or times out, for example,
        with HTTP), this is called in order to indicate that the
        reference associated with that peer is no longer attached to
        this perspective.
        """
        log.msg('detached [%s]' % reflect.qual(self.__class__))
        self._attachedCount = self._attachedCount - 1
        if self._attachedCount <= 0:
            self.service.uncachePerspective(self)
            if self._attachedCount < 0:
                log.msg(" (Weird stuff: attached count = %s)" % self._attachedCount)
        else:
            log.msg(" (multiple references attached: %s)" % self._attachedCount)
        return self

components.backwardsCompatImplements(Perspective)
Example #59
0
    def buildProtocol(self, addr):
        """Create an instance of a subclass of Protocol.

        The returned instance will handle input on an incoming server
        connection, and an attribute \"factory\" pointing to the creating
        factory.

        Override this method to alter how Protocol instances get created.

        @param addr: an object implementing L{twisted.internet.interfaces.IAddress}
        """
        p = self.protocol()
        p.factory = self
        return p

components.backwardsCompatImplements(Factory)


class ClientFactory(Factory):
    """A Protocol factory for clients.

    This can be used together with the various connectXXX methods in
    reactors.
    """

    def startedConnecting(self, connector):
        """Called when a connection has been started.

        You can call connector.stopConnecting() to stop the connection attempt.

        @param connector: a Connector object.