class StandardIO(object): implements(interfaces.ITransport, interfaces.IProducer, interfaces.IConsumer, interfaces.IHalfCloseableDescriptor) _reader = None _writer = None disconnected = False disconnecting = False def __init__(self, proto, stdin=0, stdout=1): from lib.twisted.internet import reactor self.protocol = proto self._writer = process.ProcessWriter(reactor, self, 'write', stdout) try: self._writer.startReading() except IOError, e: if e.errno == errno.EPERM: # epoll will reject certain file descriptors by raising # EPERM. Most commonly, this means stdout was redirected to # a regular file. raise RuntimeError( "This reactor does not support this type of file " "descriptor (fd %d, mode %d) (for example, epollreactor " "does not support normal files. See #4429)." % (stdout, os.fstat(stdout).st_mode)) raise self._reader = process.ProcessReader(reactor, self, 'read', stdin) self._reader.startReading() self.protocol.makeConnection(self)
class _ZipMapImpl: """ IPathImportMapper implementation for zipimport.ZipImporter. """ implements(IPathImportMapper) def __init__(self, importer): self.importer = importer def mapPath(self, fsPathString): """ Map the given FS path to a ZipPath, by looking at the ZipImporter's "archive" attribute and using it as our ZipArchive root, then walking down into the archive from there. @return: a L{zippath.ZipPath} or L{zippath.ZipArchive} instance. """ za = ZipArchive(self.importer.archive) myPath = FilePath(self.importer.archive) itsPath = FilePath(fsPathString) if myPath == itsPath: return za # This is NOT a general-purpose rule for sys.path or __file__: # zipimport specifically uses regular OS path syntax in its pathnames, # even though zip files specify that slashes are always the separator, # regardless of platform. segs = itsPath.segmentsFrom(myPath) zp = za for seg in segs: zp = zp.child(seg) return zp
class IRCAccount(basesupport.AbstractAccount): implements(interfaces.IAccount) gatewayType = "IRC" _groupFactory = IRCGroup _personFactory = IRCPerson def __init__(self, accountName, autoLogin, username, password, host, port, channels=''): basesupport.AbstractAccount.__init__(self, accountName, autoLogin, username, password, host, port) self.channels = map(string.strip, string.split(channels, ',')) if self.channels == ['']: self.channels = [] def _startLogOn(self, chatui): logonDeferred = defer.Deferred() cc = protocol.ClientCreator(reactor, IRCProto, self, chatui, logonDeferred) d = cc.connectTCP(self.host, self.port) d.addErrback(logonDeferred.errback) return logonDeferred
class Service(service.Service): """ External server-side component service. """ implements(ijabber.IService) def componentConnected(self, xs): pass def componentDisconnected(self): pass def transportConnected(self, xs): pass def send(self, obj): """ Send data over service parent's XML stream. @note: L{ServiceManager} maintains a queue for data sent using this method when there is no current established XML stream. This data is then sent as soon as a new stream has been established and initialized. Subsequently, L{componentConnected} will be called again. If this queueing is not desired, use C{send} on the XmlStream object (passed to L{componentConnected}) directly. @param obj: data to be sent over the XML stream. This is usually an object providing L{domish.IElement}, or serialized XML. See L{xmlstream.XmlStream} for details. """ self.parent.send(obj)
class PBMindReference(pb.RemoteReference): implements(iwords.IChatClient) def receive(self, sender, recipient, message): if iwords.IGroup.providedBy(recipient): rec = PBGroup(self.realm, self.avatar, recipient) else: rec = PBUser(self.realm, self.avatar, recipient) return self.callRemote( 'receive', PBUser(self.realm, self.avatar, sender), rec, message) def groupMetaUpdate(self, group, meta): return self.callRemote( 'groupMetaUpdate', PBGroup(self.realm, self.avatar, group), meta) def userJoined(self, group, user): return self.callRemote( 'userJoined', PBGroup(self.realm, self.avatar, group), PBUser(self.realm, self.avatar, user)) def userLeft(self, group, user, reason=None): assert reason is None or isinstance(reason, unicode) return self.callRemote( 'userLeft', PBGroup(self.realm, self.avatar, group), PBUser(self.realm, self.avatar, user), reason)
class MulticastPort(MulticastMixin, Port): """ UDP Port that supports multicasting. """ implements(interfaces.IMulticastTransport) def __init__(self, port, proto, interface='', maxPacketSize=8192, reactor=None, listenMultiple=False): """ @see: L{lib.twisted.internet.interfaces.IReactorMulticast.listenMulticast} """ Port.__init__(self, port, proto, interface, maxPacketSize, reactor) self.listenMultiple = listenMultiple def createInternetSocket(self): skt = Port.createInternetSocket(self) if self.listenMultiple: skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if hasattr(socket, "SO_REUSEPORT"): skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) return skt
class InMemoryRegistry: """A simplistic registry for a specific domain.""" implements(IRegistry, ILocator) def __init__(self, domain): self.domain = domain # the domain we handle registration for self.users = { } # map username to (IDelayedCall for expiry, address URI) def getAddress(self, userURI): if userURI.host != self.domain: return defer.fail(LookupError("unknown domain")) if self.users.has_key(userURI.username): dc, url = self.users[userURI.username] return defer.succeed(url) else: return defer.fail(LookupError("no such user")) def getRegistrationInfo(self, userURI): if userURI.host != self.domain: return defer.fail(LookupError("unknown domain")) if self.users.has_key(userURI.username): dc, url = self.users[userURI.username] return defer.succeed( Registration(int(dc.getTime() - time.time()), url)) else: return defer.fail(LookupError("no such user")) def _expireRegistration(self, username): try: dc, url = self.users[username] except KeyError: return defer.fail(LookupError("no such user")) else: dc.cancel() del self.users[username] return defer.succeed(Registration(0, url)) def registerAddress(self, domainURL, logicalURL, physicalURL): if domainURL.host != self.domain: log.msg("Registration for domain we don't handle.") return defer.fail(RegistrationError(404)) if logicalURL.host != self.domain: log.msg("Registration for domain we don't handle.") return defer.fail(RegistrationError(404)) if self.users.has_key(logicalURL.username): dc, old = self.users[logicalURL.username] dc.reset(3600) else: dc = reactor.callLater(3600, self._expireRegistration, logicalURL.username) log.msg("Registered %s at %s" % (logicalURL.toString(), physicalURL.toString())) self.users[logicalURL.username] = (dc, physicalURL) return defer.succeed( Registration(int(dc.getTime() - time.time()), physicalURL)) def unregisterAddress(self, domainURL, logicalURL, physicalURL): return self._expireRegistration(logicalURL.username)
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
class HierarchicalBucketFilter: """I filter things into buckets, and I am nestable. @cvar bucketFactory: Class of buckets to make. @type bucketFactory: L{Bucket} class @cvar sweepInterval: Seconds between sweeping out the bucket cache. @type sweepInterval: int """ implements(IBucketFilter) bucketFactory = Bucket sweepInterval = None def __init__(self, parentFilter=None): self.buckets = {} self.parentFilter = parentFilter self.lastSweep = time() def getBucketFor(self, *a, **kw): """You want a bucket for that? I'll give you a bucket. Any parameters are passed on to L{getBucketKey}, from them it decides which bucket you get. @returntype: L{Bucket} """ if ((self.sweepInterval is not None) and ((time() - self.lastSweep) > self.sweepInterval)): self.sweep() if self.parentFilter: parentBucket = self.parentFilter.getBucketFor(self, *a, **kw) else: parentBucket = None key = self.getBucketKey(*a, **kw) bucket = self.buckets.get(key) if bucket is None: bucket = self.bucketFactory(parentBucket) self.buckets[key] = bucket return bucket def getBucketKey(self, *a, **kw): """I determine who gets which bucket. 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()
class DatagramPort(_UNIXPort, udp.Port): """Datagram UNIX port, listening for packets.""" implements(interfaces.IUNIXDatagramTransport) addressFamily = socket.AF_UNIX def __init__(self, addr, proto, maxPacketSize=8192, mode=0666, reactor=None):
class Port(_SocketCloser): implements(interfaces.IListeningPort) connected = False disconnected = False disconnecting = False addressFamily = socket.AF_INET socketType = socket.SOCK_STREAM sessionno = 0 maxAccepts = 100 # Actual port number being listened on, only set to a non-None # value when we are actually listening. _realPortNumber = None def __init__(self, port, factory, backlog=50, interface='', reactor=None): self.port = port self.factory = factory self.backlog = backlog self.interface = interface self.reactor = reactor def __repr__(self): if self._realPortNumber is not None: return "<%s of %s on %s>" % ( self.__class__, self.factory.__class__, self._realPortNumber) else: return "<%s of %s (not listening)>" % (self.__class__, self.factory.__class__) def startListening(self): try: skt = self.reactor.createSocket(self.addressFamily, self.socketType) # TODO: resolve self.interface if necessary skt.bind((self.interface, self.port)) except socket.error, le: raise error.CannotListenError, (self.interface, self.port, le) self.addrLen = _iocp.maxAddrLen(skt.fileno()) # Make sure that if we listened on port 0, we update that to # reflect what the OS actually assigned us. self._realPortNumber = skt.getsockname()[1] log.msg("%s starting on %s" % (self.factory.__class__, self._realPortNumber)) self.factory.doStart() skt.listen(self.backlog) self.connected = True self.disconnected = False self.reactor.addActiveHandle(self) self.socket = skt self.getFileHandle = self.socket.fileno self.doAccept()
class LookupTable: implements(ILookupTable) def __init__(self, table): self._table = table def lookup(self, c): return c in self._table
class LoopbackRelay: implements(interfaces.ITransport, interfaces.IConsumer) buffer = '' shouldLose = 0 disconnecting = 0 producer = None def __init__(self, target, logFile=None): self.target = target self.logFile = logFile def write(self, data): self.buffer = self.buffer + data if self.logFile: self.logFile.write("loopback writing %s\n" % repr(data)) def writeSequence(self, iovec): self.write("".join(iovec)) def clearBuffer(self): if self.shouldLose == -1: return if self.producer: self.producer.resumeProducing() if self.buffer: if self.logFile: self.logFile.write("loopback receiving %s\n" % repr(self.buffer)) buffer = self.buffer self.buffer = '' self.target.dataReceived(buffer) if self.shouldLose == 1: self.shouldLose = -1 self.target.connectionLost(failure.Failure(main.CONNECTION_DONE)) def loseConnection(self): if self.shouldLose != -1: self.shouldLose = 1 def getHost(self): 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__, )
class TCP4ClientEndpoint(object): """ TCP client endpoint with an IPv4 configuration. @ivar _reactor: An L{IReactorTCP} provider. @type _host: str @ivar _host: The hostname to connect to as a C{str} @type _port: int @ivar _port: The port to connect to as C{int} @type _timeout: int @ivar _timeout: number of seconds to wait before assuming the connection has failed. @type _bindAddress: tuple @type _bindAddress: a (host, port) tuple of local address to bind to, or None. """ implements(interfaces.IStreamClientEndpoint) def __init__(self, reactor, host, port, timeout=30, bindAddress=None): """ @param reactor: An L{IReactorTCP} provider @param host: A hostname, used when connecting @param port: The port number, used when connecting @param timeout: number of seconds to wait before assuming the connection has failed. @param bindAddress: a (host, port tuple of local address to bind to, or None. """ self._reactor = reactor self._host = host self._port = port self._timeout = timeout self._bindAddress = bindAddress def connect(self, protocolFactory): """ Implement L{IStreamClientEndpoint.connect} to connect via TCP. """ def _canceller(deferred): connector.stopConnecting() deferred.errback( error.ConnectingCancelledError(connector.getDestination())) try: wf = _WrappingFactory(protocolFactory, _canceller) connector = self._reactor.connectTCP( self._host, self._port, wf, timeout=self._timeout, bindAddress=self._bindAddress) return wf._onConnection except: return defer.fail()
class ProtocolToConsumerAdapter(components.Adapter): implements(interfaces.IConsumer) def write(self, data): self.original.dataReceived(data) def registerProducer(self, producer, streaming): pass def unregisterProducer(self): pass
class Anonymous(object): """ Implements the ANONYMOUS SASL authentication mechanism. This mechanism is defined in RFC 2245. """ implements(ISASLMechanism) name = 'ANONYMOUS' def getInitialResponse(self): return None
class SSL4ServerEndpoint(object): """ SSL secured TCP server endpoint with an IPv4 configuration. @ivar _reactor: An L{IReactorSSL} provider. @type _host: str @ivar _host: The hostname to connect to as a C{str} @type _port: int @ivar _port: The port to connect to as C{int} @type _sslContextFactory: L{OpenSSLCertificateOptions} @var _sslContextFactory: SSL Configuration information as an L{OpenSSLCertificateOptions} @type _backlog: int @ivar _backlog: size of the listen queue @type _interface: str @ivar _interface: the hostname to bind to, defaults to '' (all) """ implements(interfaces.IStreamServerEndpoint) def __init__(self, reactor, port, sslContextFactory, backlog=50, interface=''): """ @param reactor: An L{IReactorSSL} provider. @param port: The port number used listening @param sslContextFactory: An instance of L{lib.twisted.internet._sslverify.OpenSSLCertificateOptions}. @param timeout: number of seconds to wait before assuming the connection has failed. @param bindAddress: a (host, port tuple of local address to bind to, or None. """ self._reactor = reactor self._port = port self._sslContextFactory = sslContextFactory self._backlog = backlog self._interface = interface def listen(self, protocolFactory): """ Implement L{IStreamServerEndpoint.listen} to listen for SSL on a TCP socket. """ return defer.execute(self._reactor.listenSSL, self._port, protocolFactory, contextFactory=self._sslContextFactory, backlog=self._backlog, interface=self._interface)
class EmptyMappingTable: implements(IMappingTable) def __init__(self, in_table_function): self._in_table_function = in_table_function def map(self, c): if self._in_table_function(c): return None else: return c
class BlockingResolver: implements(IResolverSimple) def getHostByName(self, name, timeout = (1, 3, 11, 45)): try: address = socket.gethostbyname(name) except socket.error: msg = "address %r not found" % (name,) err = error.DNSLookupError(msg) return defer.fail(err) else: return defer.succeed(address)
class UNIXClientEndpoint(object): """ UnixSocket client endpoint. @type _path: str @ivar _path: a path to a unix socket on the filesystem. @type _timeout: int @ivar _timeout: number of seconds to wait before assuming the connection has failed. @type _checkPID: bool @ivar _checkPID: if True, check for a pid file to verify that a server is listening. @var _reactor: An L{IReactorUNIX} provider. """ implements(interfaces.IStreamClientEndpoint) def __init__(self, reactor, path, timeout=30, checkPID=0): """ @param reactor: An L{IReactorUNIX} provider. @param path: The path to the Unix socket file, used when connecting @param timeout: number of seconds to wait before assuming the connection has failed. @param checkPID: if True, check for a pid file to verify that a server is listening. """ self._reactor = reactor self._path = path self._timeout = timeout self._checkPID = checkPID def connect(self, protocolFactory): """ Implement L{IStreamClientEndpoint.connect} to connect via a UNIX Socket """ def _canceller(deferred): connector.stopConnecting() deferred.errback( error.ConnectingCancelledError(connector.getDestination())) try: wf = _WrappingFactory(protocolFactory, _canceller) connector = self._reactor.connectUNIX( self._path, wf, timeout=self._timeout, checkPID=self._checkPID) return wf._onConnection except: return defer.fail()
class _PollableReadPipe(_PollableResource): implements(IPushProducer) def __init__(self, pipe, receivedCallback, lostCallback): # security attributes for pipes self.pipe = pipe self.receivedCallback = receivedCallback self.lostCallback = lostCallback def checkWork(self): finished = 0 fullDataRead = [] while 1: try: buffer, bytesToRead, result = win32pipe.PeekNamedPipe( self.pipe, 1) # finished = (result == -1) if not bytesToRead: break hr, data = win32file.ReadFile(self.pipe, bytesToRead, None) fullDataRead.append(data) except win32api.error: finished = 1 break dataBuf = ''.join(fullDataRead) if dataBuf: self.receivedCallback(dataBuf) if finished: self.cleanup() return len(dataBuf) def cleanup(self): self.deactivate() self.lostCallback() def close(self): try: win32api.CloseHandle(self.pipe) except pywintypes.error: # You can't close std handles...? pass def stopProducing(self): self.close() def pauseProducing(self): self.deactivate() def resumeProducing(self): self.activate()
class PBGroupReference(pb.RemoteReference): implements(iwords.IGroup) def unjellyFor(self, unjellier, unjellyList): clsName, name, ref = unjellyList self.name = name.decode('utf-8') return pb.RemoteReference.unjellyFor(self, unjellier, [clsName, ref]) def leave(self, reason=None): return self.callRemote("leave", reason) def send(self, message): return self.callRemote("send", message)
class IPv4Address(object): """ Object representing an IPv4 socket endpoint. @ivar type: A string describing the type of transport, either 'TCP' or 'UDP'. @ivar host: A string containing the dotted-quad IP address. @ivar port: An integer representing the port number. """ # _bwHack is given to old users who think we are a tuple. They expected # addr[0] to define the socket type rather than the address family, so # the value comes from a different namespace than the new .type value: # type = map[_bwHack] # map = { 'SSL': 'TCP', 'INET': 'TCP', 'INET_UDP': 'UDP' } implements(IAddress) def __init__(self, type, host, port, _bwHack=None): assert type in ('TCP', 'UDP') self.type = type self.host = host self.port = port self._bwHack = _bwHack def __getitem__(self, index): warnings.warn( "IPv4Address.__getitem__ is deprecated. Use attributes instead.", category=DeprecationWarning, stacklevel=2) return (self._bwHack or self.type, self.host, self.port).__getitem__(index) def __getslice__(self, start, stop): warnings.warn( "IPv4Address.__getitem__ is deprecated. Use attributes instead.", category=DeprecationWarning, stacklevel=2) return (self._bwHack or self.type, self.host, self.port)[start:stop] def __eq__(self, other): if isinstance(other, tuple): return tuple(self) == other elif isinstance(other, IPv4Address): a = (self.type, self.host, self.port) b = (other.type, other.host, other.port) return a == b return False def __repr__(self): return 'IPv4Address(%s, %r, %d)' % (self.type, self.host, self.port)
class ConsumerToProtocolAdapter(components.Adapter): implements(interfaces.IProtocol) def dataReceived(self, data): self.original.write(data) def connectionLost(self, reason): pass def makeConnection(self, transport): pass def connectionMade(self): pass
class TOCAccount(basesupport.AbstractAccount): implements(interfaces.IAccount) gatewayType = "AIM (TOC)" _groupFactory = TOCGroup _personFactory = TOCPerson def _startLogOn(self, chatui): logonDeferred = defer.Deferred() cc = protocol.ClientCreator(reactor, TOCProto, self, chatui, logonDeferred) d = cc.connectTCP(self.host, self.port) d.addErrback(logonDeferred.errback) return logonDeferred
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.""" h, p = self.client return address.IPv4Address('TCP', h, p, 'SSL')
class UNIXServerEndpoint(object): """ UnixSocket server endpoint. @type path: str @ivar path: a path to a unix socket on the filesystem. @type _listenArgs: dict @ivar _listenArgs: A C{dict} of keyword args that will be passed to L{IReactorUNIX.listenUNIX} @var _reactor: An L{IReactorTCP} provider. """ implements(interfaces.IStreamServerEndpoint) def __init__(self, reactor, address, backlog=50, mode=0666, wantPID=0):
class UNIXAddress(object): """ Object representing a UNIX socket endpoint. @ivar name: The filename associated with this socket. @type name: C{str} """ implements(IAddress) def __init__(self, name, _bwHack='UNIX'): self.name = name self._bwHack = _bwHack def __getitem__(self, index): warnings.warn( "UNIXAddress.__getitem__ is deprecated. Use attributes instead.", category=DeprecationWarning, stacklevel=2) return (self._bwHack, self.name).__getitem__(index) def __getslice__(self, start, stop): warnings.warn( "UNIXAddress.__getitem__ is deprecated. Use attributes instead.", category=DeprecationWarning, stacklevel=2) return (self._bwHack, self.name)[start:stop] def __eq__(self, other): if isinstance(other, tuple): return tuple(self) == other elif isinstance(other, UNIXAddress): # First do the simple thing and check to see if the names are the # same. If not, and the paths exist, check to see if they point to # the same file. if self.name == other.name: return True else: try: return os.path.samefile(self.name, other.name) except OSError: pass return False def __repr__(self): return 'UNIXAddress(%r)' % (self.name, )
class Chargen(protocol.Protocol): """Generate repeating noise (RFC 864)""" noise = r'@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ !"#$%&?' implements(interfaces.IProducer) def connectionMade(self): self.transport.registerProducer(self, 0) def resumeProducing(self): self.transport.write(self.noise) def pauseProducing(self): pass def stopProducing(self): pass
class DigestAuthorizer: CHALLENGE_LIFETIME = 15 implements(IAuthorizer) def __init__(self): warnings.warn( "lib.twisted.protocols.sip.DigestAuthorizer was deprecated " "in Twisted 9.0.0", category=DeprecationWarning, stacklevel=2) self.outstanding = {} def generateNonce(self): c = tuple([random.randrange(sys.maxint) for _ in range(3)]) c = '%d%d%d' % c return c def generateOpaque(self): return str(random.randrange(sys.maxint)) def getChallenge(self, peer): c = self.generateNonce() o = self.generateOpaque() self.outstanding[o] = c return ','.join(( 'nonce="%s"' % c, 'opaque="%s"' % o, 'qop-options="auth"', 'algorithm="MD5"', )) def decode(self, response): response = ' '.join(response.splitlines()) parts = response.split(',') auth = dict([(k.strip(), unq(v.strip())) for (k, v) in [p.split('=', 1) for p in parts]]) try: username = auth['username'] except KeyError: raise SIPError(401) try: return DigestedCredentials(username, auth, self.outstanding) except: raise SIPError(400)