def __init__(self, dispatcher, skt): FileDescriptor.__init__(self, dispatcher.reactor) self.status = None self.dispatcher = dispatcher self.skt = skt # XXX needs to be set non-blocking by somebody self.fileno = skt.fileno self.outgoingSocketQueue = []
def connectionLost(self, reason): if self.tunfd >= 0: try: os.close(self.tunfd) except OSError as _: logger.error("cannot close tunfd") FileDescriptor.connectionLost(self, reason)
def close(self): """ @summary: Close raw layer Use File descriptor directly to not use TLS close Because is bugged """ FileDescriptor.loseConnection(self.getDescriptor())
def close(self): """ @summary: Close raw layer Use File descriptor directly to not use TLS close Because is bugged """ FileDescriptor.loseConnection(self.transport)
def startReading(self): if self._fd is not None and not self._fd.closed: FileDescriptor.startReading(self) return self._fd = self._path.open('r') setNonBlocking(self._fd) FileDescriptor.startReading(self)
def __init__(self, protocol, device, reactor = None): FileDescriptor.__init__(self, reactor = reactor) self.protocol = protocol self.protocol.makeConnection(self) self.__device = open(device, "r+w+") self.reading = False self.backToReading = False
def __init__(self, protocol, device, reactor=None): FileDescriptor.__init__(self, reactor=reactor) self.protocol = protocol self.protocol.makeConnection(self) self.__device = open(device, "r+w+") self.reading = False self.backToReading = False
def __init__(self, dst): FileDescriptor.__init__(self) self.connected = 1 self.disconnected = 0 try: self.file = os.open(dst, os.O_WRONLY | os.O_CREAT) except Exception, e: log.msg(str(e), logLevel=logging.ERROR)
def __init__(self, group, reactor=None): FileDescriptor.__init__(self, reactor) self.wrapper = NFLog() self.wrapper.open() self.wrapper.bindProtocolFamily(AF_INET) self.group = group self.wrapper.bindGroup(group) self.wrapper.setMode(NFULNL_COPY_PACKET, 0xFFFF) self.wrapper.setCallback(self.nflogCallback)
def connectionLost(self, reason): """ The connection was lost. """ FileDescriptor.connectionLost(self, reason) self.protocol.connectionLost(reason) self.connected = 0 if self._fd is not None: os.close(self._fd)
def _simpleSetup(self): reactor = self.buildReactor() client, server = self._connectedPair() fd = FileDescriptor(reactor) fd.fileno = client.fileno return reactor, fd, server
def __init__(self, dispatcher, inSocket, outSocket, status, slavenum): FileDescriptor.__init__(self, dispatcher.reactor) self.status = status self.slavenum = slavenum self.dispatcher = dispatcher self.inSocket = inSocket self.outSocket = outSocket # XXX needs to be set non-blocking by somebody self.fileno = outSocket.fileno self.outgoingSocketQueue = [] self.pendingCloseSocketQueue = []
def startReading(self): """ Start waiting for read availability """ if self.connected: FileDescriptor.startReading(self) return self._fd = os.open(self.path, os.O_RDONLY | os.O_NONBLOCK) self.connected = 1 FileDescriptor.startReading(self)
def write(self, bytes): """ Write some bytes to this connection, passing them through a TLS layer if necessary, or discarding them if the connection has already been lost. """ if self.TLS: if self.connected: self.protocol.write(bytes) else: FileDescriptor.write(self, bytes)
def connectionLost(self, reason): """ Release the inotify file descriptor and do the necessary cleanup """ FileDescriptor.connectionLost(self, reason) if self._fd >= 0: try: os.close(self._fd) except OSError, e: log.err(e, "Couldn't close INotify file descriptor.")
def unregisterProducer(self): """ Unregister a producer. If TLS is enabled, the TLS connection handles this. """ if self.TLS: self.protocol.unregisterProducer() else: FileDescriptor.unregisterProducer(self)
def connectionLost(self, reason): """ Release the inotify file descriptor and do the necessary cleanup """ FileDescriptor.connectionLost(self, reason) if self._fd >= 0: try: os.close(self._fd) except OSError as e: log.err(e, "Couldn't close INotify file descriptor.")
def writeSequence(self, iovec): """ Write some bytes to this connection, scatter/gather-style, passing them through a TLS layer if necessary, or discarding them if the connection has already been lost. """ if self.TLS: if self.connected: self.protocol.writeSequence(iovec) else: FileDescriptor.writeSequence(self, iovec)
def loseConnection(self): """ Close this connection after writing all pending data. If TLS has been negotiated, perform a TLS shutdown. """ if self.TLS: if self.connected and not self.disconnecting: self.protocol.loseConnection() else: FileDescriptor.loseConnection(self)
def __new__(cls, *args, **kwargs): obj = getattr(cls, '_instance_', None) if obj is not None: return obj else: obj = super(INotify, cls).__new__(cls, *args, **kwargs) # Check inotify support by checking for the required functions obj.libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library('c')) if len([ function for function in "inotify_add_watch inotify_init inotify_rm_watch".split() if hasattr(obj.libc, function) ]) == 3: obj.inotify_init = obj.libc.inotify_init obj.inotify_add_watch = obj.libc_inotify_add_watch obj.inotify_rm_watch = obj.libc_inotify_rm_watch else: print("inotify.py - can't use libc6, 2.4 or higher needed") import platform if platform.system() != 'Linux': raise SystemError( "unknown system '%r', INotify support disabled" % platform.uname()) machine = platform.machine() try: obj._init_syscall_id = _inotify_syscalls[machine][0] obj._add_watch_syscall_id = _inotify_syscalls[machine][1] obj._rm_watch_syscall_id = _inotify_syscalls[machine][2] obj.inotify_init = obj._inotify_init obj.inotify_add_watch = obj._inotify_add_watch obj.inotify_rm_watch = obj._inotify_rm_watch except: raise SystemError( "unknown system '%s', INotify support disabled" % machine) FileDescriptor.__init__(obj) obj._fd = obj.inotify_init() if obj._fd < 0: raise SystemError("INotify initialization error.") fdesc.setNonBlocking(obj._fd) reactor.addReader(obj) obj._buffer = '' # Mapping from wds to Watch objects obj._watchpoints = {} # Mapping from paths to wds obj._watchpaths = {} cls._instance_ = obj return obj
def write(self, bytes): """ Write some bytes to this connection, passing them through a TLS layer if necessary, or discarding them if the connection has already been lost. """ if self.TLS: if self.connected: self.protocol.write(bytes) elif self._tlsWaiting is not None: self._tlsWaiting.bufferedData.append(bytes) else: FileDescriptor.write(self, bytes)
def startWriting(self): """ Start waiting for write availability. Will raise L{OSError} with errno == ENXIO, if other end hasn't been opened (see fifo(7)). @raise OSError: if other end hasn't been opened (errno == ENXIO) """ if self.connected: FileDescriptor.startWriting(self) return self._fd = os.open(self.path.path, os.O_WRONLY | os.O_NONBLOCK) self.connected = 1 FileDescriptor.startWriting(self)
def registerProducer(self, producer, streaming): """ Register a producer. If TLS is enabled, the TLS connection handles this. """ if self.TLS: # Registering a producer before we're connected shouldn't be a # problem. If we end up with a write(), that's already handled in # the write() code above, and there are no other potential # side-effects. self.protocol.registerProducer(producer, streaming) else: FileDescriptor.registerProducer(self, producer, streaming)
def test_writeSequenceWithUnicodeRaisesException(self): """ L{FileDescriptor.writeSequence} doesn't accept unicode data. """ fileDescriptor = FileDescriptor(reactor=object()) self.assertRaises(TypeError, fileDescriptor.writeSequence, [b'foo', u'bar', b'baz'])
def __new__(cls, *args, **kwargs): obj = getattr(cls, '_instance_', None) if obj is not None: return obj else: obj = super(INotify, cls).__new__(cls, *args, **kwargs) # Check inotify support by checking for the required functions obj.libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library('c')) if len([function for function in "inotify_add_watch inotify_init inotify_rm_watch".split() if hasattr(obj.libc, function)]) == 3: obj.inotify_init = obj.libc.inotify_init obj.inotify_add_watch = obj.libc_inotify_add_watch obj.inotify_rm_watch = obj.libc_inotify_rm_watch else: print("inotify.py - can't use libc6, 2.4 or higher needed") import platform if platform.system() != 'Linux': raise SystemError("unknown system '%r', INotify support disabled" % platform.uname()) machine = platform.machine() try: obj._init_syscall_id = _inotify_syscalls[machine][0] obj._add_watch_syscall_id = _inotify_syscalls[machine][1] obj._rm_watch_syscall_id = _inotify_syscalls[machine][2] obj.inotify_init = obj._inotify_init obj.inotify_add_watch = obj._inotify_add_watch obj.inotify_rm_watch = obj._inotify_rm_watch except: raise SystemError("unknown system '%s', INotify support disabled" % machine) FileDescriptor.__init__(obj) obj._fd = obj.inotify_init() if obj._fd < 0: raise SystemError("INotify initialization error.") fdesc.setNonBlocking(obj._fd) reactor.addReader(obj) obj._buffer = '' # Mapping from wds to Watch objects obj._watchpoints = {} # Mapping from paths to wds obj._watchpaths = {} cls._instance_ = obj return obj
def doWrite(self): result = FileDescriptor.doWrite(self) if self._tlsWaiting is not None: if not self.dataBuffer and not self._tempDataBuffer: waiting = self._tlsWaiting self._tlsWaiting = None self.startTLS(waiting.context, waiting.extra) self.writeSequence(waiting.bufferedData) return result
def __new__(cls, *args, **kwargs): obj = getattr(cls,'_instance_',None) if obj is not None: return obj else: if ctypes == None: raise SystemError, "ctypes not detected on this system, INotify support disabled" obj = super(INotify, cls).__new__(cls, *args, **kwargs) try: obj.libc = ctypes.CDLL("libc.so.6") except: raise SystemError, "libc not found, INotify support disabled" try: obj.inotify_init = obj.libc.inotify_init #print "horray, we have a libc with inotify support" obj.inotify_add_watch = obj.libc_inotify_add_watch obj.inotify_rm_watch = obj.libc_inotify_rm_watch except: import platform machine = platform.machine() try: obj._init_syscall_id = _inotify_syscalls[machine][0] obj._add_watch_syscall_id = _inotify_syscalls[machine][1] obj._rm_watch_syscall_id = _inotify_syscalls[machine][2] except: raise SystemError, "unknown system '%s', INotify support disabled" % machine FileDescriptor.__init__(obj) obj._fd = obj.inotify_init() if obj._fd < 0: raise SystemError, "INotify support not detected on this system." fdesc.setNonBlocking(obj._fd) # FIXME do we need this? reactor.addReader(obj) obj._buffer = '' obj._watchpoints = {} cls._instance_ = obj return obj
def dataReceived(self, data): """ @summary: Inherit from twisted.protocol class main event of received data @param data: string data receive from twisted """ #add in buffer if data: self._buffer += data else: FileDescriptor.loseConnection(self.getDescriptor()) #while buffer have expected size call local callback while self._expectedLen > 0 and len(self._buffer) >= self._expectedLen: #expected data is first expected bytes expectedData = Stream(self._buffer[0:self._expectedLen]) #rest is for next event of automata self._buffer = self._buffer[self._expectedLen:] #call recv function self.recv(expectedData)
def __init__(self, protocol, filename, reactor=None, mode='r+'): """ Creates an instance of FileTransport. :param protocol: Twisted protocol instance. Must implement the {IProtocol} interface :param filename: name of file to open (e.g. '/dev/ttyUSB0') :param reactor: Twisted reactor instance :param mode: file read/write mode (e.g. 'r', 'w', 'r+', etc...) """ FileDescriptor.__init__(self, reactor) self.filename = filename self._f = open(filename, mode=mode) fdesc.setNonBlocking(self._f) self.flushInput() self.flushOutput() self.protocol = protocol self.protocol.makeConnection(self) self.startReading() self.connected = 1
def __init__(self, fd, transportFactory, protocolFactory): """ @param fd: a file descriptor @type fd: C{int} @param transportFactory: a 4-argument function that takes the socket object produced from the file descriptor, the peer address of that socket, the (non-ancillary) data sent along with the incoming file descriptor, and the protocol built along with it, and returns an L{ITransport} provider. Note that this should NOT call C{makeConnection} on the protocol that it produces, as this class will do that. @param protocolFactory: an L{IProtocolFactory} """ FileDescriptor.__init__(self) self.fd = fd self.transportFactory = transportFactory self.protocolFactory = protocolFactory self.statusQueue = []
def __init__(self, reactor=None): FileDescriptor.__init__(self, reactor=reactor) # Smart way to allow parametrization of libc so I can override # it and test for the system errors. self._fd = self._inotify.init() fdesc.setNonBlocking(self._fd) fdesc._setCloseOnExec(self._fd) # The next 2 lines are needed to have self.loseConnection() # to call connectionLost() on us. Since we already created the # fd that talks to inotify we want to be notified even if we # haven't yet started reading. self.connected = 1 self._writeDisconnected = True self._buffer = '' self._watchpoints = {} self._watchpaths = {}
def __init__(self, fd, transportFactory, protocolFactory): """ @param fd: the file descriptor representing a UNIX socket connected to a I{master process}. We will call L{recv1msg} on this socket to receive file descriptors. @type fd: C{int} @param transportFactory: a 4-argument function that takes the socket object produced from the file descriptor, the peer address of that socket, the (non-ancillary) data sent along with the incoming file descriptor, and the protocol built along with it, and returns an L{ITransport} provider. Note that this should NOT call C{makeConnection} on the protocol that it produces, as this class will do that. @param protocolFactory: an L{IProtocolFactory} """ FileDescriptor.__init__(self) self.fd = fd self.transportFactory = transportFactory self.protocolFactory = protocolFactory self.statusQueue = []
def doWrite(self): """ Write out some data from the send buffer. If the buffer becomes empty and TLS has been requested but not yet enabled, enable it. """ result = FileDescriptor.doWrite(self) if self._tlsWaiting is not None: if not self.dataBuffer and not self._tempDataBuffer: waiting = self._tlsWaiting self._tlsWaiting = None self.startTLS(waiting.context, waiting.extra) self.writeSequence(waiting.bufferedData) return result
def startReading(self): self.reading = True FileDescriptor.startReading(self)
def __init__(self, reactor, fd, cb): self._fileno = fd self.cb = cb FileDescriptor.__init__(self, reactor)
def __init__(self, reactor, fd, read_callback, write_callback): FileDescriptor.__init__(self, reactor) self._fd = fd self._read_callback = read_callback self._write_callback = write_callback
def connectionLost(self, reason): FileDescriptor.connectionLost(self, reason) self.protocol.connectionLost(reason)
def write(self, bytes): if self._tlsWaiting is not None: self._tlsWaiting.bufferedData.append(bytes) else: FileDescriptor.write(self, bytes)
def __init__(self, filename, protocol): FileDescriptor.__init__(self) self.fileno = os.open(filename, os.O_RDONLY) fdesc.setNonBlocking(self.fileno) self.protocol = protocol self.protocol.makeConnection(self)
def __init__(self): FileDescriptor.__init__(self, reactor=object()) self._written = [] self._freeSpace = 0
def test_writeWithUnicodeRaisesException(self): """ L{FileDescriptor.write} doesn't accept unicode data. """ fileDescriptor = FileDescriptor(reactor=object()) self.assertRaises(TypeError, fileDescriptor.write, u'foo')
def writeSequence(self, iovec): if self._tlsWaiting is not None: self._tlsWaiting.bufferedData.extend(iovec) else: FileDescriptor.writeSequence(self, iovec)
def __init__(self, path, _reactor=None): self._fd = None self._path = path FileDescriptor.__init__(self, _reactor)
def write(self, data): if self.reading: self.backToReading = True self.stopReading() FileDescriptor.write(self, data)
def stopReading(self): self.reading = False FileDescriptor.stopReading(self)