summaryrefslogtreecommitdiffstats
path: root/tools/buildbot/pylibs/twisted/internet
diff options
context:
space:
mode:
Diffstat (limited to 'tools/buildbot/pylibs/twisted/internet')
-rw-r--r--tools/buildbot/pylibs/twisted/internet/__init__.py10
-rw-r--r--tools/buildbot/pylibs/twisted/internet/_dumbwin32proc.py337
-rw-r--r--tools/buildbot/pylibs/twisted/internet/_dumbwin32proc_orig.py338
-rw-r--r--tools/buildbot/pylibs/twisted/internet/_javaserialport.py78
-rw-r--r--tools/buildbot/pylibs/twisted/internet/_pollingfile.py270
-rw-r--r--tools/buildbot/pylibs/twisted/internet/_posixserialport.py60
-rw-r--r--tools/buildbot/pylibs/twisted/internet/_posixstdio.py171
-rw-r--r--tools/buildbot/pylibs/twisted/internet/_sslverify.py948
-rw-r--r--tools/buildbot/pylibs/twisted/internet/_threadedselect.py362
-rw-r--r--tools/buildbot/pylibs/twisted/internet/_win32serialport.py112
-rw-r--r--tools/buildbot/pylibs/twisted/internet/_win32stdio.py116
-rw-r--r--tools/buildbot/pylibs/twisted/internet/abstract.py368
-rw-r--r--tools/buildbot/pylibs/twisted/internet/address.py113
-rw-r--r--tools/buildbot/pylibs/twisted/internet/base.py1069
-rw-r--r--tools/buildbot/pylibs/twisted/internet/cfreactor.py342
-rw-r--r--tools/buildbot/pylibs/twisted/internet/cfsupport/cfdate.pxi2
-rw-r--r--tools/buildbot/pylibs/twisted/internet/cfsupport/cfdecl.pxi227
-rw-r--r--tools/buildbot/pylibs/twisted/internet/cfsupport/cfrunloop.pxi104
-rw-r--r--tools/buildbot/pylibs/twisted/internet/cfsupport/cfsocket.pxi111
-rw-r--r--tools/buildbot/pylibs/twisted/internet/cfsupport/cfsupport.c2136
-rw-r--r--tools/buildbot/pylibs/twisted/internet/cfsupport/cfsupport.pyx6
-rw-r--r--tools/buildbot/pylibs/twisted/internet/cfsupport/python.pxi5
-rw-r--r--tools/buildbot/pylibs/twisted/internet/cfsupport/setup.py50
-rw-r--r--tools/buildbot/pylibs/twisted/internet/default.py21
-rw-r--r--tools/buildbot/pylibs/twisted/internet/defer.py1107
-rw-r--r--tools/buildbot/pylibs/twisted/internet/epollreactor.py256
-rw-r--r--tools/buildbot/pylibs/twisted/internet/error.py305
-rw-r--r--tools/buildbot/pylibs/twisted/internet/fdesc.py93
-rw-r--r--tools/buildbot/pylibs/twisted/internet/glib2reactor.py49
-rw-r--r--tools/buildbot/pylibs/twisted/internet/gtk2reactor.py295
-rw-r--r--tools/buildbot/pylibs/twisted/internet/gtkreactor.py233
-rw-r--r--tools/buildbot/pylibs/twisted/internet/interfaces.py1417
-rw-r--r--tools/buildbot/pylibs/twisted/internet/iocpreactor/__init__.py2
-rw-r--r--tools/buildbot/pylibs/twisted/internet/iocpreactor/abstract.py456
-rw-r--r--tools/buildbot/pylibs/twisted/internet/iocpreactor/build.bat4
-rw-r--r--tools/buildbot/pylibs/twisted/internet/iocpreactor/const.py26
-rw-r--r--tools/buildbot/pylibs/twisted/internet/iocpreactor/interfaces.py33
-rw-r--r--tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/acceptex.pxi38
-rw-r--r--tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/connectex.pxi34
-rw-r--r--tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/iocpsupport.c2003
-rw-r--r--tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/iocpsupport.pyx250
-rw-r--r--tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/winsock_pointers.c62
-rw-r--r--tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/winsock_pointers.h51
-rw-r--r--tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/wsarecv.pxi61
-rw-r--r--tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/wsasend.pxi27
-rw-r--r--tools/buildbot/pylibs/twisted/internet/iocpreactor/notes.txt24
-rw-r--r--tools/buildbot/pylibs/twisted/internet/iocpreactor/reactor.py211
-rw-r--r--tools/buildbot/pylibs/twisted/internet/iocpreactor/setup.py23
-rw-r--r--tools/buildbot/pylibs/twisted/internet/iocpreactor/tcp.py497
-rw-r--r--tools/buildbot/pylibs/twisted/internet/iocpreactor/udp.py389
-rw-r--r--tools/buildbot/pylibs/twisted/internet/kqreactor.py232
-rw-r--r--tools/buildbot/pylibs/twisted/internet/main.py28
-rw-r--r--tools/buildbot/pylibs/twisted/internet/pollreactor.py217
-rw-r--r--tools/buildbot/pylibs/twisted/internet/posixbase.py406
-rw-r--r--tools/buildbot/pylibs/twisted/internet/process.py922
-rw-r--r--tools/buildbot/pylibs/twisted/internet/protocol.py674
-rw-r--r--tools/buildbot/pylibs/twisted/internet/pyuisupport.py37
-rw-r--r--tools/buildbot/pylibs/twisted/internet/qtreactor.py15
-rw-r--r--tools/buildbot/pylibs/twisted/internet/reactor.py12
-rw-r--r--tools/buildbot/pylibs/twisted/internet/selectreactor.py204
-rw-r--r--tools/buildbot/pylibs/twisted/internet/serialport.py65
-rw-r--r--tools/buildbot/pylibs/twisted/internet/ssl.py205
-rw-r--r--tools/buildbot/pylibs/twisted/internet/stdio.py31
-rw-r--r--tools/buildbot/pylibs/twisted/internet/task.py420
-rw-r--r--tools/buildbot/pylibs/twisted/internet/tcp.py894
-rw-r--r--tools/buildbot/pylibs/twisted/internet/test/__init__.py6
-rw-r--r--tools/buildbot/pylibs/twisted/internet/test/test_gtk2reactor.py43
-rw-r--r--tools/buildbot/pylibs/twisted/internet/test/test_iocp.py105
-rw-r--r--tools/buildbot/pylibs/twisted/internet/threads.py88
-rw-r--r--tools/buildbot/pylibs/twisted/internet/tksupport.py68
-rw-r--r--tools/buildbot/pylibs/twisted/internet/udp.py385
-rw-r--r--tools/buildbot/pylibs/twisted/internet/unix.py297
-rw-r--r--tools/buildbot/pylibs/twisted/internet/utils.py172
-rw-r--r--tools/buildbot/pylibs/twisted/internet/win32eventreactor.py244
-rw-r--r--tools/buildbot/pylibs/twisted/internet/wxreactor.py181
-rw-r--r--tools/buildbot/pylibs/twisted/internet/wxsupport.py61
76 files changed, 0 insertions, 21314 deletions
diff --git a/tools/buildbot/pylibs/twisted/internet/__init__.py b/tools/buildbot/pylibs/twisted/internet/__init__.py
deleted file mode 100644
index e87f846..0000000
--- a/tools/buildbot/pylibs/twisted/internet/__init__.py
+++ /dev/null
@@ -1,10 +0,0 @@
-
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-
-Twisted Internet: Asynchronous I/O and Events.
-
-"""
diff --git a/tools/buildbot/pylibs/twisted/internet/_dumbwin32proc.py b/tools/buildbot/pylibs/twisted/internet/_dumbwin32proc.py
deleted file mode 100644
index 4334f77..0000000
--- a/tools/buildbot/pylibs/twisted/internet/_dumbwin32proc.py
+++ /dev/null
@@ -1,337 +0,0 @@
-# -*- test-case-name: twisted.test.test_process -*-
-# Copyright (c) 2001-2008 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-http://isometric.sixsided.org/_/gates_in_the_head/
-"""
-
-import os
-
-# Win32 imports
-import win32api
-import win32con
-import win32event
-import win32file
-import win32pipe
-import win32process
-import win32security
-
-import pywintypes
-
-# security attributes for pipes
-PIPE_ATTRS_INHERITABLE = win32security.SECURITY_ATTRIBUTES()
-PIPE_ATTRS_INHERITABLE.bInheritHandle = 1
-
-from zope.interface import implements
-from twisted.internet.interfaces import IProcessTransport, IConsumer, IProducer
-
-from twisted.python.win32 import quoteArguments
-
-from twisted.internet import error
-from twisted.python import failure
-
-from twisted.internet import _pollingfile
-
-def debug(msg):
- import sys
- print msg
- sys.stdout.flush()
-
-class _Reaper(_pollingfile._PollableResource):
-
- def __init__(self, proc):
- self.proc = proc
-
- def checkWork(self):
- if win32event.WaitForSingleObject(self.proc.hProcess, 0) != win32event.WAIT_OBJECT_0:
- return 0
- exitCode = win32process.GetExitCodeProcess(self.proc.hProcess)
- self.deactivate()
- self.proc.processEnded(exitCode)
- return 0
-
-
-def _findShebang(filename):
- """
- Look for a #! line, and return the value following the #! if one exists, or
- None if this file is not a script.
-
- I don't know if there are any conventions for quoting in Windows shebang
- lines, so this doesn't support any; therefore, you may not pass any
- arguments to scripts invoked as filters. That's probably wrong, so if
- somebody knows more about the cultural expectations on Windows, please feel
- free to fix.
-
- This shebang line support was added in support of the CGI tests;
- appropriately enough, I determined that shebang lines are culturally
- accepted in the Windows world through this page:
-
- http://www.cgi101.com/learn/connect/winxp.html
-
- @param filename: str representing a filename
-
- @return: a str representing another filename.
- """
- f = file(filename, 'ru')
- if f.read(2) == '#!':
- exe = f.readline(1024).strip('\n')
- return exe
-
-def _invalidWin32App(pywinerr):
- """
- Determine if a pywintypes.error is telling us that the given process is
- 'not a valid win32 application', i.e. not a PE format executable.
-
- @param pywinerr: a pywintypes.error instance raised by CreateProcess
-
- @return: a boolean
- """
-
- # Let's do this better in the future, but I have no idea what this error
- # is; MSDN doesn't mention it, and there is no symbolic constant in
- # win32process module that represents 193.
-
- return pywinerr.args[0] == 193
-
-class Process(_pollingfile._PollingTimer):
- """A process that integrates with the Twisted event loop.
-
- If your subprocess is a python program, you need to:
-
- - Run python.exe with the '-u' command line option - this turns on
- unbuffered I/O. Buffering stdout/err/in can cause problems, see e.g.
- http://support.microsoft.com/default.aspx?scid=kb;EN-US;q1903
-
- - If you don't want Windows messing with data passed over
- stdin/out/err, set the pipes to be in binary mode::
-
- import os, sys, mscvrt
- msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
- msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
- msvcrt.setmode(sys.stderr.fileno(), os.O_BINARY)
-
- """
- implements(IProcessTransport, IConsumer, IProducer)
-
- buffer = ''
- pid = None
-
- def __init__(self, reactor, protocol, command, args, environment, path):
- _pollingfile._PollingTimer.__init__(self, reactor)
- self.protocol = protocol
-
- # security attributes for pipes
- sAttrs = win32security.SECURITY_ATTRIBUTES()
- sAttrs.bInheritHandle = 1
-
- # create the pipes which will connect to the secondary process
- self.hStdoutR, hStdoutW = win32pipe.CreatePipe(sAttrs, 0)
- self.hStderrR, hStderrW = win32pipe.CreatePipe(sAttrs, 0)
- hStdinR, self.hStdinW = win32pipe.CreatePipe(sAttrs, 0)
-
- win32pipe.SetNamedPipeHandleState(self.hStdinW,
- win32pipe.PIPE_NOWAIT,
- None,
- None)
-
- # set the info structure for the new process.
- StartupInfo = win32process.STARTUPINFO()
- StartupInfo.hStdOutput = hStdoutW
- StartupInfo.hStdError = hStderrW
- StartupInfo.hStdInput = hStdinR
- StartupInfo.dwFlags = win32process.STARTF_USESTDHANDLES
-
- # Create new handles whose inheritance property is false
- currentPid = win32api.GetCurrentProcess()
-
- tmp = win32api.DuplicateHandle(currentPid, self.hStdoutR, currentPid, 0, 0,
- win32con.DUPLICATE_SAME_ACCESS)
- win32file.CloseHandle(self.hStdoutR)
- self.hStdoutR = tmp
-
- tmp = win32api.DuplicateHandle(currentPid, self.hStderrR, currentPid, 0, 0,
- win32con.DUPLICATE_SAME_ACCESS)
- win32file.CloseHandle(self.hStderrR)
- self.hStderrR = tmp
-
- tmp = win32api.DuplicateHandle(currentPid, self.hStdinW, currentPid, 0, 0,
- win32con.DUPLICATE_SAME_ACCESS)
- win32file.CloseHandle(self.hStdinW)
- self.hStdinW = tmp
-
- # Add the specified environment to the current environment - this is
- # necessary because certain operations are only supported on Windows
- # if certain environment variables are present.
-
- env = os.environ.copy()
- env.update(environment or {})
-
- cmdline = quoteArguments(args)
- # TODO: error detection here.
- def doCreate():
- self.hProcess, self.hThread, self.pid, dwTid = win32process.CreateProcess(
- command, cmdline, None, None, 1, 0, env, path, StartupInfo)
- try:
- doCreate()
- except pywintypes.error, pwte:
- if not _invalidWin32App(pwte):
- # This behavior isn't _really_ documented, but let's make it
- # consistent with the behavior that is documented.
- raise OSError(pwte)
- else:
- # look for a shebang line. Insert the original 'command'
- # (actually a script) into the new arguments list.
- sheb = _findShebang(command)
- if sheb is None:
- raise OSError(
- "%r is neither a Windows executable, "
- "nor a script with a shebang line" % command)
- else:
- args = list(args)
- args.insert(0, command)
- cmdline = quoteArguments(args)
- origcmd = command
- command = sheb
- try:
- # Let's try again.
- doCreate()
- except pywintypes.error, pwte2:
- # d'oh, failed again!
- if _invalidWin32App(pwte2):
- raise OSError(
- "%r has an invalid shebang line: "
- "%r is not a valid executable" % (
- origcmd, sheb))
- raise OSError(pwte2)
-
- win32file.CloseHandle(self.hThread)
-
- # close handles which only the child will use
- win32file.CloseHandle(hStderrW)
- win32file.CloseHandle(hStdoutW)
- win32file.CloseHandle(hStdinR)
-
- self.closed = 0
- self.closedNotifies = 0
-
- # set up everything
- self.stdout = _pollingfile._PollableReadPipe(
- self.hStdoutR,
- lambda data: self.protocol.childDataReceived(1, data),
- self.outConnectionLost)
-
- self.stderr = _pollingfile._PollableReadPipe(
- self.hStderrR,
- lambda data: self.protocol.childDataReceived(2, data),
- self.errConnectionLost)
-
- self.stdin = _pollingfile._PollableWritePipe(
- self.hStdinW, self.inConnectionLost)
-
- for pipewatcher in self.stdout, self.stderr, self.stdin:
- self._addPollableResource(pipewatcher)
-
-
- # notify protocol
- self.protocol.makeConnection(self)
-
- # (maybe?) a good idea in win32er, otherwise not
- # self.reactor.addEvent(self.hProcess, self, 'inConnectionLost')
-
-
- def signalProcess(self, signalID):
- if self.pid is None:
- raise error.ProcessExitedAlready()
- if signalID in ("INT", "TERM", "KILL"):
- os.popen('taskkill /T /F /PID %s' % self.pid)
-
- def processEnded(self, status):
- """
- This is called when the child terminates.
- """
- self.pid = None
- if status == 0:
- err = error.ProcessDone(status)
- else:
- err = error.ProcessTerminated(status)
- self.protocol.processEnded(failure.Failure(err))
-
-
- def write(self, data):
- """Write data to the process' stdin."""
- self.stdin.write(data)
-
- def writeSequence(self, seq):
- """Write data to the process' stdin."""
- self.stdin.writeSequence(seq)
-
- def closeChildFD(self, fd):
- if fd == 0:
- self.closeStdin()
- elif fd == 1:
- self.closeStdout()
- elif fd == 2:
- self.closeStderr()
- else:
- raise NotImplementedError("Only standard-IO file descriptors available on win32")
-
- def closeStdin(self):
- """Close the process' stdin.
- """
- self.stdin.close()
-
- def closeStderr(self):
- self.stderr.close()
-
- def closeStdout(self):
- self.stdout.close()
-
- def loseConnection(self):
- """Close the process' stdout, in and err."""
- self.closeStdin()
- self.closeStdout()
- self.closeStderr()
-
- def outConnectionLost(self):
- self.protocol.childConnectionLost(1)
- self.connectionLostNotify()
-
- def errConnectionLost(self):
- self.protocol.childConnectionLost(2)
- self.connectionLostNotify()
-
- def inConnectionLost(self):
- self.protocol.childConnectionLost(0)
- self.connectionLostNotify()
-
- def connectionLostNotify(self):
- """Will be called 3 times, by stdout/err threads and process handle."""
- self.closedNotifies = self.closedNotifies + 1
- if self.closedNotifies == 3:
- self.closed = 1
- self._addPollableResource(_Reaper(self))
-
- # IConsumer
- def registerProducer(self, producer, streaming):
- self.stdin.registerProducer(producer, streaming)
-
- def unregisterProducer(self):
- self.stdin.unregisterProducer()
-
- # IProducer
- def pauseProducing(self):
- self._pause()
-
- def resumeProducing(self):
- self._unpause()
-
- def stopProducing(self):
- self.loseConnection()
-
-
- def __repr__(self):
- """
- Return a string representation of the process.
- """
- return "<%s pid=%s>" % (self.__class__.__name__, self.pid)
diff --git a/tools/buildbot/pylibs/twisted/internet/_dumbwin32proc_orig.py b/tools/buildbot/pylibs/twisted/internet/_dumbwin32proc_orig.py
deleted file mode 100644
index 44e3837..0000000
--- a/tools/buildbot/pylibs/twisted/internet/_dumbwin32proc_orig.py
+++ /dev/null
@@ -1,338 +0,0 @@
-# -*- test-case-name: twisted.test.test_process -*-
-# Copyright (c) 2001-2008 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-http://isometric.sixsided.org/_/gates_in_the_head/
-"""
-
-import os
-
-# Win32 imports
-import win32api
-import win32con
-import win32event
-import win32file
-import win32pipe
-import win32process
-import win32security
-
-import pywintypes
-
-# security attributes for pipes
-PIPE_ATTRS_INHERITABLE = win32security.SECURITY_ATTRIBUTES()
-PIPE_ATTRS_INHERITABLE.bInheritHandle = 1
-
-from zope.interface import implements
-from twisted.internet.interfaces import IProcessTransport, IConsumer, IProducer
-
-from twisted.python.win32 import quoteArguments
-
-from twisted.internet import error
-from twisted.python import failure
-
-from twisted.internet import _pollingfile
-
-def debug(msg):
- import sys
- print msg
- sys.stdout.flush()
-
-class _Reaper(_pollingfile._PollableResource):
-
- def __init__(self, proc):
- self.proc = proc
-
- def checkWork(self):
- if win32event.WaitForSingleObject(self.proc.hProcess, 0) != win32event.WAIT_OBJECT_0:
- return 0
- exitCode = win32process.GetExitCodeProcess(self.proc.hProcess)
- self.deactivate()
- self.proc.processEnded(exitCode)
- return 0
-
-
-def _findShebang(filename):
- """
- Look for a #! line, and return the value following the #! if one exists, or
- None if this file is not a script.
-
- I don't know if there are any conventions for quoting in Windows shebang
- lines, so this doesn't support any; therefore, you may not pass any
- arguments to scripts invoked as filters. That's probably wrong, so if
- somebody knows more about the cultural expectations on Windows, please feel
- free to fix.
-
- This shebang line support was added in support of the CGI tests;
- appropriately enough, I determined that shebang lines are culturally
- accepted in the Windows world through this page:
-
- http://www.cgi101.com/learn/connect/winxp.html
-
- @param filename: str representing a filename
-
- @return: a str representing another filename.
- """
- f = file(filename, 'ru')
- if f.read(2) == '#!':
- exe = f.readline(1024).strip('\n')
- return exe
-
-def _invalidWin32App(pywinerr):
- """
- Determine if a pywintypes.error is telling us that the given process is
- 'not a valid win32 application', i.e. not a PE format executable.
-
- @param pywinerr: a pywintypes.error instance raised by CreateProcess
-
- @return: a boolean
- """
-
- # Let's do this better in the future, but I have no idea what this error
- # is; MSDN doesn't mention it, and there is no symbolic constant in
- # win32process module that represents 193.
-
- return pywinerr.args[0] == 193
-
-class Process(_pollingfile._PollingTimer):
- """A process that integrates with the Twisted event loop.
-
- If your subprocess is a python program, you need to:
-
- - Run python.exe with the '-u' command line option - this turns on
- unbuffered I/O. Buffering stdout/err/in can cause problems, see e.g.
- http://support.microsoft.com/default.aspx?scid=kb;EN-US;q1903
-
- - If you don't want Windows messing with data passed over
- stdin/out/err, set the pipes to be in binary mode::
-
- import os, sys, mscvrt
- msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
- msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
- msvcrt.setmode(sys.stderr.fileno(), os.O_BINARY)
-
- """
- implements(IProcessTransport, IConsumer, IProducer)
-
- buffer = ''
- pid = None
-
- def __init__(self, reactor, protocol, command, args, environment, path):
- _pollingfile._PollingTimer.__init__(self, reactor)
- self.protocol = protocol
-
- # security attributes for pipes
- sAttrs = win32security.SECURITY_ATTRIBUTES()
- sAttrs.bInheritHandle = 1
-
- # create the pipes which will connect to the secondary process
- self.hStdoutR, hStdoutW = win32pipe.CreatePipe(sAttrs, 0)
- self.hStderrR, hStderrW = win32pipe.CreatePipe(sAttrs, 0)
- hStdinR, self.hStdinW = win32pipe.CreatePipe(sAttrs, 0)
-
- win32pipe.SetNamedPipeHandleState(self.hStdinW,
- win32pipe.PIPE_NOWAIT,
- None,
- None)
-
- # set the info structure for the new process.
- StartupInfo = win32process.STARTUPINFO()
- StartupInfo.hStdOutput = hStdoutW
- StartupInfo.hStdError = hStderrW
- StartupInfo.hStdInput = hStdinR
- StartupInfo.dwFlags = win32process.STARTF_USESTDHANDLES
-
- # Create new handles whose inheritance property is false
- currentPid = win32api.GetCurrentProcess()
-
- tmp = win32api.DuplicateHandle(currentPid, self.hStdoutR, currentPid, 0, 0,
- win32con.DUPLICATE_SAME_ACCESS)
- win32file.CloseHandle(self.hStdoutR)
- self.hStdoutR = tmp
-
- tmp = win32api.DuplicateHandle(currentPid, self.hStderrR, currentPid, 0, 0,
- win32con.DUPLICATE_SAME_ACCESS)
- win32file.CloseHandle(self.hStderrR)
- self.hStderrR = tmp
-
- tmp = win32api.DuplicateHandle(currentPid, self.hStdinW, currentPid, 0, 0,
- win32con.DUPLICATE_SAME_ACCESS)
- win32file.CloseHandle(self.hStdinW)
- self.hStdinW = tmp
-
- # Add the specified environment to the current environment - this is
- # necessary because certain operations are only supported on Windows
- # if certain environment variables are present.
-
- env = os.environ.copy()
- env.update(environment or {})
-
- cmdline = quoteArguments(args)
- # TODO: error detection here.
- def doCreate():
- self.hProcess, self.hThread, self.pid, dwTid = win32process.CreateProcess(
- command, cmdline, None, None, 1, 0, env, path, StartupInfo)
- try:
- doCreate()
- except pywintypes.error, pwte:
- if not _invalidWin32App(pwte):
- # This behavior isn't _really_ documented, but let's make it
- # consistent with the behavior that is documented.
- raise OSError(pwte)
- else:
- # look for a shebang line. Insert the original 'command'
- # (actually a script) into the new arguments list.
- sheb = _findShebang(command)
- if sheb is None:
- raise OSError(
- "%r is neither a Windows executable, "
- "nor a script with a shebang line" % command)
- else:
- args = list(args)
- args.insert(0, command)
- cmdline = quoteArguments(args)
- origcmd = command
- command = sheb
- try:
- # Let's try again.
- doCreate()
- except pywintypes.error, pwte2:
- # d'oh, failed again!
- if _invalidWin32App(pwte2):
- raise OSError(
- "%r has an invalid shebang line: "
- "%r is not a valid executable" % (
- origcmd, sheb))
- raise OSError(pwte2)
-
- win32file.CloseHandle(self.hThread)
-
- # close handles which only the child will use
- win32file.CloseHandle(hStderrW)
- win32file.CloseHandle(hStdoutW)
- win32file.CloseHandle(hStdinR)
-
- self.closed = 0
- self.closedNotifies = 0
-
- # set up everything
- self.stdout = _pollingfile._PollableReadPipe(
- self.hStdoutR,
- lambda data: self.protocol.childDataReceived(1, data),
- self.outConnectionLost)
-
- self.stderr = _pollingfile._PollableReadPipe(
- self.hStderrR,
- lambda data: self.protocol.childDataReceived(2, data),
- self.errConnectionLost)
-
- self.stdin = _pollingfile._PollableWritePipe(
- self.hStdinW, self.inConnectionLost)
-
- for pipewatcher in self.stdout, self.stderr, self.stdin:
- self._addPollableResource(pipewatcher)
-
-
- # notify protocol
- self.protocol.makeConnection(self)
-
- # (maybe?) a good idea in win32er, otherwise not
- # self.reactor.addEvent(self.hProcess, self, 'inConnectionLost')
-
-
- def signalProcess(self, signalID):
- if self.pid is None:
- raise error.ProcessExitedAlready()
- if signalID in ("INT", "TERM", "KILL"):
- win32process.TerminateProcess(self.hProcess, 1)
-
-
- def processEnded(self, status):
- """
- This is called when the child terminates.
- """
- self.pid = None
- if status == 0:
- err = error.ProcessDone(status)
- else:
- err = error.ProcessTerminated(status)
- self.protocol.processEnded(failure.Failure(err))
-
-
- def write(self, data):
- """Write data to the process' stdin."""
- self.stdin.write(data)
-
- def writeSequence(self, seq):
- """Write data to the process' stdin."""
- self.stdin.writeSequence(seq)
-
- def closeChildFD(self, fd):
- if fd == 0:
- self.closeStdin()
- elif fd == 1:
- self.closeStdout()
- elif fd == 2:
- self.closeStderr()
- else:
- raise NotImplementedError("Only standard-IO file descriptors available on win32")
-
- def closeStdin(self):
- """Close the process' stdin.
- """
- self.stdin.close()
-
- def closeStderr(self):
- self.stderr.close()
-
- def closeStdout(self):
- self.stdout.close()
-
- def loseConnection(self):
- """Close the process' stdout, in and err."""
- self.closeStdin()
- self.closeStdout()
- self.closeStderr()
-
- def outConnectionLost(self):
- self.protocol.childConnectionLost(1)
- self.connectionLostNotify()
-
- def errConnectionLost(self):
- self.protocol.childConnectionLost(2)
- self.connectionLostNotify()
-
- def inConnectionLost(self):
- self.protocol.childConnectionLost(0)
- self.connectionLostNotify()
-
- def connectionLostNotify(self):
- """Will be called 3 times, by stdout/err threads and process handle."""
- self.closedNotifies = self.closedNotifies + 1
- if self.closedNotifies == 3:
- self.closed = 1
- self._addPollableResource(_Reaper(self))
-
- # IConsumer
- def registerProducer(self, producer, streaming):
- self.stdin.registerProducer(producer, streaming)
-
- def unregisterProducer(self):
- self.stdin.unregisterProducer()
-
- # IProducer
- def pauseProducing(self):
- self._pause()
-
- def resumeProducing(self):
- self._unpause()
-
- def stopProducing(self):
- self.loseConnection()
-
-
- def __repr__(self):
- """
- Return a string representation of the process.
- """
- return "<%s pid=%s>" % (self.__class__.__name__, self.pid)
diff --git a/tools/buildbot/pylibs/twisted/internet/_javaserialport.py b/tools/buildbot/pylibs/twisted/internet/_javaserialport.py
deleted file mode 100644
index ee84695..0000000
--- a/tools/buildbot/pylibs/twisted/internet/_javaserialport.py
+++ /dev/null
@@ -1,78 +0,0 @@
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-Serial Port Protocol
-"""
-
-# system imports
-import os
-
-# dependent on pyserial ( http://pyserial.sf.net/ )
-# only tested w/ 1.18 (5 Dec 2002)
-import serial
-from serial import PARITY_NONE, PARITY_EVEN, PARITY_ODD
-from serial import STOPBITS_ONE, STOPBITS_TWO
-from serial import FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS
-from serialport import BaseSerialPort
-
-# twisted imports
-from twisted.internet import abstract, javareactor, main
-from twisted.python import log
-
-class SerialPort(BaseSerialPort, javareactor.JConnection):
- """A select()able serial device, acting as a transport."""
- connected = 1
-
- def __init__(self, protocol, deviceNameOrPortNumber, reactor,
- baudrate = 9600, bytesize = EIGHTBITS, parity = PARITY_NONE,
- stopbits = STOPBITS_ONE, timeout = 3, xonxoff = 0, rtscts = 0):
- # do NOT use timeout = 0 !!
- self._serial = serial.Serial(deviceNameOrPortNumber, baudrate = baudrate, bytesize = bytesize, parity = parity, stopbits = stopbits, timeout = timeout, xonxoff = xonxoff, rtscts = rtscts)
- javareactor.JConnection.__init__(self, self._serial.sPort, protocol, None)
- self.flushInput()
- self.flushOutput()
-
- self.reactor = reactor
- self.protocol = protocol
- self.protocol.makeConnection(self)
- wb = javareactor.WriteBlocker(self, reactor.q)
- wb.start()
- self.writeBlocker = wb
- javareactor.ReadBlocker(self, reactor.q).start()
-
- def writeSomeData(self, data):
- try:
- self._serial.write(data)
- return len(data)
- # should have something better here
- except Exception, e:
- return main.CONNECTION_LOST
-
- def doRead(self):
- readBytes = ''
- try:
- readBytes = self._serial.read(min(8192, self.inWaiting()))
- except Exception, e:
- return main.CONNECTION_LOST
- if not readBytes:
- return main.CONNECTION_LOST
- self.protocol.dataReceived(readBytes)
-
- def connectionLost(self, reason):
- self._serial.close()
- self.protocol.connectionLost(reason)
- abstract.FileDescriptor.connectionLost(self, reason)
-
- def getHost(self):
- raise NotImplementedError
-
- def getPeer(self):
- raise NotImplementedError
-
- def getTcpNoDelay(self):
- raise NotImplementedError
-
- def setTcpNoDelay(self, enabled):
- raise NotImplementedError
diff --git a/tools/buildbot/pylibs/twisted/internet/_pollingfile.py b/tools/buildbot/pylibs/twisted/internet/_pollingfile.py
deleted file mode 100644
index cdf55ef..0000000
--- a/tools/buildbot/pylibs/twisted/internet/_pollingfile.py
+++ /dev/null
@@ -1,270 +0,0 @@
-# -*- test-case-name: twisted.web2.test -*-
-"""
-
-Implements a simple polling interface for file descriptors that don't work with
-select() - this is pretty much only useful on Windows.
-
-"""
-
-from zope.interface import implements
-
-from twisted.internet.interfaces import IConsumer, IPushProducer
-
-MIN_TIMEOUT = 0.000000001
-MAX_TIMEOUT = 0.1
-
-class _PollableResource:
- active = True
-
- def activate(self):
- self.active = True
-
- def deactivate(self):
- self.active = False
-
-class _PollingTimer:
- # Everything is private here because it is really an implementation detail.
-
- def __init__(self, reactor):
- self.reactor = reactor
- self._resources = []
- self._pollTimer = None
- self._currentTimeout = MAX_TIMEOUT
- self._paused = False
-
- def _addPollableResource(self, res):
- self._resources.append(res)
- self._checkPollingState()
-
- def _checkPollingState(self):
- for resource in self._resources:
- if resource.active:
- self._startPolling()
- break
- else:
- self._stopPolling()
-
- def _startPolling(self):
- if self._pollTimer is None:
- self._pollTimer = self._reschedule()
-
- def _stopPolling(self):
- if self._pollTimer is not None:
- self._pollTimer.cancel()
- self._pollTimer = None
-
- def _pause(self):
- self._paused = True
-
- def _unpause(self):
- self._paused = False
- self._checkPollingState()
-
- def _reschedule(self):
- if not self._paused:
- return self.reactor.callLater(self._currentTimeout, self._pollEvent)
-
- def _pollEvent(self):
- workUnits = 0.
- anyActive = []
- for resource in self._resources:
- if resource.active:
- workUnits += resource.checkWork()
- # Check AFTER work has been done
- if resource.active:
- anyActive.append(resource)
-
- newTimeout = self._currentTimeout
- if workUnits:
- newTimeout = self._currentTimeout / (workUnits + 1.)
- if newTimeout < MIN_TIMEOUT:
- newTimeout = MIN_TIMEOUT
- else:
- newTimeout = self._currentTimeout * 2.
- if newTimeout > MAX_TIMEOUT:
- newTimeout = MAX_TIMEOUT
- self._currentTimeout = newTimeout
- if anyActive:
- self._pollTimer = self._reschedule()
-
-
-# If we ever (let's hope not) need the above functionality on UNIX, this could
-# be factored into a different module.
-
-import win32pipe
-import win32file
-import win32api
-import pywintypes
-
-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()
-
-
-FULL_BUFFER_SIZE = 64 * 1024
-
-class _PollableWritePipe(_PollableResource):
-
- implements(IConsumer)
-
- def __init__(self, writePipe, lostCallback):
- self.disconnecting = False
- self.producer = None
- self.producerPaused = 0
- self.streamingProducer = 0
- self.outQueue = []
- self.writePipe = writePipe
- self.lostCallback = lostCallback
- try:
- win32pipe.SetNamedPipeHandleState(writePipe,
- win32pipe.PIPE_NOWAIT,
- None,
- None)
- except pywintypes.error:
- # Maybe it's an invalid handle. Who knows.
- pass
-
- def close(self):
- self.disconnecting = True
-
- def bufferFull(self):
- if self.producer is not None:
- self.producerPaused = 1
- self.producer.pauseProducing()
-
- def bufferEmpty(self):
- if self.producer is not None and ((not self.streamingProducer) or
- self.producerPaused):
- self.producer.producerPaused = 0
- self.producer.resumeProducing()
- return True
- return False
-
- # almost-but-not-quite-exact copy-paste from abstract.FileDescriptor... ugh
-
- def registerProducer(self, producer, streaming):
- """Register to receive data from a producer.
-
- This sets this selectable to be a consumer for a producer. When this
- selectable runs out of data on a write() call, it will ask the producer
- to resumeProducing(). A producer should implement the IProducer
- interface.
-
- FileDescriptor provides some infrastructure for producer methods.
- """
- if self.producer is not None:
- raise RuntimeError("Cannot register producer %s, because producer %s was never unregistered." % (producer, self.producer))
- if not self.active:
- producer.stopProducing()
- else:
- self.producer = producer
- self.streamingProducer = streaming
- if not streaming:
- producer.resumeProducing()
-
- def unregisterProducer(self):
- """Stop consuming data from a producer, without disconnecting.
- """
- self.producer = None
-
- def writeConnectionLost(self):
- self.deactivate()
- try:
- win32api.CloseHandle(self.writePipe)
- except pywintypes.error:
- # OMG what
- pass
- self.lostCallback()
-
- def writeSequence(self, seq):
- self.outQueue.extend(seq)
-
- def write(self, data):
- if self.disconnecting:
- return
- self.outQueue.append(data)
- if sum(map(len, self.outQueue)) > FULL_BUFFER_SIZE:
- self.bufferFull()
-
- def checkWork(self):
- numBytesWritten = 0
- if not self.outQueue:
- if self.disconnecting:
- self.writeConnectionLost()
- return 0
- try:
- win32file.WriteFile(self.writePipe, '', None)
- except pywintypes.error:
- self.writeConnectionLost()
- return numBytesWritten
- while self.outQueue:
- data = self.outQueue.pop(0)
- errCode = 0
- try:
- errCode, nBytesWritten = win32file.WriteFile(self.writePipe,
- data, None)
- except win32api.error:
- self.writeConnectionLost()
- break
- else:
- # assert not errCode, "wtf an error code???"
- numBytesWritten += nBytesWritten
- if len(data) > nBytesWritten:
- self.outQueue.insert(0, data[nBytesWritten:])
- break
- else:
- resumed = self.bufferEmpty()
- if not resumed and self.disconnecting:
- self.writeConnectionLost()
- return numBytesWritten
-
-
diff --git a/tools/buildbot/pylibs/twisted/internet/_posixserialport.py b/tools/buildbot/pylibs/twisted/internet/_posixserialport.py
deleted file mode 100644
index c94ecee..0000000
--- a/tools/buildbot/pylibs/twisted/internet/_posixserialport.py
+++ /dev/null
@@ -1,60 +0,0 @@
-# Copyright (c) 2001-2007 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-Serial Port Protocol
-"""
-
-# system imports
-import os, errno
-
-# dependent on pyserial ( http://pyserial.sf.net/ )
-# only tested w/ 1.18 (5 Dec 2002)
-import serial
-from serial import PARITY_NONE, PARITY_EVEN, PARITY_ODD
-from serial import STOPBITS_ONE, STOPBITS_TWO
-from serial import FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS
-
-from serialport import BaseSerialPort
-
-# twisted imports
-from twisted.internet import abstract, fdesc, main
-
-class SerialPort(BaseSerialPort, abstract.FileDescriptor):
- """
- A select()able serial device, acting as a transport.
- """
-
- connected = 1
-
- def __init__(self, protocol, deviceNameOrPortNumber, reactor,
- baudrate = 9600, bytesize = EIGHTBITS, parity = PARITY_NONE,
- stopbits = STOPBITS_ONE, timeout = 0, xonxoff = 0, rtscts = 0):
- abstract.FileDescriptor.__init__(self, reactor)
- self._serial = serial.Serial(deviceNameOrPortNumber, baudrate = baudrate, bytesize = bytesize, parity = parity, stopbits = stopbits, timeout = timeout, xonxoff = xonxoff, rtscts = rtscts)
- self.reactor = reactor
- self.flushInput()
- self.flushOutput()
- self.protocol = protocol
- self.protocol.makeConnection(self)
- self.startReading()
-
- def fileno(self):
- return self._serial.fd
-
- def writeSomeData(self, data):
- """
- Write some data to the serial device.
- """
- return fdesc.writeToFD(self.fileno(), data)
-
- def doRead(self):
- """
- Some data's readable from serial device.
- """
- return fdesc.readFromFD(self.fileno(), self.protocol.dataReceived)
-
- def connectionLost(self, reason):
- abstract.FileDescriptor.connectionLost(self, reason)
- self._serial.close()
diff --git a/tools/buildbot/pylibs/twisted/internet/_posixstdio.py b/tools/buildbot/pylibs/twisted/internet/_posixstdio.py
deleted file mode 100644
index 56eb141..0000000
--- a/tools/buildbot/pylibs/twisted/internet/_posixstdio.py
+++ /dev/null
@@ -1,171 +0,0 @@
-# -*- test-case-name: twisted.test.test_stdio -*-
-
-"""Standard input/out/err support.
-
-Future Plans::
-
- support for stderr, perhaps
- Rewrite to use the reactor instead of an ad-hoc mechanism for connecting
- protocols to transport.
-
-Maintainer: U{James Y Knight <mailto:foom@fuhm.net>}
-"""
-
-import warnings
-from zope.interface import implements
-
-from twisted.internet import process, error, interfaces
-from twisted.python import log, failure
-
-
-class PipeAddress(object):
- implements(interfaces.IAddress)
-
-
-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 twisted.internet import reactor
- self.protocol = proto
-
- self._reader=process.ProcessReader(reactor, self, 'read', stdin)
- self._reader.startReading()
- self._writer=process.ProcessWriter(reactor, self, 'write', stdout)
- self._writer.startReading()
- self.protocol.makeConnection(self)
-
- # ITransport
- def loseWriteConnection(self):
- if self._writer is not None:
- self._writer.loseConnection()
-
- def write(self, data):
- if self._writer is not None:
- self._writer.write(data)
-
- def writeSequence(self, data):
- if self._writer is not None:
- self._writer.writeSequence(data)
-
- def loseConnection(self):
- self.disconnecting = True
-
- if self._writer is not None:
- self._writer.loseConnection()
- if self._reader is not None:
- # Don't loseConnection, because we don't want to SIGPIPE it.
- self._reader.stopReading()
-
- def getPeer(self):
- return PipeAddress()
-
- def getHost(self):
- return PipeAddress()
-
-
- # Callbacks from process.ProcessReader/ProcessWriter
- def childDataReceived(self, fd, data):
- self.protocol.dataReceived(data)
-
- def childConnectionLost(self, fd, reason):
- if self.disconnected:
- return
-
- if reason.value.__class__ == error.ConnectionDone:
- # Normal close
- if fd == 'read':
- self._readConnectionLost(reason)
- else:
- self._writeConnectionLost(reason)
- else:
- self.connectionLost(reason)
-
- def connectionLost(self, reason):
- self.disconnected = True
-
- # Make sure to cleanup the other half
- _reader = self._reader
- _writer = self._writer
- protocol = self.protocol
- self._reader = self._writer = None
- self.protocol = None
-
- if _writer is not None and not _writer.disconnected:
- _writer.connectionLost(reason)
-
- if _reader is not None and not _reader.disconnected:
- _reader.connectionLost(reason)
-
- try:
- protocol.connectionLost(reason)
- except:
- log.err()
-
- def _writeConnectionLost(self, reason):
- self._writer=None
- if self.disconnecting:
- self.connectionLost(reason)
- return
-
- p = interfaces.IHalfCloseableProtocol(self.protocol, None)
- if p:
- try:
- p.writeConnectionLost()
- except:
- log.err()
- self.connectionLost(failure.Failure())
-
- def _readConnectionLost(self, reason):
- self._reader=None
- p = interfaces.IHalfCloseableProtocol(self.protocol, None)
- if p:
- try:
- p.readConnectionLost()
- except:
- log.err()
- self.connectionLost(failure.Failure())
- else:
- self.connectionLost(reason)
-
- # IConsumer
- def registerProducer(self, producer, streaming):
- if self._writer is None:
- producer.stopProducing()
- else:
- self._writer.registerProducer(producer, streaming)
-
- def unregisterProducer(self):
- if self._writer is not None:
- self._writer.unregisterProducer()
-
- # IProducer
- def stopProducing(self):
- self.loseConnection()
-
- def pauseProducing(self):
- if self._reader is not None:
- self._reader.pauseProducing()
-
- def resumeProducing(self):
- if self._reader is not None:
- self._reader.resumeProducing()
-
- # Stupid compatibility:
- def closeStdin(self):
- """Compatibility only, don't use. Same as loseWriteConnection."""
- warnings.warn("This function is deprecated, use loseWriteConnection instead.",
- category=DeprecationWarning, stacklevel=2)
- self.loseWriteConnection()
-
- def stopReading(self):
- """Compatibility only, don't use. Call pauseProducing."""
- self.pauseProducing()
-
- def startReading(self):
- """Compatibility only, don't use. Call resumeProducing."""
- self.resumeProducing()
diff --git a/tools/buildbot/pylibs/twisted/internet/_sslverify.py b/tools/buildbot/pylibs/twisted/internet/_sslverify.py
deleted file mode 100644
index 32c4173..0000000
--- a/tools/buildbot/pylibs/twisted/internet/_sslverify.py
+++ /dev/null
@@ -1,948 +0,0 @@
-# -*- test-case-name: twisted.test.test_sslverify -*-
-# Copyright 2005 Divmod, Inc. See LICENSE file for details
-
-import itertools, md5
-from OpenSSL import SSL, crypto
-
-from twisted.python import reflect, util
-from twisted.internet.defer import Deferred
-from twisted.internet.error import VerifyError, CertificateError
-
-# Private - shared between all OpenSSLCertificateOptions, counts up to provide
-# a unique session id for each context
-_sessionCounter = itertools.count().next
-
-class _SSLApplicationData(object):
- def __init__(self):
- self.problems = []
-
-class OpenSSLVerifyError(VerifyError):
-
- _errorCodes = {0: ('X509_V_OK',
- 'ok',
- 'the operation was successful. >'),
-
- 2: ('X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT',
- 'unable to get issuer certificate',
- "The issuer certificate could not be found. This "
- "occurs if the issuer certificate of an untrusted "
- "certificate cannot be found."),
-
- 3: ('X509_V_ERR_UNABLE_TO_GET_CRL',
- 'unable to get certificate CRL',
- "The CRL of a certificate could not be found. "
- "Unused."),
-
- 4: ('X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE',
- "unable to decrypt certificate's signature",
- "The certificate signature could not be decrypted. "
- "This means that the actual signature value could not "
- "be determined rather than it not matching the "
- "expected value, this is only meaningful for RSA "
- "keys."),
-
- 5: ('X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE',
- "unable to decrypt CRL's signature",
- "The CRL signature could not be decrypted. This "
- "means that the actual signature value could not be "
- "determined rather than it not matching the expected "
- "value. Unused."),
-
- 6: ('X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY',
- 'unable to decode issuer',
- "Public key the public key in the certificate "
- "SubjectPublicKeyInfo could not be read."),
-
- 7: ('X509_V_ERR_CERT_SIGNATURE_FAILURE',
- 'certificate signature failure',
- 'The signature of the certificate is invalid.'),
-
- 8: ('X509_V_ERR_CRL_SIGNATURE_FAILURE',
- 'CRL signature failure',
- 'The signature of the certificate is invalid. Unused.'),
-
- 9: ('X509_V_ERR_CERT_NOT_YET_VALID',
- 'certificate is not yet valid',
- "The certificate is not yet valid. The notBefore "
- "date is after the current time."),
-
- 10: ('X509_V_ERR_CERT_HAS_EXPIRED',
- 'certificate has expired',
- "The certificate has expired. The notAfter date "
- "is before the current time."),
-
- 11: ('X509_V_ERR_CRL_NOT_YET_VALID',
- 'CRL is not yet valid',
- 'The CRL is not yet valid. Unused.'),
-
- 12: ('X509_V_ERR_CRL_HAS_EXPIRED',
- 'CRL has expired',
- 'The CRL has expired. Unused.'),
-
- 13: ('X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD',
- "format error in certificate's notBefore field",
- "The certificate's notBefore field contains an "
- "invalid time."),
-
- 14: ('X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD',
- "format error in certificate's notAfter field.",
- "The certificate's notAfter field contains an "
- "invalid time."),
-
- 15: ('X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD',
- "format error in CRL's lastUpdate field",
- "The CRL lastUpdate field contains an invalid "
- "time. Unused."),
-
- 16: ('X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD',
- "format error in CRL's nextUpdate field",
- "The CRL nextUpdate field contains an invalid "
- "time. Unused."),
-
- 17: ('X509_V_ERR_OUT_OF_MEM',
- 'out of memory',
- 'An error occurred trying to allocate memory. '
- 'This should never happen.'),
-
- 18: ('X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT',
- 'self signed certificate',
- 'The passed certificate is self signed and the same '
- 'certificate cannot be found in the list of trusted '
- 'certificates.'),
-
- 19: ('X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN',
- 'self signed certificate in certificate chain',
- 'The certificate chain could be built up using the '
- 'untrusted certificates but the root could not be '
- 'found locally.'),
-
- 20: ('X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY',
- 'unable to get local issuer certificate',
- 'The issuer certificate of a locally looked up '
- 'certificate could not be found. This normally '
- 'means the list of trusted certificates is not '
- 'complete.'),
-
- 21: ('X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE',
- 'unable to verify the first certificate',
- 'No signatures could be verified because the chain '
- 'contains only one certificate and it is not self '
- 'signed.'),
-
- 22: ('X509_V_ERR_CERT_CHAIN_TOO_LONG',
- 'certificate chain too long',
- 'The certificate chain length is greater than the '
- 'supplied maximum depth. Unused.'),
-
- 23: ('X509_V_ERR_CERT_REVOKED',
- 'certificate revoked',
- 'The certificate has been revoked. Unused.'),
-
- 24: ('X509_V_ERR_INVALID_CA',
- 'invalid CA certificate',
- 'A CA certificate is invalid. Either it is not a CA '
- 'or its extensions are not consistent with the '
- 'supplied purpose.'),
-
- 25: ('X509_V_ERR_PATH_LENGTH_EXCEEDED',
- 'path length constraint exceeded',
- 'The basicConstraints pathlength parameter has been '
- 'exceeded.'),
-
- 26: ('X509_V_ERR_INVALID_PURPOSE',
- 'unsupported certificate purpose',
- 'The supplied certificate cannot be used for the '
- 'specified purpose.'),
-
- 27: ('X509_V_ERR_CERT_UNTRUSTED',
- 'certificate not trusted',
- 'The root CA is not marked as trusted for the '
- 'specified purpose.'),
-
- 28: ('X509_V_ERR_CERT_REJECTED',
- 'certificate rejected',
- 'The root CA is marked to reject the specified '
- 'purpose.'),
-
- 29: ('X509_V_ERR_SUBJECT_ISSUER_MISMATCH',
- 'subject issuer mismatch',
- 'The current candidate issuer certificate was '
- 'rejected because its subject name did not match '
- 'the issuer name of the current certificate. Only '
- 'displayed when the issuer_checks option is set.'),
-
- 30: ('X509_V_ERR_AKID_SKID_MISMATCH',
- 'authority and subject key identifier mismatch',
- 'The current candidate issuer certificate was '
- 'rejected because its subject key identifier was '
- 'present and did not match the authority key '
- 'identifier current certificate. Only displayed '
- 'when the issuer_checks option is set.'),
-
- 31: ('X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH',
- 'authority and issuer serial number mismatch',
- 'The current candidate issuer certificate was '
- 'rejected because its issuer name and serial '
- 'number was present and did not match the '
- 'authority key identifier of the current '
- 'certificate. Only displayed when the issuer_checks '
- 'option is set.'),
-
- 32: ('X509_V_ERR_KEYUSAGE_NO_CERTSIGN',
- 'key usage does not include certificate',
- 'Signing the current candidate issuer certificate was '
- 'rejected because its keyUsage extension does not '
- 'permit certificate signing.'),
-
- 50: ('X509_V_ERR_APPLICATION_VERIFICATION',
- 'application verification failure',
- 'an application specific error. Unused.')}
-
-
- def __init__(self, cert, errno, depth):
- VerifyError.__init__(self, cert, errno, depth)
- self.cert = cert
- self.errno = errno
- self.depth = depth
-
- def __repr__(self):
- x = self._errorCodes.get(self.errno)
- if x is not None:
- name, short, long = x
- return 'Peer Certificate Verification Failed: %s (error code: %d)' % (
- long, self.errno
- )
- return "Peer Certificate Verification Failed for Unknown Reason"
-
- __str__ = __repr__
-
-
-_x509names = {
- 'CN': 'commonName',
- 'commonName': 'commonName',
-
- 'O': 'organizationName',
- 'organizationName': 'organizationName',
-
- 'OU': 'organizationalUnitName',
- 'organizationalUnitName': 'organizationalUnitName',
-
- 'L': 'localityName',
- 'localityName': 'localityName',
-
- 'ST': 'stateOrProvinceName',
- 'stateOrProvinceName': 'stateOrProvinceName',
-
- 'C': 'countryName',
- 'countryName': 'countryName',
-
- 'emailAddress': 'emailAddress'}
-
-
-class DistinguishedName(dict):
- """
- Identify and describe an entity.
-
- Distinguished names are used to provide a minimal amount of identifying
- information about a certificate issuer or subject. They are commonly
- created with one or more of the following fields::
-
- commonName (CN)
- organizationName (O)
- organizationalUnitName (OU)
- localityName (L)
- stateOrProvinceName (ST)
- countryName (C)
- emailAddress
- """
- __slots__ = ()
-
- def __init__(self, **kw):
- for k, v in kw.iteritems():
- setattr(self, k, v)
-
-
- def _copyFrom(self, x509name):
- d = {}
- for name in _x509names:
- value = getattr(x509name, name, None)
- if value is not None:
- setattr(self, name, value)
-
-
- def _copyInto(self, x509name):
- for k, v in self.iteritems():
- setattr(x509name, k, v)
-
-
- def __repr__(self):
- return '<DN %s>' % (dict.__repr__(self)[1:-1])
-
-
- def __getattr__(self, attr):
- try:
- return self[_x509names[attr]]
- except KeyError:
- raise AttributeError(attr)
-
-
- def __setattr__(self, attr, value):
- assert type(attr) is str
- if not attr in _x509names:
- raise AttributeError("%s is not a valid OpenSSL X509 name field" % (attr,))
- realAttr = _x509names[attr]
- value = value.encode('ascii')
- assert type(value) is str
- self[realAttr] = value
-
-
- def inspect(self):
- """
- Return a multi-line, human-readable representation of this DN.
- """
- l = []
- lablen = 0
- def uniqueValues(mapping):
- return dict.fromkeys(mapping.itervalues()).keys()
- for k in uniqueValues(_x509names):
- label = util.nameToLabel(k)
- lablen = max(len(label), lablen)
- v = getattr(self, k, None)
- if v is not None:
- l.append((label, v))
- lablen += 2
- for n, (label, attr) in enumerate(l):
- l[n] = (label.rjust(lablen)+': '+ attr)
- return '\n'.join(l)
-
-DN = DistinguishedName
-
-
-class CertBase:
- def __init__(self, original):
- self.original = original
-
- def _copyName(self, suffix):
- dn = DistinguishedName()
- dn._copyFrom(getattr(self.original, 'get_'+suffix)())
- return dn
-
- def getSubject(self):
- """
- Retrieve the subject of this certificate.
-
- @rtype: L{DistinguishedName}
- @return: A copy of the subject of this certificate.
- """
- return self._copyName('subject')
-
-
-
-def problemsFromTransport(tpt):
- """
- Retrieve the SSL errors associated with the given transport.
-
- @type tpt: L{ISystemHandle} provider wrapper around an SSL connection.
- @rtype: C{list} of L{OpenSSLVerifyError}.
- """
- return tpt.getHandle().get_context().get_app_data().problems
-
-
-def _handleattrhelper(Class, transport, methodName):
- """
- (private) Helper for L{Certificate.peerFromTransport} and
- L{Certificate.hostFromTransport} which checks for incompatible handle types
- and null certificates and raises the appropriate exception or returns the
- appropriate certificate object.
- """
- method = getattr(transport.getHandle(),
- "get_%s_certificate" % (methodName,), None)
- if method is None:
- raise CertificateError(
- "non-TLS transport %r did not have %s certificate" % (transport, methodName))
- cert = method()
- if cert is None:
- raise CertificateError(
- "TLS transport %r did not have %s certificate" % (transport, methodName))
- return Class(cert)
-
-
-class Certificate(CertBase):
- """
- An x509 certificate.
- """
- def __repr__(self):
- return '<%s Subject=%s Issuer=%s>' % (self.__class__.__name__,
- self.getSubject().commonName,
- self.getIssuer().commonName)
-
- def __eq__(self, other):
- if isinstance(other, Certificate):
- return self.dump() == other.dump()
- return False
-
-
- def __ne__(self, other):
- return not self.__eq__(other)
-
-
- def load(Class, requestData, format=crypto.FILETYPE_ASN1, args=()):
- """
- Load a certificate from an ASN.1- or PEM-format string.
-
- @rtype: C{Class}
- """
- return Class(crypto.load_certificate(format, requestData), *args)
- load = classmethod(load)
- _load = load
-
-
- def dumpPEM(self):
- """
- Dump this certificate to a PEM-format data string.
-
- @rtype: C{str}
- """
- return self.dump(crypto.FILETYPE_PEM)
-
-
- def loadPEM(Class, data):
- """
- Load a certificate from a PEM-format data string.
-
- @rtype: C{Class}
- """
- return Class.load(data, crypto.FILETYPE_PEM)
- loadPEM = classmethod(loadPEM)
-
-
- def peerFromTransport(Class, transport):
- """
- Get the certificate for the remote end of the given transport.
-
- @type: L{ISystemHandle}
- @rtype: C{Class}
-
- @raise: L{CertificateError}, if the given transport does not have a peer
- certificate.
- """
- return _handleattrhelper(Class, transport, 'peer')
- peerFromTransport = classmethod(peerFromTransport)
-
-
- def hostFromTransport(Class, transport):
- """
- Get the certificate for the local end of the given transport.
-
- @param transport: an L{ISystemHandle} provider; the transport we will
-
- @rtype: C{Class}
-
- @raise: L{CertificateError}, if the given transport does not have a host
- certificate.
- """
- return _handleattrhelper(Class, transport, 'host')
- hostFromTransport = classmethod(hostFromTransport)
-
-
- def getPublicKey(self):
- """
- Get the public key for this certificate.
-
- @rtype: L{PublicKey}
- """
- return PublicKey(self.original.get_pubkey())
-
-
- def dump(self, format=crypto.FILETYPE_ASN1):
- return crypto.dump_certificate(format, self.original)
-
-
- def serialNumber(self):
- """
- Retrieve the serial number of this certificate.
-
- @rtype: C{int}
- """
- return self.original.get_serial_number()
-
-
- def digest(self, method='md5'):
- """
- Return a digest hash of this certificate using the specified hash
- algorithm.
-
- @param method: One of C{'md5'} or C{'sha'}.
- @rtype: C{str}
- """
- return self.original.digest(method)
-
-
- def _inspect(self):
- return '\n'.join(['Certificate For Subject:',
- self.getSubject().inspect(),
- '\nIssuer:',
- self.getIssuer().inspect(),
- '\nSerial Number: %d' % self.serialNumber(),
- 'Digest: %s' % self.digest()])
-
-
- def inspect(self):
- """
- Return a multi-line, human-readable representation of this
- Certificate, including information about the subject, issuer, and
- public key.
- """
- return '\n'.join((self._inspect(), self.getPublicKey().inspect()))
-
-
- def getIssuer(self):
- """
- Retrieve the issuer of this certificate.
-
- @rtype: L{DistinguishedName}
- @return: A copy of the issuer of this certificate.
- """
- return self._copyName('issuer')
-
-
- def options(self, *authorities):
- raise NotImplementedError('Possible, but doubtful we need this yet')
-
-
-
-class CertificateRequest(CertBase):
- """
- An x509 certificate request.
-
- Certificate requests are given to certificate authorities to be signed and
- returned resulting in an actual certificate.
- """
- def load(Class, requestData, requestFormat=crypto.FILETYPE_ASN1):
- req = crypto.load_certificate_request(requestFormat, requestData)
- dn = DistinguishedName()
- dn._copyFrom(req.get_subject())
- if not req.verify(req.get_pubkey()):
- raise VerifyError("Can't verify that request for %r is self-signed." % (dn,))
- return Class(req)
- load = classmethod(load)
-
-
- def dump(self, format=crypto.FILETYPE_ASN1):
- return crypto.dump_certificate_request(format, self.original)
-
-
-
-class PrivateCertificate(Certificate):
- """
- An x509 certificate and private key.
- """
- def __repr__(self):
- return Certificate.__repr__(self) + ' with ' + repr(self.privateKey)
-
-
- def _setPrivateKey(self, privateKey):
- if not privateKey.matches(self.getPublicKey()):
- raise VerifyError(
- "Sanity check failed: Your certificate was not properly signed.")
- self.privateKey = privateKey
- return self
-
-
- def newCertificate(self, newCertData, format=crypto.FILETYPE_ASN1):
- """
- Create a new L{PrivateCertificate} from the given certificate data and
- this instance's private key.
- """
- return self.load(newCertData, self.privateKey, format)
-
-
- def load(Class, data, privateKey, format=crypto.FILETYPE_ASN1):
- return Class._load(data, format)._setPrivateKey(privateKey)
- load = classmethod(load)
-
-
- def inspect(self):
- return '\n'.join([Certificate._inspect(self),
- self.privateKey.inspect()])
-
-
- def dumpPEM(self):
- """
- Dump both public and private parts of a private certificate to
- PEM-format data.
- """
- return self.dump(crypto.FILETYPE_PEM) + self.privateKey.dump(crypto.FILETYPE_PEM)
-
-
- def loadPEM(Class, data):
- """
- Load both private and public parts of a private certificate from a
- chunk of PEM-format data.
- """
- return Class.load(data, KeyPair.load(data, crypto.FILETYPE_PEM),
- crypto.FILETYPE_PEM)
- loadPEM = classmethod(loadPEM)
-
-
- def fromCertificateAndKeyPair(Class, certificateInstance, privateKey):
- privcert = Class(certificateInstance.original)
- return privcert._setPrivateKey(privateKey)
- fromCertificateAndKeyPair = classmethod(fromCertificateAndKeyPair)
-
-
- def options(self, *authorities):
- options = dict(privateKey=self.privateKey.original,
- certificate=self.original)
- if authorities:
- options.update(dict(verify=True,
- requireCertificate=True,
- caCerts=[auth.original for auth in authorities]))
- return OpenSSLCertificateOptions(**options)
-
-
- def certificateRequest(self, format=crypto.FILETYPE_ASN1,
- digestAlgorithm='md5'):
- return self.privateKey.certificateRequest(
- self.getSubject(),
- format,
- digestAlgorithm)
-
-
- def signCertificateRequest(self,
- requestData,
- verifyDNCallback,
- serialNumber,
- requestFormat=crypto.FILETYPE_ASN1,
- certificateFormat=crypto.FILETYPE_ASN1):
- issuer = self.getSubject()
- return self.privateKey.signCertificateRequest(
- issuer,
- requestData,
- verifyDNCallback,
- serialNumber,
- requestFormat,
- certificateFormat)
-
-
- def signRequestObject(self, certificateRequest, serialNumber,
- secondsToExpiry=60 * 60 * 24 * 365, # One year
- digestAlgorithm='md5'):
- return self.privateKey.signRequestObject(self.getSubject(),
- certificateRequest,
- serialNumber,
- secondsToExpiry,
- digestAlgorithm)
-
-
-class PublicKey:
- def __init__(self, osslpkey):
- self.original = osslpkey
- req1 = crypto.X509Req()
- req1.set_pubkey(osslpkey)
- self._emptyReq = crypto.dump_certificate_request(crypto.FILETYPE_ASN1, req1)
-
-
- def matches(self, otherKey):
- return self._emptyReq == otherKey._emptyReq
-
-
- # XXX This could be a useful method, but sometimes it triggers a segfault,
- # so we'll steer clear for now.
-# def verifyCertificate(self, certificate):
-# """
-# returns None, or raises a VerifyError exception if the certificate
-# could not be verified.
-# """
-# if not certificate.original.verify(self.original):
-# raise VerifyError("We didn't sign that certificate.")
-
- def __repr__(self):
- return '<%s %s>' % (self.__class__.__name__, self.keyHash())
-
-
- def keyHash(self):
- """
- MD5 hex digest of signature on an empty certificate request with this
- key.
- """
- return md5.md5(self._emptyReq).hexdigest()
-
-
- def inspect(self):
- return 'Public Key with Hash: %s' % (self.keyHash(),)
-
-
-
-class KeyPair(PublicKey):
-
- def load(Class, data, format=crypto.FILETYPE_ASN1):
- return Class(crypto.load_privatekey(format, data))
- load = classmethod(load)
-
-
- def dump(self, format=crypto.FILETYPE_ASN1):
- return crypto.dump_privatekey(format, self.original)
-
-
- def __getstate__(self):
- return self.dump()
-
-
- def __setstate__(self, state):
- self.__init__(crypto.load_privatekey(crypto.FILETYPE_ASN1, state))
-
-
- def inspect(self):
- t = self.original.type()
- if t == crypto.TYPE_RSA:
- ts = 'RSA'
- elif t == crypto.TYPE_DSA:
- ts = 'DSA'
- else:
- ts = '(Unknown Type!)'
- L = (self.original.bits(), ts, self.keyHash())
- return '%s-bit %s Key Pair with Hash: %s' % L
-
-
- def generate(Class, kind=crypto.TYPE_RSA, size=1024):
- pkey = crypto.PKey()
- pkey.generate_key(kind, size)
- return Class(pkey)
-
-
- def newCertificate(self, newCertData, format=crypto.FILETYPE_ASN1):
- return PrivateCertificate.load(newCertData, self, format)
- generate = classmethod(generate)
-
-
- def requestObject(self, distinguishedName, digestAlgorithm='md5'):
- req = crypto.X509Req()
- req.set_pubkey(self.original)
- distinguishedName._copyInto(req.get_subject())
- req.sign(self.original, digestAlgorithm)
- return CertificateRequest(req)
-
-
- def certificateRequest(self, distinguishedName,
- format=crypto.FILETYPE_ASN1,
- digestAlgorithm='md5'):
- """Create a certificate request signed with this key.
-
- @return: a string, formatted according to the 'format' argument.
- """
- return self.requestObject(distinguishedName, digestAlgorithm).dump(format)
-
-
- def signCertificateRequest(self,
- issuerDistinguishedName,
- requestData,
- verifyDNCallback,
- serialNumber,
- requestFormat=crypto.FILETYPE_ASN1,
- certificateFormat=crypto.FILETYPE_ASN1,
- secondsToExpiry=60 * 60 * 24 * 365, # One year
- digestAlgorithm='md5'):
- """
- Given a blob of certificate request data and a certificate authority's
- DistinguishedName, return a blob of signed certificate data.
-
- If verifyDNCallback returns a Deferred, I will return a Deferred which
- fires the data when that Deferred has completed.
- """
- hlreq = CertificateRequest.load(requestData, requestFormat)
-
- dn = hlreq.getSubject()
- vval = verifyDNCallback(dn)
-
- def verified(value):
- if not value:
- raise VerifyError("DN callback %r rejected request DN %r" % (verifyDNCallback, dn))
- return self.signRequestObject(issuerDistinguishedName, hlreq,
- serialNumber, secondsToExpiry, digestAlgorithm).dump(certificateFormat)
-
- if isinstance(vval, Deferred):
- return vval.addCallback(verified)
- else:
- return verified(vval)
-
-
- def signRequestObject(self,
- issuerDistinguishedName,
- requestObject,
- serialNumber,
- secondsToExpiry=60 * 60 * 24 * 365, # One year
- digestAlgorithm='md5'):
- """
- Sign a CertificateRequest instance, returning a Certificate instance.
- """
- req = requestObject.original
- dn = requestObject.getSubject()
- cert = crypto.X509()
- issuerDistinguishedName._copyInto(cert.get_issuer())
- cert.set_subject(req.get_subject())
- cert.set_pubkey(req.get_pubkey())
- cert.gmtime_adj_notBefore(0)
- cert.gmtime_adj_notAfter(secondsToExpiry)
- cert.set_serial_number(serialNumber)
- cert.sign(self.original, digestAlgorithm)
- return Certificate(cert)
-
-
- def selfSignedCert(self, serialNumber, **kw):
- dn = DN(**kw)
- return PrivateCertificate.fromCertificateAndKeyPair(
- self.signRequestObject(dn, self.requestObject(dn), serialNumber),
- self)
-
-
-
-class OpenSSLCertificateOptions(object):
- """
- A factory for SSL context objects for both SSL servers and clients.
- """
-
- _context = None
- # Older versions of PyOpenSSL didn't provide OP_ALL. Fudge it here, just in case.
- _OP_ALL = getattr(SSL, 'OP_ALL', 0x0000FFFF)
-
- method = SSL.TLSv1_METHOD
-
- def __init__(self,
- privateKey=None,
- certificate=None,
- method=None,
- verify=False,
- caCerts=None,
- verifyDepth=9,
- requireCertificate=True,
- verifyOnce=True,
- enableSingleUseKeys=True,
- enableSessions=True,
- fixBrokenPeers=False):
- """
- Create an OpenSSL context SSL connection context factory.
-
- @param privateKey: A PKey object holding the private key.
-
- @param certificate: An X509 object holding the certificate.
-
- @param method: The SSL protocol to use, one of SSLv23_METHOD,
- SSLv2_METHOD, SSLv3_METHOD, TLSv1_METHOD. Defaults to TLSv1_METHOD.
-
- @param verify: If True, verify certificates received from the peer and
- fail the handshake if verification fails. Otherwise, allow anonymous
- sessions and sessions with certificates which fail validation. By
- default this is False.
-
- @param caCerts: List of certificate authority certificates to
- send to the client when requesting a certificate. Only used if verify
- is True, and if verify is True, either this must be specified or
- caCertsFile must be given. Since verify is False by default,
- this is None by default.
-
- @param verifyDepth: Depth in certificate chain down to which to verify.
- If unspecified, use the underlying default (9).
-
- @param requireCertificate: If True, do not allow anonymous sessions.
-
- @param verifyOnce: If True, do not re-verify the certificate
- on session resumption.
-
- @param enableSingleUseKeys: If True, generate a new key whenever
- ephemeral DH parameters are used to prevent small subgroup attacks.
-
- @param enableSessions: If True, set a session ID on each context. This
- allows a shortened handshake to be used when a known client reconnects.
-
- @param fixBrokenPeers: If True, enable various non-spec protocol fixes
- for broken SSL implementations. This should be entirely safe,
- according to the OpenSSL documentation, but YMMV. This option is now
- off by default, because it causes problems with connections between
- peers using OpenSSL 0.9.8a.
- """
-
- assert (privateKey is None) == (certificate is None), "Specify neither or both of privateKey and certificate"
- self.privateKey = privateKey
- self.certificate = certificate
- if method is not None:
- self.method = method
-
- self.verify = verify
- assert ((verify and caCerts) or
- (not verify)), "Specify client CA certificate information if and only if enabling certificate verification"
-
- self.caCerts = caCerts
- self.verifyDepth = verifyDepth
- self.requireCertificate = requireCertificate
- self.verifyOnce = verifyOnce
- self.enableSingleUseKeys = enableSingleUseKeys
- self.enableSessions = enableSessions
- self.fixBrokenPeers = fixBrokenPeers
-
-
- def __getstate__(self):
- d = self.__dict__.copy()
- try:
- del d['_context']
- except KeyError:
- pass
- return d
-
-
- def __setstate__(self, state):
- self.__dict__ = state
-
-
- def getContext(self):
- """Return a SSL.Context object.
- """
- if self._context is None:
- self._context = self._makeContext()
- return self._context
-
-
- def _makeContext(self):
- ctx = SSL.Context(self.method)
- ctx.set_app_data(_SSLApplicationData())
-
- if self.certificate is not None and self.privateKey is not None:
- ctx.use_certificate(self.certificate)
- ctx.use_privatekey(self.privateKey)
- # Sanity check
- ctx.check_privatekey()
-
- verifyFlags = SSL.VERIFY_NONE
- if self.verify:
- verifyFlags = SSL.VERIFY_PEER
- if self.requireCertificate:
- verifyFlags |= SSL.VERIFY_FAIL_IF_NO_PEER_CERT
- if self.verifyOnce:
- verifyFlags |= SSL.VERIFY_CLIENT_ONCE
- if self.caCerts:
- store = ctx.get_cert_store()
- for cert in self.caCerts:
- store.add_cert(cert)
-
- def _trackVerificationProblems(conn,cert,errno,depth,preverify_ok):
- # retcode is the answer OpenSSL's default verifier would have
- # given, had we allowed it to run.
- if not preverify_ok:
- ctx.get_app_data().problems.append(OpenSSLVerifyError(cert, errno, depth))
- return preverify_ok
- ctx.set_verify(verifyFlags, _trackVerificationProblems)
-
- if self.verifyDepth is not None:
- ctx.set_verify_depth(self.verifyDepth)
-
- if self.enableSingleUseKeys:
- ctx.set_options(SSL.OP_SINGLE_DH_USE)
-
- if self.fixBrokenPeers:
- ctx.set_options(self._OP_ALL)
-
- if self.enableSessions:
- sessionName = md5.md5("%s-%d" % (reflect.qual(self.__class__), _sessionCounter())).hexdigest()
- ctx.set_session_id(sessionName)
-
- return ctx
diff --git a/tools/buildbot/pylibs/twisted/internet/_threadedselect.py b/tools/buildbot/pylibs/twisted/internet/_threadedselect.py
deleted file mode 100644
index 9dc90a0..0000000
--- a/tools/buildbot/pylibs/twisted/internet/_threadedselect.py
+++ /dev/null
@@ -1,362 +0,0 @@
-# -*- test-case-name: twisted.test.test_internet -*-
-# $Id: default.py,v 1.90 2004/01/06 22:35:22 warner Exp $
-#
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-from __future__ import generators
-
-"""
-Threaded select reactor
-
-Maintainer: U{Bob Ippolito<mailto:bob@redivi.com>}
-
-
-The threadedselectreactor is a specialized reactor for integrating with
-arbitrary foreign event loop, such as those you find in GUI toolkits.
-
-There are three things you'll need to do to use this reactor.
-
-Install the reactor at the beginning of your program, before importing
-the rest of Twisted::
-
- | from twisted.internet import _threadedselect
- | _threadedselect.install()
-
-Interleave this reactor with your foreign event loop, at some point after
-your event loop is initialized::
-
- | from twisted.internet import reactor
- | reactor.interleave(foreignEventLoopWakerFunction)
- | self.addSystemEventTrigger('after', 'shutdown', foreignEventLoopStop)
-
-Instead of shutting down the foreign event loop directly, shut down the
-reactor::
-
- | from twisted.internet import reactor
- | reactor.stop()
-
-In order for Twisted to do its work in the main thread (the thread that
-interleave is called from), a waker function is necessary. The waker function
-will be called from a "background" thread with one argument: func.
-The waker function's purpose is to call func() from the main thread.
-Many GUI toolkits ship with appropriate waker functions.
-Some examples of this are wxPython's wx.callAfter (may be wxCallAfter in
-older versions of wxPython) or PyObjC's PyObjCTools.AppHelper.callAfter.
-These would be used in place of "foreignEventLoopWakerFunction" in the above
-example.
-
-The other integration point at which the foreign event loop and this reactor
-must integrate is shutdown. In order to ensure clean shutdown of Twisted,
-you must allow for Twisted to come to a complete stop before quitting the
-application. Typically, you will do this by setting up an after shutdown
-trigger to stop your foreign event loop, and call reactor.stop() where you
-would normally have initiated the shutdown procedure for the foreign event
-loop. Shutdown functions that could be used in place of
-"foreignEventloopStop" would be the ExitMainLoop method of the wxApp instance
-with wxPython, or the PyObjCTools.AppHelper.stopEventLoop function.
-"""
-
-from threading import Thread
-from Queue import Queue, Empty
-from time import sleep
-import sys
-
-from zope.interface import implements
-
-from twisted.internet.interfaces import IReactorFDSet
-from twisted.internet import error
-from twisted.internet import posixbase
-from twisted.python import log, failure, threadable
-from twisted.persisted import styles
-from twisted.python.runtime import platformType
-
-import select
-from errno import EINTR, EBADF
-
-from twisted.internet.selectreactor import _select
-
-# Exceptions that doSelect might return frequently
-_NO_FILENO = error.ConnectionFdescWentAway('Handler has no fileno method')
-_NO_FILEDESC = error.ConnectionFdescWentAway('Filedescriptor went away')
-
-def dictRemove(dct, value):
- try:
- del dct[value]
- except KeyError:
- pass
-
-def raiseException(e):
- raise e
-
-class ThreadedSelectReactor(posixbase.PosixReactorBase):
- """A threaded select() based reactor - runs on all POSIX platforms and on
- Win32.
- """
- implements(IReactorFDSet)
-
- def __init__(self):
- threadable.init(1)
- self.reads = {}
- self.writes = {}
- self.toThreadQueue = Queue()
- self.toMainThread = Queue()
- self.workerThread = None
- self.mainWaker = None
- posixbase.PosixReactorBase.__init__(self)
- self.addSystemEventTrigger('after', 'shutdown', self._mainLoopShutdown)
-
- def wakeUp(self):
- # we want to wake up from any thread
- self.waker.wakeUp()
-
- def callLater(self, *args, **kw):
- tple = posixbase.PosixReactorBase.callLater(self, *args, **kw)
- self.wakeUp()
- return tple
-
- def _sendToMain(self, msg, *args):
- #print >>sys.stderr, 'sendToMain', msg, args
- self.toMainThread.put((msg, args))
- if self.mainWaker is not None:
- self.mainWaker()
-
- def _sendToThread(self, fn, *args):
- #print >>sys.stderr, 'sendToThread', fn, args
- self.toThreadQueue.put((fn, args))
-
- def _preenDescriptorsInThread(self):
- log.msg("Malformed file descriptor found. Preening lists.")
- readers = self.reads.keys()
- writers = self.writes.keys()
- self.reads.clear()
- self.writes.clear()
- for selDict, selList in ((self.reads, readers), (self.writes, writers)):
- for selectable in selList:
- try:
- select.select([selectable], [selectable], [selectable], 0)
- except:
- log.msg("bad descriptor %s" % selectable)
- else:
- selDict[selectable] = 1
-
- def _workerInThread(self):
- try:
- while 1:
- fn, args = self.toThreadQueue.get()
- #print >>sys.stderr, "worker got", fn, args
- fn(*args)
- except SystemExit:
- pass # exception indicates this thread should exit
- except:
- f = failure.Failure()
- self._sendToMain('Failure', f)
- #print >>sys.stderr, "worker finished"
-
- def _doSelectInThread(self, timeout):
- """Run one iteration of the I/O monitor loop.
-
- This will run all selectables who had input or output readiness
- waiting for them.
- """
- reads = self.reads
- writes = self.writes
- while 1:
- try:
- r, w, ignored = _select(reads.keys(),
- writes.keys(),
- [], timeout)
- break
- except ValueError, ve:
- # Possibly a file descriptor has gone negative?
- log.err()
- self._preenDescriptorsInThread()
- except TypeError, te:
- # Something *totally* invalid (object w/o fileno, non-integral
- # result) was passed
- log.err()
- self._preenDescriptorsInThread()
- except (select.error, IOError), se:
- # select(2) encountered an error
- if se.args[0] in (0, 2):
- # windows does this if it got an empty list
- if (not reads) and (not writes):
- return
- else:
- raise
- elif se.args[0] == EINTR:
- return
- elif se.args[0] == EBADF:
- self._preenDescriptorsInThread()
- else:
- # OK, I really don't know what's going on. Blow up.
- raise
- self._sendToMain('Notify', r, w)
-
- def _process_Notify(self, r, w):
- #print >>sys.stderr, "_process_Notify"
- reads = self.reads
- writes = self.writes
-
- _drdw = self._doReadOrWrite
- _logrun = log.callWithLogger
- for selectables, method, dct in ((r, "doRead", reads), (w, "doWrite", writes)):
- for selectable in selectables:
- # if this was disconnected in another thread, kill it.
- if selectable not in dct:
- continue
- # This for pausing input when we're not ready for more.
- _logrun(selectable, _drdw, selectable, method, dct)
- #print >>sys.stderr, "done _process_Notify"
-
- def _process_Failure(self, f):
- f.raiseException()
-
- _doIterationInThread = _doSelectInThread
-
- def ensureWorkerThread(self):
- if self.workerThread is None or not self.workerThread.isAlive():
- self.workerThread = Thread(target=self._workerInThread)
- self.workerThread.start()
-
- def doThreadIteration(self, timeout):
- self._sendToThread(self._doIterationInThread, timeout)
- self.ensureWorkerThread()
- #print >>sys.stderr, 'getting...'
- msg, args = self.toMainThread.get()
- #print >>sys.stderr, 'got', msg, args
- getattr(self, '_process_' + msg)(*args)
-
- doIteration = doThreadIteration
-
- def _interleave(self):
- while self.running:
- #print >>sys.stderr, "runUntilCurrent"
- self.runUntilCurrent()
- t2 = self.timeout()
- t = self.running and t2
- self._sendToThread(self._doIterationInThread, t)
- #print >>sys.stderr, "yielding"
- yield None
- #print >>sys.stderr, "fetching"
- msg, args = self.toMainThread.get_nowait()
- getattr(self, '_process_' + msg)(*args)
-
- def interleave(self, waker, *args, **kw):
- """
- interleave(waker) interleaves this reactor with the
- current application by moving the blocking parts of
- the reactor (select() in this case) to a separate
- thread. This is typically useful for integration with
- GUI applications which have their own event loop
- already running.
-
- See the module docstring for more information.
- """
- self.startRunning(*args, **kw)
- loop = self._interleave()
- def mainWaker(waker=waker, loop=loop):
- #print >>sys.stderr, "mainWaker()"
- waker(loop.next)
- self.mainWaker = mainWaker
- loop.next()
- self.ensureWorkerThread()
-
- def _mainLoopShutdown(self):
- self.mainWaker = None
- if self.workerThread is not None:
- #print >>sys.stderr, 'getting...'
- self._sendToThread(raiseException, SystemExit)
- self.wakeUp()
- try:
- while 1:
- msg, args = self.toMainThread.get_nowait()
- #print >>sys.stderr, "ignored:", (msg, args)
- except Empty:
- pass
- self.workerThread.join()
- self.workerThread = None
- try:
- while 1:
- fn, args = self.toThreadQueue.get_nowait()
- if fn is self._doIterationInThread:
- log.msg('Iteration is still in the thread queue!')
- elif fn is raiseException and args[0] is SystemExit:
- pass
- else:
- fn(*args)
- except Empty:
- pass
-
- def _doReadOrWrite(self, selectable, method, dict):
- try:
- why = getattr(selectable, method)()
- handfn = getattr(selectable, 'fileno', None)
- if not handfn:
- why = _NO_FILENO
- elif handfn() == -1:
- why = _NO_FILEDESC
- except:
- why = sys.exc_info()[1]
- log.err()
- if why:
- self._disconnectSelectable(selectable, why, method == "doRead")
-
- def addReader(self, reader):
- """Add a FileDescriptor for notification of data available to read.
- """
- self._sendToThread(self.reads.__setitem__, reader, 1)
- self.wakeUp()
-
- def addWriter(self, writer):
- """Add a FileDescriptor for notification of data available to write.
- """
- self._sendToThread(self.writes.__setitem__, writer, 1)
- self.wakeUp()
-
- def removeReader(self, reader):
- """Remove a Selectable for notification of data available to read.
- """
- self._sendToThread(dictRemove, self.reads, reader)
-
- def removeWriter(self, writer):
- """Remove a Selectable for notification of data available to write.
- """
- self._sendToThread(dictRemove, self.writes, writer)
-
- def removeAll(self):
- return self._removeAll(self.reads, self.writes)
-
-
- def getReaders(self):
- return self.reads.keys()
-
-
- def getWriters(self):
- return self.writes.keys()
-
-
- def run(self, installSignalHandlers=1):
- self.startRunning(installSignalHandlers=installSignalHandlers)
- self.mainLoop()
-
- def mainLoop(self):
- q = Queue()
- self.interleave(q.put)
- while self.running:
- try:
- q.get()()
- except StopIteration:
- break
-
-
-
-def install():
- """Configure the twisted mainloop to be run using the select() reactor.
- """
- reactor = ThreadedSelectReactor()
- from twisted.internet.main import installReactor
- installReactor(reactor)
- return reactor
-
-__all__ = ['install']
diff --git a/tools/buildbot/pylibs/twisted/internet/_win32serialport.py b/tools/buildbot/pylibs/twisted/internet/_win32serialport.py
deleted file mode 100644
index 576e7b4..0000000
--- a/tools/buildbot/pylibs/twisted/internet/_win32serialport.py
+++ /dev/null
@@ -1,112 +0,0 @@
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-Serial port support for Windows.
-
-Requires PySerial and win32all, and needs to be used with win32event
-reactor.
-"""
-
-# system imports
-import os
-import serial
-from serial import PARITY_NONE, PARITY_EVEN, PARITY_ODD
-from serial import STOPBITS_ONE, STOPBITS_TWO
-from serial import FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS
-import win32file, win32event
-
-# twisted imports
-from twisted.protocols import basic
-from twisted.internet import abstract
-from twisted.python import log
-
-# sibling imports
-from serialport import BaseSerialPort
-
-
-class SerialPort(BaseSerialPort, abstract.FileDescriptor):
- """A select()able serial device, acting as a transport."""
-
- connected = 1
-
- def __init__(self, protocol, deviceNameOrPortNumber, reactor,
- baudrate = 9600, bytesize = EIGHTBITS, parity = PARITY_NONE,
- stopbits = STOPBITS_ONE, xonxoff = 0, rtscts = 0):
- self._serial = serial.Serial(deviceNameOrPortNumber, baudrate=baudrate,
- bytesize=bytesize, parity=parity,
- stopbits=stopbits, timeout=None,
- xonxoff=xonxoff, rtscts=rtscts)
- self.flushInput()
- self.flushOutput()
- self.reactor = reactor
- self.protocol = protocol
- self.outQueue = []
- self.closed = 0
- self.closedNotifies = 0
- self.writeInProgress = 0
-
- self.protocol = protocol
- self._overlappedRead = win32file.OVERLAPPED()
- self._overlappedRead.hEvent = win32event.CreateEvent(None, 1, 0, None)
- self._overlappedWrite = win32file.OVERLAPPED()
- self._overlappedWrite.hEvent = win32event.CreateEvent(None, 0, 0, None)
-
- self.reactor.addEvent(self._overlappedRead.hEvent, self, 'serialReadEvent')
- self.reactor.addEvent(self._overlappedWrite.hEvent, self, 'serialWriteEvent')
-
- self.protocol.makeConnection(self)
-
- flags, comstat = win32file.ClearCommError(self._serial.hComPort)
- rc, self.read_buf = win32file.ReadFile(self._serial.hComPort,
- win32file.AllocateReadBuffer(1),
- self._overlappedRead)
-
- def serialReadEvent(self):
- #get that character we set up
- n = win32file.GetOverlappedResult(self._serial.hComPort, self._overlappedRead, 0)
- if n:
- first = str(self.read_buf[:n])
- #now we should get everything that is already in the buffer
- flags, comstat = win32file.ClearCommError(self._serial.hComPort)
- if comstat.cbInQue:
- win32event.ResetEvent(self._overlappedRead.hEvent)
- rc, buf = win32file.ReadFile(self._serial.hComPort,
- win32file.AllocateReadBuffer(comstat.cbInQue),
- self._overlappedRead)
- n = win32file.GetOverlappedResult(self._serial.hComPort, self._overlappedRead, 1)
- #handle all the received data:
- self.protocol.dataReceived(first + str(buf[:n]))
- else:
- #handle all the received data:
- self.protocol.dataReceived(first)
-
- #set up next one
- win32event.ResetEvent(self._overlappedRead.hEvent)
- rc, self.read_buf = win32file.ReadFile(self._serial.hComPort,
- win32file.AllocateReadBuffer(1),
- self._overlappedRead)
-
- def write(self, data):
- if data:
- if self.writeInProgress:
- self.outQueue.append(data)
- else:
- self.writeInProgress = 1
- win32file.WriteFile(self._serial.hComPort, data, self._overlappedWrite)
-
- def serialWriteEvent(self):
- try:
- dataToWrite = self.outQueue.pop(0)
- except IndexError:
- self.writeInProgress = 0
- return
- else:
- win32file.WriteFile(self._serial.hComPort, dataToWrite, self._overlappedWrite)
-
- def connectionLost(self, reason):
- self.reactor.removeEvent(self._overlappedRead.hEvent)
- self.reactor.removeEvent(self._overlappedWrite.hEvent)
- abstract.FileDescriptor.connectionLost(self, reason)
- self._serial.close()
diff --git a/tools/buildbot/pylibs/twisted/internet/_win32stdio.py b/tools/buildbot/pylibs/twisted/internet/_win32stdio.py
deleted file mode 100644
index b87f7a3..0000000
--- a/tools/buildbot/pylibs/twisted/internet/_win32stdio.py
+++ /dev/null
@@ -1,116 +0,0 @@
-# -*- test-case-name: twisted.test.test_process.ProcessTestCase.testStdio -*-
-
-import win32api
-import os, msvcrt
-
-from zope.interface import implements
-
-from twisted.internet.interfaces import IHalfCloseableProtocol, ITransport, IAddress
-from twisted.internet.interfaces import IConsumer, IPushProducer
-
-from twisted.internet import _pollingfile, main
-
-class Win32PipeAddress(object):
- implements(IAddress)
-
-class StandardIO(_pollingfile._PollingTimer):
-
- implements(ITransport,
- IConsumer,
- IPushProducer)
-
- disconnecting = False
- disconnected = False
-
- def __init__(self, proto):
- """
- Start talking to standard IO with the given protocol.
-
- Also, put it stdin/stdout/stderr into binary mode.
- """
- from twisted.internet import reactor
-
- for stdfd in range(0, 1, 2):
- msvcrt.setmode(stdfd, os.O_BINARY)
-
- _pollingfile._PollingTimer.__init__(self, reactor)
- self.proto = proto
-
- hstdin = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE)
- hstdout = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
-
- self.stdin = _pollingfile._PollableReadPipe(
- hstdin, self.dataReceived, self.readConnectionLost)
-
- self.stdout = _pollingfile._PollableWritePipe(
- hstdout, self.writeConnectionLost)
-
- self._addPollableResource(self.stdin)
- self._addPollableResource(self.stdout)
-
- self.proto.makeConnection(self)
-
- def dataReceived(self, data):
- self.proto.dataReceived(data)
-
- def readConnectionLost(self):
- if IHalfCloseableProtocol.providedBy(self.proto):
- self.proto.readConnectionLost()
- self.checkConnLost()
-
- def writeConnectionLost(self):
- if IHalfCloseableProtocol.providedBy(self.proto):
- self.proto.writeConnectionLost()
- self.checkConnLost()
-
- connsLost = 0
-
- def checkConnLost(self):
- self.connsLost += 1
- if self.connsLost >= 2:
- self.disconnecting = True
- self.disconnected = True
- self.proto.connectionLost(main.CONNECTION_DONE)
-
- # ITransport
-
- def write(self, data):
- self.stdout.write(data)
-
- def writeSequence(self, seq):
- self.stdout.write(''.join(seq))
-
- def loseConnection(self):
- self.disconnecting = True
- self.stdin.close()
- self.stdout.close()
-
- def getPeer(self):
- return Win32PipeAddress()
-
- def getHost(self):
- return Win32PipeAddress()
-
- # IConsumer
-
- def registerProducer(self, producer, streaming):
- return self.stdout.registerProducer(producer, streaming)
-
- def unregisterProducer(self):
- return self.stdout.unregisterProducer()
-
- # def write() above
-
- # IProducer
-
- def stopProducing(self):
- self.stdin.stopProducing()
-
- # IPushProducer
-
- def pauseProducing(self):
- self.stdin.pauseProducing()
-
- def resumeProducing(self):
- self.stdin.resumeProducing()
-
diff --git a/tools/buildbot/pylibs/twisted/internet/abstract.py b/tools/buildbot/pylibs/twisted/internet/abstract.py
deleted file mode 100644
index cc6db47..0000000
--- a/tools/buildbot/pylibs/twisted/internet/abstract.py
+++ /dev/null
@@ -1,368 +0,0 @@
-# -*- test-case-name: twisted.test.test_abstract -*-
-# Copyright (c) 2001-2007 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-Support for generic select()able objects.
-
-Maintainer: U{Itamar Shtull-Trauring<mailto:twisted@itamarst.org>}
-"""
-
-from zope.interface import implements
-
-# Twisted Imports
-from twisted.python import log, reflect, failure
-from twisted.persisted import styles
-from twisted.internet import interfaces, main
-
-
-class FileDescriptor(log.Logger, styles.Ephemeral, object):
- """An object which can be operated on by select().
-
- This is an abstract superclass of all objects which may be notified when
- they are readable or writable; e.g. they have a file-descriptor that is
- valid to be passed to select(2).
- """
- connected = 0
- producerPaused = 0
- streamingProducer = 0
- producer = None
- disconnected = 0
- disconnecting = 0
- _writeDisconnecting = False
- _writeDisconnected = False
- dataBuffer = ""
- offset = 0
-
- SEND_LIMIT = 128*1024
-
- implements(interfaces.IProducer, interfaces.IReadWriteDescriptor,
- interfaces.IConsumer, interfaces.ITransport, interfaces.IHalfCloseableDescriptor)
-
- def __init__(self, reactor=None):
- if not reactor:
- from twisted.internet import reactor
- self.reactor = reactor
- self._tempDataBuffer = [] # will be added to dataBuffer in doWrite
- self._tempDataLen = 0
-
- def connectionLost(self, reason):
- """The connection was lost.
-
- This is called when the connection on a selectable object has been
- lost. It will be called whether the connection was closed explicitly,
- an exception occurred in an event handler, or the other end of the
- connection closed it first.
-
- Clean up state here, but make sure to call back up to FileDescriptor.
- """
-
- self.disconnected = 1
- self.connected = 0
- if self.producer is not None:
- self.producer.stopProducing()
- self.producer = None
- self.stopReading()
- self.stopWriting()
-
- def writeSomeData(self, data):
- """Write as much as possible of the given data, immediately.
-
- This is called to invoke the lower-level writing functionality, such as
- a socket's send() method, or a file's write(); this method returns an
- integer. If positive, it is the number of bytes written; if negative,
- it indicates the connection was lost.
- """
-
- raise NotImplementedError("%s does not implement writeSomeData" %
- reflect.qual(self.__class__))
-
- def doRead(self):
- """Called when data is avaliable for reading.
-
- Subclasses must override this method. The result will be interpreted
- in the same way as a result of doWrite().
- """
- raise NotImplementedError("%s does not implement doRead" %
- reflect.qual(self.__class__))
-
- def doWrite(self):
- """Called when data can be written.
-
- A result that is true (which will be a negative number) implies the
- connection was lost. A false result implies the connection is still
- there; a result of 0 implies no write was done, and a result of None
- indicates that a write was done.
- """
- if len(self.dataBuffer) - self.offset < self.SEND_LIMIT:
- # If there is currently less than SEND_LIMIT bytes left to send
- # in the string, extend it with the array data.
- self.dataBuffer = buffer(self.dataBuffer, self.offset) + "".join(self._tempDataBuffer)
- self.offset = 0
- self._tempDataBuffer = []
- self._tempDataLen = 0
-
- # Send as much data as you can.
- if self.offset:
- l = self.writeSomeData(buffer(self.dataBuffer, self.offset))
- else:
- l = self.writeSomeData(self.dataBuffer)
- if l < 0 or isinstance(l, Exception):
- return l
- if l == 0 and self.dataBuffer:
- result = 0
- else:
- result = None
- self.offset += l
- # If there is nothing left to send,
- if self.offset == len(self.dataBuffer) and not self._tempDataLen:
- self.dataBuffer = ""
- self.offset = 0
- # stop writing.
- self.stopWriting()
- # If I've got a producer who is supposed to supply me with data,
- if self.producer is not None and ((not self.streamingProducer)
- or self.producerPaused):
- # tell them to supply some more.
- self.producerPaused = 0
- self.producer.resumeProducing()
- elif self.disconnecting:
- # But if I was previously asked to let the connection die, do
- # so.
- return self._postLoseConnection()
- elif self._writeDisconnecting:
- # I was previously asked to to half-close the connection.
- result = self._closeWriteConnection()
- self._writeDisconnected = True
- return result
- return result
-
- def _postLoseConnection(self):
- """Called after a loseConnection(), when all data has been written.
-
- Whatever this returns is then returned by doWrite.
- """
- # default implementation, telling reactor we're finished
- return main.CONNECTION_DONE
-
- def _closeWriteConnection(self):
- # override in subclasses
- pass
-
- def writeConnectionLost(self, reason):
- # in current code should never be called
- self.connectionLost(reason)
-
- def readConnectionLost(self, reason):
- # override in subclasses
- self.connectionLost(reason)
-
- def write(self, data):
- """Reliably write some data.
-
- The data is buffered until the underlying file descriptor is ready
- for writing. If there is more than C{self.bufferSize} data in the
- buffer and this descriptor has a registered streaming producer, its
- C{pauseProducing()} method will be called.
- """
- if isinstance(data, unicode): # no, really, I mean it
- raise TypeError("Data must not be unicode")
- if not self.connected or self._writeDisconnected:
- return
- if data:
- self._tempDataBuffer.append(data)
- self._tempDataLen += len(data)
- # If we are responsible for pausing our producer,
- if self.producer is not None and self.streamingProducer:
- # and our buffer is full,
- if len(self.dataBuffer) + self._tempDataLen > self.bufferSize:
- # pause it.
- self.producerPaused = 1
- self.producer.pauseProducing()
- self.startWriting()
-
- def writeSequence(self, iovec):
- """Reliably write a sequence of data.
-
- Currently, this is a convenience method roughly equivalent to::
-
- for chunk in iovec:
- fd.write(chunk)
-
- It may have a more efficient implementation at a later time or in a
- different reactor.
-
- As with the C{write()} method, if a buffer size limit is reached and a
- streaming producer is registered, it will be paused until the buffered
- data is written to the underlying file descriptor.
- """
- if not self.connected or not iovec or self._writeDisconnected:
- return
- self._tempDataBuffer.extend(iovec)
- for i in iovec:
- self._tempDataLen += len(i)
- # If we are responsible for pausing our producer,
- if self.producer is not None and self.streamingProducer:
- # and our buffer is full,
- if len(self.dataBuffer) + self._tempDataLen > self.bufferSize:
- # pause it.
- self.producerPaused = 1
- self.producer.pauseProducing()
- self.startWriting()
-
- def loseConnection(self, _connDone=failure.Failure(main.CONNECTION_DONE)):
- """Close the connection at the next available opportunity.
-
- Call this to cause this FileDescriptor to lose its connection. It will
- first write any data that it has buffered.
-
- If there is data buffered yet to be written, this method will cause the
- transport to lose its connection as soon as it's done flushing its
- write buffer. If you have a producer registered, the connection won't
- be closed until the producer is finished. Therefore, make sure you
- unregister your producer when it's finished, or the connection will
- never close.
- """
-
- if self.connected and not self.disconnecting:
- if self._writeDisconnected:
- # doWrite won't trigger the connection close anymore
- self.stopReading()
- self.stopWriting()
- self.connectionLost(_connDone)
- else:
- self.stopReading()
- self.startWriting()
- self.disconnecting = 1
-
- def loseWriteConnection(self):
- self._writeDisconnecting = True
- self.startWriting()
-
- def stopReading(self):
- """Stop waiting for read availability.
-
- Call this to remove this selectable from being notified when it is
- ready for reading.
- """
- self.reactor.removeReader(self)
-
- def stopWriting(self):
- """Stop waiting for write availability.
-
- Call this to remove this selectable from being notified when it is ready
- for writing.
- """
- self.reactor.removeWriter(self)
-
- def startReading(self):
- """Start waiting for read availability.
- """
- self.reactor.addReader(self)
-
- def startWriting(self):
- """Start waiting for write availability.
-
- Call this to have this FileDescriptor be notified whenever it is ready for
- writing.
- """
- self.reactor.addWriter(self)
-
- # Producer/consumer implementation
-
- # first, the consumer stuff. This requires no additional work, as
- # any object you can write to can be a consumer, really.
-
- producer = None
- bufferSize = 2**2**2**2
-
- def registerProducer(self, producer, streaming):
- """Register to receive data from a producer.
-
- This sets this selectable to be a consumer for a producer. When this
- selectable runs out of data on a write() call, it will ask the producer
- to resumeProducing(). When the FileDescriptor's internal data buffer is
- filled, it will ask the producer to pauseProducing(). If the connection
- is lost, FileDescriptor calls producer's stopProducing() method.
-
- If streaming is true, the producer should provide the IPushProducer
- interface. Otherwise, it is assumed that producer provides the
- IPullProducer interface. In this case, the producer won't be asked
- to pauseProducing(), but it has to be careful to write() data only
- when its resumeProducing() method is called.
- """
- if self.producer is not None:
- raise RuntimeError("Cannot register producer %s, because producer %s was never unregistered." % (producer, self.producer))
- if self.disconnected:
- producer.stopProducing()
- else:
- self.producer = producer
- self.streamingProducer = streaming
- if not streaming:
- producer.resumeProducing()
-
- def unregisterProducer(self):
- """Stop consuming data from a producer, without disconnecting.
- """
- self.producer = None
-
- def stopConsuming(self):
- """Stop consuming data.
-
- This is called when a producer has lost its connection, to tell the
- consumer to go lose its connection (and break potential circular
- references).
- """
- self.unregisterProducer()
- self.loseConnection()
-
- # producer interface implementation
-
- def resumeProducing(self):
- assert self.connected and not self.disconnecting
- self.startReading()
-
- 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
-
-
-def isIPAddress(addr):
- """
- Determine whether the given string represents an IPv4 address.
-
- @type addr: C{str}
- @param addr: A string which may or may not be the decimal dotted
- representation of an IPv4 address.
-
- @rtype: C{bool}
- @return: C{True} if C{addr} represents an IPv4 address, C{False}
- otherwise.
- """
- dottedParts = addr.split('.')
- if len(dottedParts) == 4:
- for octet in dottedParts:
- try:
- value = int(octet)
- except ValueError:
- return False
- else:
- if value < 0 or value > 255:
- return False
- return True
- return False
-
-
-__all__ = ["FileDescriptor"]
diff --git a/tools/buildbot/pylibs/twisted/internet/address.py b/tools/buildbot/pylibs/twisted/internet/address.py
deleted file mode 100644
index b349080..0000000
--- a/tools/buildbot/pylibs/twisted/internet/address.py
+++ /dev/null
@@ -1,113 +0,0 @@
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""Address objects for network connections."""
-
-import warnings, os
-from zope.interface import implements
-from twisted.internet.interfaces import IAddress
-
-
-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 __str__(self):
- return 'IPv4Address(%s, %r, %d)' % (self.type, self.host, self.port)
-
-
-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):
- try:
- return os.path.samefile(self.name, other.name)
- except OSError:
- pass
- return False
-
- def __str__(self):
- return 'UNIXSocket(%r)' % (self.name,)
-
-
-# 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):
- a = (self.type, self.host, self.port)
- b = (other.type, other.host, other.port)
- return a == b
- return False
diff --git a/tools/buildbot/pylibs/twisted/internet/base.py b/tools/buildbot/pylibs/twisted/internet/base.py
deleted file mode 100644
index 0d700f8..0000000
--- a/tools/buildbot/pylibs/twisted/internet/base.py
+++ /dev/null
@@ -1,1069 +0,0 @@
-# -*- test-case-name: twisted.test.test_internet -*-
-# Copyright (c) 2001-2008 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-Very basic functionality for a Reactor implementation.
-
-Maintainer: U{Itamar Shtull-Trauring<mailto:twisted@itamarst.org>}
-"""
-
-import socket # needed only for sync-dns
-from zope.interface import implements, classImplements
-
-import sys
-import warnings
-import operator
-from heapq import heappush, heappop, heapify
-
-try:
- import fcntl
-except ImportError:
- fcntl = None
-import traceback
-
-from twisted.internet.interfaces import IReactorCore, IReactorTime, IReactorThreads
-from twisted.internet.interfaces import IResolverSimple, IReactorPluggableResolver
-from twisted.internet.interfaces import IConnector, IDelayedCall
-from twisted.internet import main, error, abstract, defer, threads
-from twisted.python import log, failure, reflect
-from twisted.python.runtime import seconds as runtimeSeconds, platform, platformType
-from twisted.internet.defer import Deferred, DeferredList
-from twisted.persisted import styles
-
-# This import is for side-effects! Even if you don't see any code using it
-# in this module, don't delete it.
-from twisted.python import threadable
-
-
-class DelayedCall(styles.Ephemeral):
-
- implements(IDelayedCall)
- # enable .debug to record creator call stack, and it will be logged if
- # an exception occurs while the function is being run
- debug = False
- _str = None
-
- def __init__(self, time, func, args, kw, cancel, reset,
- seconds=runtimeSeconds):
- """
- @param time: Seconds from the epoch at which to call C{func}.
- @param func: The callable to call.
- @param args: The positional arguments to pass to the callable.
- @param kw: The keyword arguments to pass to the callable.
- @param cancel: A callable which will be called with this
- DelayedCall before cancellation.
- @param reset: A callable which will be called with this
- DelayedCall after changing this DelayedCall's scheduled
- execution time. The callable should adjust any necessary
- scheduling details to ensure this DelayedCall is invoked
- at the new appropriate time.
- @param seconds: If provided, a no-argument callable which will be
- used to determine the current time any time that information is
- needed.
- """
- self.time, self.func, self.args, self.kw = time, func, args, kw
- self.resetter = reset
- self.canceller = cancel
- self.seconds = seconds
- self.cancelled = self.called = 0
- self.delayed_time = 0
- if self.debug:
- self.creator = traceback.format_stack()[:-2]
-
- def getTime(self):
- """Return the time at which this call will fire
-
- @rtype: C{float}
- @return: The number of seconds after the epoch at which this call is
- scheduled to be made.
- """
- return self.time + self.delayed_time
-
- def cancel(self):
- """Unschedule this call
-
- @raise AlreadyCancelled: Raised if this call has already been
- unscheduled.
-
- @raise AlreadyCalled: Raised if this call has already been made.
- """
- if self.cancelled:
- raise error.AlreadyCancelled
- elif self.called:
- raise error.AlreadyCalled
- else:
- self.canceller(self)
- self.cancelled = 1
- if self.debug:
- self._str = str(self)
- del self.func, self.args, self.kw
-
- def reset(self, secondsFromNow):
- """Reschedule this call for a different time
-
- @type secondsFromNow: C{float}
- @param secondsFromNow: The number of seconds from the time of the
- C{reset} call at which this call will be scheduled.
-
- @raise AlreadyCancelled: Raised if this call has been cancelled.
- @raise AlreadyCalled: Raised if this call has already been made.
- """
- if self.cancelled:
- raise error.AlreadyCancelled
- elif self.called:
- raise error.AlreadyCalled
- else:
- newTime = self.seconds() + secondsFromNow
- if newTime < self.time:
- self.delayed_time = 0
- self.time = newTime
- self.resetter(self)
- else:
- self.delayed_time = newTime - self.time
-
- def delay(self, secondsLater):
- """Reschedule this call for a later time
-
- @type secondsLater: C{float}
- @param secondsLater: The number of seconds after the originally
- scheduled time for which to reschedule this call.
-
- @raise AlreadyCancelled: Raised if this call has been cancelled.
- @raise AlreadyCalled: Raised if this call has already been made.
- """
- if self.cancelled:
- raise error.AlreadyCancelled
- elif self.called:
- raise error.AlreadyCalled
- else:
- self.delayed_time += secondsLater
- if self.delayed_time < 0:
- self.activate_delay()
- self.resetter(self)
-
- def activate_delay(self):
- self.time += self.delayed_time
- self.delayed_time = 0
-
- def active(self):
- """Determine whether this call is still pending
-
- @rtype: C{bool}
- @return: True if this call has not yet been made or cancelled,
- False otherwise.
- """
- return not (self.cancelled or self.called)
-
- def __le__(self, other):
- return self.time <= other.time
-
- def __str__(self):
- if self._str is not None:
- return self._str
- if hasattr(self, 'func'):
- if hasattr(self.func, 'func_name'):
- func = self.func.func_name
- if hasattr(self.func, 'im_class'):
- func = self.func.im_class.__name__ + '.' + func
- else:
- func = reflect.safe_repr(self.func)
- else:
- func = None
-
- now = self.seconds()
- L = ["<DelayedCall %s [%ss] called=%s cancelled=%s" % (
- id(self), self.time - now, self.called, self.cancelled)]
- if func is not None:
- L.extend((" ", func, "("))
- if self.args:
- L.append(", ".join([reflect.safe_repr(e) for e in self.args]))
- if self.kw:
- L.append(", ")
- 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)
-
-
-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]
- del self._runningQueries[lookupDeferred]
- userDeferred.errback(self._fail(name, "timeout error"))
-
- def _checkTimeout(self, result, name, lookupDeferred):
- try:
- userDeferred, cancelCall = self._runningQueries[lookupDeferred]
- except KeyError:
- pass
- else:
- del self._runningQueries[lookupDeferred]
- cancelCall.cancel()
-
- if isinstance(result, failure.Failure):
- userDeferred.errback(self._fail(name, result.getErrorMessage()))
- else:
- userDeferred.callback(result)
-
- def getHostByName(self, name, timeout = (1, 3, 11, 45)):
- if timeout:
- timeoutDelay = reduce(operator.add, timeout)
- else:
- timeoutDelay = 60
- userDeferred = defer.Deferred()
- lookupDeferred = threads.deferToThread(socket.gethostbyname, name)
- cancelCall = self.reactor.callLater(
- timeoutDelay, self._cleanup, name, lookupDeferred)
- self._runningQueries[lookupDeferred] = (userDeferred, cancelCall)
- lookupDeferred.addBoth(self._checkTimeout, name, lookupDeferred)
- return userDeferred
-
-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 _ThreePhaseEvent(object):
- """
- Collection of callables (with arguments) which can be invoked as a group in
- a particular order.
-
- This provides the underlying implementation for the reactor's system event
- triggers. An instance of this class tracks triggers for all phases of a
- single type of event.
-
- @ivar before: A list of the before-phase triggers containing three-tuples
- of a callable, a tuple of positional arguments, and a dict of keyword
- arguments
-
- @ivar finishedBefore: A list of the before-phase triggers which have
- already been executed. This is only populated in the C{'BEFORE'} state.
-
- @ivar during: A list of the during-phase triggers containing three-tuples
- of a callable, a tuple of positional arguments, and a dict of keyword
- arguments
-
- @ivar after: A list of the after-phase triggers containing three-tuples
- of a callable, a tuple of positional arguments, and a dict of keyword
- arguments
-
- @ivar state: A string indicating what is currently going on with this
- object. One of C{'BASE'} (for when nothing in particular is happening;
- this is the initial value), C{'BEFORE'} (when the before-phase triggers
- are in the process of being executed).
- """
- def __init__(self):
- self.before = []
- self.during = []
- self.after = []
- self.state = 'BASE'
-
-
- def addTrigger(self, phase, callable, *args, **kwargs):
- """
- Add a trigger to the indicate phase.
-
- @param phase: One of C{'before'}, C{'during'}, or C{'after'}.
-
- @param callable: An object to be called when this event is triggered.
- @param *args: Positional arguments to pass to C{callable}.
- @param **kwargs: Keyword arguments to pass to C{callable}.
-
- @return: An opaque handle which may be passed to L{removeTrigger} to
- reverse the effects of calling this method.
- """
- if phase not in ('before', 'during', 'after'):
- raise KeyError("invalid phase")
- getattr(self, phase).append((callable, args, kwargs))
- return phase, callable, args, kwargs
-
-
- def removeTrigger(self, handle):
- """
- Remove a previously added trigger callable.
-
- @param handle: An object previously returned by L{addTrigger}. The
- trigger added by that call will be removed.
-
- @raise ValueError: If the trigger associated with C{handle} has already
- been removed or if C{handle} is not a valid handle.
- """
- return getattr(self, 'removeTrigger_' + self.state)(handle)
-
-
- def removeTrigger_BASE(self, handle):
- """
- Just try to remove the trigger.
-
- @see removeTrigger
- """
- try:
- phase, callable, args, kwargs = handle
- except (TypeError, ValueError), e:
- raise ValueError("invalid trigger handle")
- else:
- if phase not in ('before', 'during', 'after'):
- raise KeyError("invalid phase")
- getattr(self, phase).remove((callable, args, kwargs))
-
-
- def removeTrigger_BEFORE(self, handle):
- """
- Remove the trigger if it has yet to be executed, otherwise emit a
- warning that in the future an exception will be raised when removing an
- already-executed trigger.
-
- @see removeTrigger
- """
- phase, callable, args, kwargs = handle
- if phase != 'before':
- return self.removeTrigger_BASE(handle)
- if (callable, args, kwargs) in self.finishedBefore:
- warnings.warn(
- "Removing already-fired system event triggers will raise an "
- "exception in a future version of Twisted.",
- category=DeprecationWarning,
- stacklevel=3)
- else:
- self.removeTrigger_BASE(handle)
-
-
- def fireEvent(self):
- """
- Call the triggers added to this event.
- """
- self.state = 'BEFORE'
- self.finishedBefore = []
- beforeResults = []
- while self.before:
- callable, args, kwargs = self.before.pop(0)
- self.finishedBefore.append((callable, args, kwargs))
- try:
- result = callable(*args, **kwargs)
- except:
- log.err()
- else:
- if isinstance(result, Deferred):
- beforeResults.append(result)
- DeferredList(beforeResults).addCallback(self._continueFiring)
-
-
- def _continueFiring(self, ignored):
- """
- Call the during and after phase triggers for this event.
- """
- self.state = 'BASE'
- self.finishedBefore = []
- for phase in self.during, self.after:
- while phase:
- callable, args, kwargs = phase.pop(0)
- try:
- callable(*args, **kwargs)
- except:
- log.err()
-
-
-
-class ReactorBase(object):
- """
- Default base class for Reactors.
-
- @type _stopped: C{bool}
- @ivar _stopped: A flag which is true between paired calls to C{reactor.run}
- and C{reactor.stop}.
- """
-
- implements(IReactorCore, IReactorTime, IReactorPluggableResolver)
-
- _stopped = True
- installed = False
- usingThreads = False
- resolver = BlockingResolver()
-
- __name__ = "twisted.internet.reactor"
-
- def __init__(self):
- self.threadCallQueue = []
- self._eventTriggers = {}
- self._pendingTimedCalls = []
- self._newTimedCalls = []
- self._cancellations = 0
- self.running = False
- self.waker = None
-
- self.addSystemEventTrigger('during', 'shutdown', self.crash)
- self.addSystemEventTrigger('during', 'shutdown', self.disconnectAll)
-
- if platform.supportsThreads():
- self._initThreads()
-
- # override in subclasses
-
- _lock = None
-
- def installWaker(self):
- raise NotImplementedError()
-
- def installResolver(self, resolver):
- assert IResolverSimple.providedBy(resolver)
- oldResolver = self.resolver
- self.resolver = resolver
- return oldResolver
-
- def wakeUp(self):
- """Wake up the event loop."""
- if not threadable.isInIOThread():
- if self.waker:
- self.waker.wakeUp()
- # if the waker isn't installed, the reactor isn't running, and
- # therefore doesn't need to be woken up
-
- def doIteration(self, delay):
- """Do one iteration over the readers and writers we know about."""
- raise NotImplementedError
-
- def addReader(self, reader):
- raise NotImplementedError
-
- def addWriter(self, writer):
- raise NotImplementedError
-
- def removeReader(self, reader):
- raise NotImplementedError
-
- def removeWriter(self, writer):
- raise NotImplementedError
-
- def removeAll(self):
- raise NotImplementedError
-
-
- def getReaders(self):
- raise NotImplementedError()
-
-
- def getWriters(self):
- raise NotImplementedError()
-
-
- def resolve(self, name, timeout = (1, 3, 11, 45)):
- """Return a Deferred that will resolve a hostname.
- """
- if not name:
- # XXX - This is *less than* '::', and will screw up IPv6 servers
- return defer.succeed('0.0.0.0')
- if abstract.isIPAddress(name):
- return defer.succeed(name)
- return self.resolver.getHostByName(name, timeout)
-
- # Installation.
-
- # IReactorCore
-
- def stop(self):
- """
- See twisted.internet.interfaces.IReactorCore.stop.
- """
- if self._stopped:
- raise error.ReactorNotRunning(
- "Can't stop reactor that isn't running.")
- self._stopped = True
- self.callLater(0, self.fireSystemEvent, "shutdown")
-
- def crash(self):
- """
- See twisted.internet.interfaces.IReactorCore.crash.
- """
- self.running = False
-
- def sigInt(self, *args):
- """Handle a SIGINT interrupt.
- """
- log.msg("Received SIGINT, shutting down.")
- self.callFromThread(self.stop)
-
- def sigBreak(self, *args):
- """Handle a SIGBREAK interrupt.
- """
- log.msg("Received SIGBREAK, shutting down.")
- self.callFromThread(self.stop)
-
- def sigTerm(self, *args):
- """Handle a SIGTERM interrupt.
- """
- log.msg("Received SIGTERM, shutting down.")
- self.callFromThread(self.stop)
-
- def disconnectAll(self):
- """Disconnect every reader, and writer in the system.
- """
- selectables = self.removeAll()
- for reader in selectables:
- log.callWithLogger(reader,
- reader.connectionLost,
- failure.Failure(main.CONNECTION_LOST))
-
-
- def iterate(self, delay=0):
- """See twisted.internet.interfaces.IReactorCore.iterate.
- """
- self.runUntilCurrent()
- self.doIteration(delay)
-
-
- def fireSystemEvent(self, eventType):
- """See twisted.internet.interfaces.IReactorCore.fireSystemEvent.
- """
- event = self._eventTriggers.get(eventType)
- if event is not None:
- event.fireEvent()
-
-
- def addSystemEventTrigger(self, _phase, _eventType, _f, *args, **kw):
- """See twisted.internet.interfaces.IReactorCore.addSystemEventTrigger.
- """
- assert callable(_f), "%s is not callable" % _f
- if _eventType not in self._eventTriggers:
- self._eventTriggers[_eventType] = _ThreePhaseEvent()
- return (_eventType, self._eventTriggers[_eventType].addTrigger(
- _phase, _f, *args, **kw))
-
-
- def removeSystemEventTrigger(self, triggerID):
- """See twisted.internet.interfaces.IReactorCore.removeSystemEventTrigger.
- """
- eventType, handle = triggerID
- self._eventTriggers[eventType].removeTrigger(handle)
-
-
- def callWhenRunning(self, _callable, *args, **kw):
- """See twisted.internet.interfaces.IReactorCore.callWhenRunning.
- """
- if self.running:
- _callable(*args, **kw)
- else:
- return self.addSystemEventTrigger('after', 'startup',
- _callable, *args, **kw)
-
- def startRunning(self):
- """
- Method called when reactor starts: do some initialization and fire
- startup events.
-
- Don't call this directly, call reactor.run() instead: it should take
- care of calling this.
- """
- if self.running:
- warnings.warn(
- "Reactor already running! This behavior is deprecated "
- "since Twisted 8.0",
- category=DeprecationWarning, stacklevel=3)
- self.running = True
- self._stopped = False
- threadable.registerAsIOThread()
- self.fireSystemEvent('startup')
-
- # IReactorTime
-
- seconds = staticmethod(runtimeSeconds)
-
- def callLater(self, _seconds, _f, *args, **kw):
- """See twisted.internet.interfaces.IReactorTime.callLater.
- """
- assert callable(_f), "%s is not callable" % _f
- assert sys.maxint >= _seconds >= 0, \
- "%s is not greater than or equal to 0 seconds" % (_seconds,)
- tple = DelayedCall(self.seconds() + _seconds, _f, args, kw,
- self._cancelCallLater,
- self._moveCallLaterSooner,
- seconds=self.seconds)
- self._newTimedCalls.append(tple)
- return tple
-
- def _moveCallLaterSooner(self, tple):
- # Linear time find: slow.
- heap = self._pendingTimedCalls
- try:
- pos = heap.index(tple)
-
- # Move elt up the heap until it rests at the right place.
- elt = heap[pos]
- while pos != 0:
- parent = (pos-1) // 2
- if heap[parent] <= elt:
- break
- # move parent down
- heap[pos] = heap[parent]
- pos = parent
- heap[pos] = elt
- except ValueError:
- # element was not found in heap - oh well...
- pass
-
- def _cancelCallLater(self, tple):
- self._cancellations+=1
-
- def cancelCallLater(self, callID):
- """See twisted.internet.interfaces.IReactorTime.cancelCallLater.
- """
- # DO NOT DELETE THIS - this is documented in Python in a Nutshell, so we
- # we can't get rid of it for a long time.
- warnings.warn("reactor.cancelCallLater(callID) is deprecated - use callID.cancel() instead")
- callID.cancel()
-
- def getDelayedCalls(self):
- """Return all the outstanding delayed calls in the system.
- They are returned in no particular order.
- This method is not efficient -- it is really only meant for
- test cases."""
- return [x for x in (self._pendingTimedCalls + self._newTimedCalls) if not x.cancelled]
-
- def _insertNewDelayedCalls(self):
- for call in self._newTimedCalls:
- if call.cancelled:
- self._cancellations-=1
- else:
- call.activate_delay()
- heappush(self._pendingTimedCalls, call)
- self._newTimedCalls = []
-
- def timeout(self):
- # insert new delayed calls to make sure to include them in timeout value
- self._insertNewDelayedCalls()
-
- if not self._pendingTimedCalls:
- return None
-
- return max(0, self._pendingTimedCalls[0].time - self.seconds())
-
-
- def runUntilCurrent(self):
- """Run all pending timed calls.
- """
- if self.threadCallQueue:
- # Keep track of how many calls we actually make, as we're
- # making them, in case another call is added to the queue
- # while we're in this loop.
- count = 0
- total = len(self.threadCallQueue)
- for (f, a, kw) in self.threadCallQueue:
- try:
- f(*a, **kw)
- except:
- log.err()
- count += 1
- if count == total:
- break
- del self.threadCallQueue[:count]
- if self.threadCallQueue:
- if self.waker:
- self.waker.wakeUp()
-
- # insert new delayed calls now
- self._insertNewDelayedCalls()
-
- now = self.seconds()
- while self._pendingTimedCalls and (self._pendingTimedCalls[0].time <= now):
- call = heappop(self._pendingTimedCalls)
- if call.cancelled:
- self._cancellations-=1
- continue
-
- if call.delayed_time > 0:
- call.activate_delay()
- heappush(self._pendingTimedCalls, call)
- continue
-
- try:
- call.called = 1
- call.func(*call.args, **call.kw)
- except:
- log.deferr()
- if hasattr(call, "creator"):
- e = "\n"
- e += " C: previous exception occurred in " + \
- "a DelayedCall created here:\n"
- e += " C:"
- e += "".join(call.creator).rstrip().replace("\n","\n C:")
- e += "\n"
- log.msg(e)
-
-
- if (self._cancellations > 50 and
- self._cancellations > len(self._pendingTimedCalls) >> 1):
- self._cancellations = 0
- self._pendingTimedCalls = [x for x in self._pendingTimedCalls
- if not x.cancelled]
- heapify(self._pendingTimedCalls)
-
- # IReactorProcess
-
- def _checkProcessArgs(self, args, env):
- """
- Check for valid arguments and environment to spawnProcess.
-
- @return: A two element tuple giving values to use when creating the
- process. The first element of the tuple is a C{list} of C{str}
- giving the values for argv of the child process. The second element
- of the tuple is either C{None} if C{env} was C{None} or a C{dict}
- mapping C{str} environment keys to C{str} environment values.
- """
- # Any unicode string which Python would successfully implicitly
- # encode to a byte string would have worked before these explicit
- # checks were added. Anything which would have failed with a
- # UnicodeEncodeError during that implicit encoding step would have
- # raised an exception in the child process and that would have been
- # a pain in the butt to debug.
- #
- # So, we will explicitly attempt the same encoding which Python
- # would implicitly do later. If it fails, we will report an error
- # without ever spawning a child process. If it succeeds, we'll save
- # the result so that Python doesn't need to do it implicitly later.
- #
- # For any unicode which we can actually encode, we'll also issue a
- # deprecation warning, because no one should be passing unicode here
- # anyway.
- #
- # -exarkun
- defaultEncoding = sys.getdefaultencoding()
-
- # Common check function
- def argChecker(arg):
- """
- Return either a str or None. If the given value is not
- allowable for some reason, None is returned. Otherwise, a
- possibly different object which should be used in place of arg
- is returned. This forces unicode encoding to happen now, rather
- than implicitly later.
- """
- if isinstance(arg, unicode):
- try:
- arg = arg.encode(defaultEncoding)
- except UnicodeEncodeError:
- return None
- warnings.warn(
- "Argument strings and environment keys/values passed to "
- "reactor.spawnProcess should be str, not unicode.",
- category=DeprecationWarning,
- stacklevel=4)
- if isinstance(arg, str) and '\0' not in arg:
- return arg
- return None
-
- # Make a few tests to check input validity
- if not isinstance(args, (tuple, list)):
- raise TypeError("Arguments must be a tuple or list")
-
- outputArgs = []
- for arg in args:
- arg = argChecker(arg)
- if arg is None:
- raise TypeError("Arguments contain a non-string value")
- else:
- outputArgs.append(arg)
-
- outputEnv = None
- if env is not None:
- outputEnv = {}
- for key, val in env.iteritems():
- key = argChecker(key)
- if key is None:
- raise TypeError("Environment contains a non-string key")
- val = argChecker(val)
- if val is None:
- raise TypeError("Environment contains a non-string value")
- outputEnv[key] = val
- return outputArgs, outputEnv
-
- # IReactorThreads
- if platform.supportsThreads():
- threadpool = None
- # ID of the trigger stopping the threadpool
- threadpoolShutdownID = None
-
- def _initThreads(self):
- self.usingThreads = True
- self.resolver = ThreadedResolver(self)
- self.installWaker()
-
- def callFromThread(self, f, *args, **kw):
- """
- See L{twisted.internet.interfaces.IReactorThreads.callFromThread}.
- """
- assert callable(f), "%s is not callable" % (f,)
- # lists are thread-safe in CPython, but not in Jython
- # this is probably a bug in Jython, but until fixed this code
- # won't work in Jython.
- self.threadCallQueue.append((f, args, kw))
- self.wakeUp()
-
- def _initThreadPool(self):
- """
- Create the threadpool accessible with callFromThread.
- """
- from twisted.python import threadpool
- self.threadpool = threadpool.ThreadPool(0, 10, 'twisted.internet.reactor')
- self.callWhenRunning(self.threadpool.start)
- self.threadpoolShutdownID = self.addSystemEventTrigger(
- 'during', 'shutdown', self._stopThreadPool)
-
- def _stopThreadPool(self):
- """
- Stop the reactor threadpool.
- """
- self.threadpoolShutdownID = None
- self.threadpool.stop()
- self.threadpool = None
-
- def callInThread(self, _callable, *args, **kwargs):
- """
- See L{twisted.internet.interfaces.IReactorThreads.callInThread}.
- """
- if self.threadpool is None:
- self._initThreadPool()
- self.threadpool.callInThread(_callable, *args, **kwargs)
-
- def suggestThreadPoolSize(self, size):
- """
- See L{twisted.internet.interfaces.IReactorThreads.suggestThreadPoolSize}.
- """
- if size == 0 and self.threadpool is None:
- return
- if self.threadpool is None:
- self._initThreadPool()
- self.threadpool.adjustPoolsize(maxthreads=size)
- else:
- # This is for signal handlers.
- def callFromThread(self, f, *args, **kw):
- assert callable(f), "%s is not callable" % (f,)
- # See comment in the other callFromThread implementation.
- self.threadCallQueue.append((f, args, kw))
-
-if platform.supportsThreads():
- classImplements(ReactorBase, IReactorThreads)
-
-
-class BaseConnector(styles.Ephemeral):
- """Basic implementation of connector.
-
- State can be: "connecting", "connected", "disconnected"
- """
-
- implements(IConnector)
-
- timeoutID = None
- factoryStarted = 0
-
- def __init__(self, factory, timeout, reactor):
- self.state = "disconnected"
- self.reactor = reactor
- self.factory = factory
- self.timeout = timeout
-
- def disconnect(self):
- """Disconnect whatever our state is."""
- if self.state == 'connecting':
- self.stopConnecting()
- elif self.state == 'connected':
- self.transport.loseConnection()
-
- def connect(self):
- """Start connection to remote server."""
- if self.state != "disconnected":
- raise RuntimeError, "can't connect in this state"
-
- self.state = "connecting"
- if not self.factoryStarted:
- self.factory.doStart()
- self.factoryStarted = 1
- self.transport = transport = self._makeTransport()
- if self.timeout is not None:
- self.timeoutID = self.reactor.callLater(self.timeout, transport.failIfNotConnected, error.TimeoutError())
- self.factory.startedConnecting(self)
-
- def stopConnecting(self):
- """Stop attempting to connect."""
- if self.state != "connecting":
- raise error.NotConnectingError, "we're not trying to connect"
-
- self.state = "disconnected"
- self.transport.failIfNotConnected(error.UserError())
- del self.transport
-
- def cancelTimeout(self):
- if self.timeoutID is not None:
- try:
- self.timeoutID.cancel()
- except ValueError:
- pass
- del self.timeoutID
-
- def buildProtocol(self, addr):
- self.state = "connected"
- self.cancelTimeout()
- return self.factory.buildProtocol(addr)
-
- def connectionFailed(self, reason):
- self.cancelTimeout()
- self.transport = None
- self.state = "disconnected"
- self.factory.clientConnectionFailed(self, reason)
- if self.state == "disconnected":
- # factory hasn't called our connect() method
- self.factory.doStop()
- self.factoryStarted = 0
-
- def connectionLost(self, reason):
- self.state = "disconnected"
- self.factory.clientConnectionLost(self, reason)
- if self.state == "disconnected":
- # factory hasn't called our connect() method
- self.factory.doStop()
- self.factoryStarted = 0
-
- def getDestination(self):
- raise NotImplementedError, "implement in subclasses"
-
-
-class BasePort(abstract.FileDescriptor):
- """Basic implementation of a ListeningPort.
-
- Note: This does not actually implement IListeningPort.
- """
-
- addressFamily = None
- socketType = None
-
- def createInternetSocket(self):
- s = socket.socket(self.addressFamily, self.socketType)
- s.setblocking(0)
- if fcntl and hasattr(fcntl, 'FD_CLOEXEC'):
- old = fcntl.fcntl(s.fileno(), fcntl.F_GETFD)
- fcntl.fcntl(s.fileno(), fcntl.F_SETFD, old | fcntl.FD_CLOEXEC)
- return s
-
-
- def doWrite(self):
- """Raises a RuntimeError"""
- raise RuntimeError, "doWrite called on a %s" % reflect.qual(self.__class__)
-
-
-
-class _SignalReactorMixin:
- """
- Private mixin to manage signals: it installs signal handlers at start time,
- and define run method.
-
- It can only be used mixed in with L{ReactorBase}, and has to be defined
- first in the inheritance (so that method resolution order finds
- startRunning first).
- """
-
- def _handleSignals(self):
- """
- Install the signal handlers for the Twisted event loop.
- """
- try:
- import signal
- except ImportError:
- log.msg("Warning: signal module unavailable -- "
- "not installing signal handlers.")
- return
-
- if signal.getsignal(signal.SIGINT) == signal.default_int_handler:
- # only handle if there isn't already a handler, e.g. for Pdb.
- signal.signal(signal.SIGINT, self.sigInt)
- signal.signal(signal.SIGTERM, self.sigTerm)
-
- # Catch Ctrl-Break in windows
- if hasattr(signal, "SIGBREAK"):
- signal.signal(signal.SIGBREAK, self.sigBreak)
-
- if platformType == 'posix':
- signal.signal(signal.SIGCHLD, self._handleSigchld)
-
-
- def _handleSigchld(self, signum, frame, _threadSupport=platform.supportsThreads()):
- """
- Reap all processes on SIGCHLD.
-
- This gets called on SIGCHLD. We do no processing inside a signal
- handler, as the calls we make here could occur between any two
- python bytecode instructions. Deferring processing to the next
- eventloop round prevents us from violating the state constraints
- of arbitrary classes.
- """
- from twisted.internet.process import reapAllProcesses
- if _threadSupport:
- self.callFromThread(reapAllProcesses)
- else:
- self.callLater(0, reapAllProcesses)
-
-
- def startRunning(self, installSignalHandlers=True):
- """
- Forward call to ReactorBase, arrange for signal handlers to be
- installed if asked.
- """
- if installSignalHandlers:
- # Make sure this happens before after-startup events, since the
- # expectation of after-startup is that the reactor is fully
- # initialized. Don't do it right away for historical reasons
- # (perhaps some before-startup triggers don't want there to be a
- # custom SIGCHLD handler so that they can run child processes with
- # some blocking api).
- self.addSystemEventTrigger(
- 'during', 'startup', self._handleSignals)
- ReactorBase.startRunning(self)
-
-
- def run(self, installSignalHandlers=True):
- self.startRunning(installSignalHandlers=installSignalHandlers)
- self.mainLoop()
-
-
- def mainLoop(self):
- while self.running:
- try:
- while self.running:
- # Advance simulation time in delayed event
- # processors.
- self.runUntilCurrent()
- t2 = self.timeout()
- t = self.running and t2
- self.doIteration(t)
- except:
- log.msg("Unexpected error in main loop.")
- log.err()
- else:
- log.msg('Main loop terminated.')
-
-
-
-__all__ = []
diff --git a/tools/buildbot/pylibs/twisted/internet/cfreactor.py b/tools/buildbot/pylibs/twisted/internet/cfreactor.py
deleted file mode 100644
index 84ccaea..0000000
--- a/tools/buildbot/pylibs/twisted/internet/cfreactor.py
+++ /dev/null
@@ -1,342 +0,0 @@
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-This module provides support for Twisted to interact with CoreFoundation
-CFRunLoops. This includes Cocoa's NSRunLoop.
-
-In order to use this support, simply do the following::
-
- | from twisted.internet import cfreactor
- | cfreactor.install()
-
-Then use the twisted.internet APIs as usual. The other methods here are not
-intended to be called directly under normal use. However, install can take
-a runLoop kwarg, and run will take a withRunLoop arg if you need to explicitly
-pass a CFRunLoop for some reason. Otherwise it will make a pretty good guess
-as to which runLoop you want (the current NSRunLoop if PyObjC is imported,
-otherwise the current CFRunLoop. Either way, if one doesn't exist, it will
-be created).
-
-Maintainer: U{Bob Ippolito<mailto:bob@redivi.com>}
-"""
-
-__all__ = ['install']
-
-import sys
-
-# hints for py2app
-import Carbon.CF
-import traceback
-
-import cfsupport as cf
-
-from zope.interface import implements
-
-from twisted.python import log, threadable, failure
-from twisted.internet.interfaces import IReactorFDSet
-from twisted.internet import posixbase, error
-from weakref import WeakKeyDictionary
-from Foundation import NSRunLoop
-from AppKit import NSApp
-
-# cache two extremely common "failures" without traceback info
-_faildict = {
- error.ConnectionDone: failure.Failure(error.ConnectionDone()),
- error.ConnectionLost: failure.Failure(error.ConnectionLost()),
-}
-
-class SelectableSocketWrapper(object):
- _objCache = WeakKeyDictionary()
-
- cf = None
- def socketWrapperForReactorAndObject(klass, reactor, obj):
- _objCache = klass._objCache
- if obj in _objCache:
- return _objCache[obj]
- v = _objCache[obj] = klass(reactor, obj)
- return v
- socketWrapperForReactorAndObject = classmethod(socketWrapperForReactorAndObject)
-
- def __init__(self, reactor, obj):
- if self.cf:
- raise ValueError, "This socket wrapper is already initialized"
- self.reactor = reactor
- self.obj = obj
- obj._orig_ssw_connectionLost = obj.connectionLost
- obj.connectionLost = self.objConnectionLost
- self.fd = obj.fileno()
- self.writing = False
- self.reading = False
- self.wouldRead = False
- self.wouldWrite = False
- self.cf = cf.PyCFSocket(obj.fileno(), self.doRead, self.doWrite, self.doConnect)
- self.cf.stopWriting()
- reactor.getRunLoop().addSocket(self.cf)
-
- def __repr__(self):
- return 'SSW(fd=%r r=%r w=%r x=%08x o=%08x)' % (self.fd, int(self.reading), int(self.writing), id(self), id(self.obj))
-
- def objConnectionLost(self, *args, **kwargs):
- obj = self.obj
- self.reactor.removeReader(obj)
- self.reactor.removeWriter(obj)
- obj.connectionLost = obj._orig_ssw_connectionLost
- obj.connectionLost(*args, **kwargs)
- try:
- del self._objCache[obj]
- except:
- pass
- self.obj = None
- self.cf = None
-
- def doConnect(self, why):
- pass
-
- def startReading(self):
- self.cf.startReading()
- self.reading = True
- if self.wouldRead:
- if not self.reactor.running:
- self.reactor.callLater(0, self.doRead)
- else:
- self.doRead()
- self.wouldRead = False
- return self
-
- def stopReading(self):
- self.cf.stopReading()
- self.reading = False
- self.wouldRead = False
- return self
-
- def startWriting(self):
- self.cf.startWriting()
- self.writing = True
- if self.wouldWrite:
- if not self.reactor.running:
- self.reactor.callLater(0, self.doWrite)
- else:
- self.doWrite()
- self.wouldWrite = False
- return self
-
- def stopWriting(self):
- self.cf.stopWriting()
- self.writing = False
- self.wouldWrite = False
-
- def _finishReadOrWrite(self, fn, faildict=_faildict):
- try:
- why = fn()
- except:
- why = sys.exc_info()[1]
- log.err()
- if why:
- try:
- f = faildict.get(why.__class__) or failure.Failure(why)
- self.objConnectionLost(f)
- except:
- log.err()
- if self.reactor.running:
- self.reactor.simulate()
-
- def doRead(self):
- obj = self.obj
- if not obj:
- return
- if not self.reading:
- self.wouldRead = True
- if self.reactor.running:
- self.reactor.simulate()
- return
- self._finishReadOrWrite(obj.doRead)
-
- def doWrite(self):
- obj = self.obj
- if not obj:
- return
- if not self.writing:
- self.wouldWrite = True
- if self.reactor.running:
- self.reactor.simulate()
- return
- self._finishReadOrWrite(obj.doWrite)
-
- def __hash__(self):
- return hash(self.fd)
-
-class CFReactor(posixbase.PosixReactorBase):
- implements(IReactorFDSet)
- # how long to poll if we're don't care about signals
- longIntervalOfTime = 60.0
-
- # how long we should poll if we do care about signals
- shortIntervalOfTime = 1.0
-
- # don't set this
- pollInterval = longIntervalOfTime
-
- def __init__(self, runLoop=None):
- self.readers = {}
- self.writers = {}
- self.running = 0
- self.crashing = False
- self._doRunUntilCurrent = True
- self.timer = None
- self.runLoop = None
- self.nsRunLoop = None
- self.didStartRunLoop = False
- if runLoop is not None:
- self.getRunLoop(runLoop)
- posixbase.PosixReactorBase.__init__(self)
-
- def getRunLoop(self, runLoop=None):
- if self.runLoop is None:
- self.nsRunLoop = runLoop or NSRunLoop.currentRunLoop()
- self.runLoop = cf.PyCFRunLoop(self.nsRunLoop.getCFRunLoop())
- return self.runLoop
-
- def addReader(self, reader):
- self.readers[reader] = SelectableSocketWrapper.socketWrapperForReactorAndObject(self, reader).startReading()
-
- def addWriter(self, writer):
- self.writers[writer] = SelectableSocketWrapper.socketWrapperForReactorAndObject(self, writer).startWriting()
-
- def removeReader(self, reader):
- wrapped = self.readers.get(reader, None)
- if wrapped is not None:
- del self.readers[reader]
- wrapped.stopReading()
-
- def removeWriter(self, writer):
- wrapped = self.writers.get(writer, None)
- if wrapped is not None:
- del self.writers[writer]
- wrapped.stopWriting()
-
-
- def getReaders(self):
- return self.readers.keys()
-
-
- def getWriters(self):
- return self.writers.keys()
-
-
- def removeAll(self):
- r = self.readers.keys()
- for s in self.readers.itervalues():
- s.stopReading()
- for s in self.writers.itervalues():
- s.stopWriting()
- self.readers.clear()
- self.writers.clear()
- return r
-
- def run(self, installSignalHandlers=1, withRunLoop=None):
- if self.running:
- raise ValueError, "Reactor already running"
- if installSignalHandlers:
- self.pollInterval = self.shortIntervalOfTime
- runLoop = self.getRunLoop(withRunLoop)
- self._startup()
-
- self.startRunning(installSignalHandlers=installSignalHandlers)
-
- self.running = True
- if NSApp() is None and self.nsRunLoop.currentMode() is None:
- # Most of the time the NSRunLoop will have already started,
- # but in this case it wasn't.
- runLoop.run()
- self.crashing = False
- self.didStartRunLoop = True
-
- def callLater(self, howlong, *args, **kwargs):
- rval = posixbase.PosixReactorBase.callLater(self, howlong, *args, **kwargs)
- if self.timer:
- timeout = self.timeout()
- if timeout is None:
- timeout = howlong
- sleepUntil = cf.now() + min(timeout, howlong)
- if sleepUntil < self.timer.getNextFireDate():
- self.timer.setNextFireDate(sleepUntil)
- else:
- pass
- return rval
-
- def iterate(self, howlong=0.0):
- if self.running:
- raise ValueError, "Can't iterate a running reactor"
- self.runUntilCurrent()
- self.doIteration(howlong)
-
- def doIteration(self, howlong):
- if self.running:
- raise ValueError, "Can't iterate a running reactor"
- howlong = howlong or 0.01
- pi = self.pollInterval
- self.pollInterval = howlong
- self._doRunUntilCurrent = False
- self.run()
- self._doRunUntilCurrent = True
- self.pollInterval = pi
-
- def simulate(self):
- if self.crashing:
- return
- if not self.running:
- raise ValueError, "You can't simulate a stopped reactor"
- if self._doRunUntilCurrent:
- self.runUntilCurrent()
- if self.crashing:
- return
- if self.timer is None:
- return
- nap = self.timeout()
- if nap is None:
- nap = self.pollInterval
- else:
- nap = min(self.pollInterval, nap)
- if self.running:
- self.timer.setNextFireDate(cf.now() + nap)
- if not self._doRunUntilCurrent:
- self.crash()
-
- def _startup(self):
- if self.running:
- raise ValueError, "Can't bootstrap a running reactor"
- self.timer = cf.PyCFRunLoopTimer(cf.now(), self.pollInterval, self.simulate)
- self.runLoop.addTimer(self.timer)
-
- def cleanup(self):
- pass
-
- def sigInt(self, *args):
- self.callLater(0.0, self.stop)
-
- def crash(self):
- if not self.running:
- raise ValueError, "Can't crash a stopped reactor"
- posixbase.PosixReactorBase.crash(self)
- self.crashing = True
- if self.timer is not None:
- self.runLoop.removeTimer(self.timer)
- self.timer = None
- if self.didStartRunLoop:
- self.runLoop.stop()
-
- def stop(self):
- if not self.running:
- raise ValueError, "Can't stop a stopped reactor"
- posixbase.PosixReactorBase.stop(self)
-
-def install(runLoop=None):
- """Configure the twisted mainloop to be run inside CFRunLoop.
- """
- reactor = CFReactor(runLoop=runLoop)
- reactor.addSystemEventTrigger('after', 'shutdown', reactor.cleanup)
- from twisted.internet.main import installReactor
- installReactor(reactor)
- return reactor
diff --git a/tools/buildbot/pylibs/twisted/internet/cfsupport/cfdate.pxi b/tools/buildbot/pylibs/twisted/internet/cfsupport/cfdate.pxi
deleted file mode 100644
index 3a773d7..0000000
--- a/tools/buildbot/pylibs/twisted/internet/cfsupport/cfdate.pxi
+++ /dev/null
@@ -1,2 +0,0 @@
-def now():
- return CFAbsoluteTimeGetCurrent()
diff --git a/tools/buildbot/pylibs/twisted/internet/cfsupport/cfdecl.pxi b/tools/buildbot/pylibs/twisted/internet/cfsupport/cfdecl.pxi
deleted file mode 100644
index 7586001..0000000
--- a/tools/buildbot/pylibs/twisted/internet/cfsupport/cfdecl.pxi
+++ /dev/null
@@ -1,227 +0,0 @@
-cdef extern from "pymactoolbox.h":
- # CFBase
- ctypedef void *CFTypeRef
- ctypedef CFTypeRef CFAllocatorRef
- ctypedef CFTypeRef CFStringRef
- ctypedef CFStringRef CFMutableStringRef
- ctypedef CFTypeRef CFDataRef
- ctypedef CFDataRef CFMutableDataRef
- ctypedef CFTypeRef CFArrayRef
- ctypedef CFArrayRef CFMutableArrayRef
- ctypedef CFTypeRef CFDictionaryRef
- ctypedef CFDictionaryRef CFMutableDictionaryRef
- ctypedef CFTypeRef CFURLRef
-
- ctypedef unsigned short UniChar
- ctypedef int CFIndex
- ctypedef int CFOptionFlags
- ctypedef int Boolean
-
- ctypedef struct CFRange:
- CFIndex location
- CFIndex length
-
- cdef extern CFAllocatorRef kCFAllocatorDefault
- cdef extern CFAllocatorRef kCFAllocatorNull
-
- cdef CFTypeRef CFRetain(CFTypeRef cf)
- cdef void CFRelease(CFTypeRef cf)
- cdef CFIndex CFGetRetainCount(CFTypeRef cf)
- cdef CFStringRef CFCopyDescription(CFTypeRef cf)
- cdef CFRange CFRangeMake(CFIndex location, CFIndex length)
-
- # CFData
- cdef CFDataRef CFDataCreate(CFAllocatorRef allocator, unsigned char *bytes, CFIndex length)
- cdef CFDataRef CFDataCreateWithBytesNoCopy(CFAllocatorRef, unsigned char *bytes, CFIndexLength, CFAllocatorRef bytesDeallocator)
- cdef CFMutableDataRef CFDataCreateMutable(CFAllocatorRef allocator, CFIndex capacity)
- cdef CFMutableDataRef CFDataCreateMutableCopy(CFAllocatorRef allocator, CFIndex capacity, CFDataRef theData)
- cdef CFIndex CFDataGetLength(CFDataRef theData)
- cdef unsigned char *CFDataGetBytePtr(CFDataRef theData)
- cdef unsigned char *CFDataGetMutableBytePtr(CFMutableDataRef theData)
- cdef CFDataGetBytes(CFDataRef theData, CFRange range, unsigned char *buffer)
- cdef CFDataSetLength(CFMutableDataRef theData, CFIndex length)
- cdef CFDataIncreaseLength(CFMutableDataRef theData, CFIndex extraLength)
- cdef CFDataAppendBytes(CFMutableDataRef theData, unsigned char *bytes, CFIndex length)
- cdef CFDataReplaceBytes(CFMutableDataRef theData, CFRange range, unsigned char *newBytes, CFIndex newLength)
- cdef CFDataDeleteBytes(CFMutableDataRef theData, CFRange range)
-
-
- # CFString
-
- ctypedef enum CFStringBuiltInEncodings:
- kCFStringEncodingMacRoman = 0
- kCFStringEncodingWindowsLatin1 = 0x0500
- kCFStringEncodingISOLatin1 = 0x0201
- kCFStringEncodingNextStepLatin = 0x0B01
- kCFStringEncodingASCII = 0x0600
- kCFStringEncodingUnicode = 0x0100
- kCFStringEncodingUTF8 = 0x08000100
- kCFStringEncodingNonLossyASCII = 0x0BFF
- kCFStringEncodingInvalidId = 0xffffffff
- ctypedef unsigned int CFStringEncoding
-
- cdef void CFStringGetCharacters(CFStringRef theString, CFRange range, UniChar *ubuffer)
- cdef CFIndex CFStringGetLength(CFStringRef theString)
- cdef CFStringRef CFStringCreateWithCString(CFAllocatorRef alloc, char *cStr, CFStringEncoding encoding)
- cdef CFStringRef CFStringCreateWithCharacters(CFAllocatorRef alloc, UniChar *chars, CFIndex numChars)
-
- # CFArray
-
- cdef CFIndex CFArrayGetCount(CFArrayRef theArray)
- cdef void *CFArrayGetValueAtIndex(CFArrayRef theArray, CFIndex idx)
- cdef void CFArrayGetValues(CFArrayRef theArray, CFRange range, void **values)
-
- # CFDate
- ctypedef double CFTimeInterval
- ctypedef CFTimeInterval CFAbsoluteTime
-
- cdef CFAbsoluteTime CFAbsoluteTimeGetCurrent()
-
- # CFRunLoop
- ctypedef struct CFRunLoopTimerContext:
- CFIndex version
- void* info
- void *(*retain)(void *info)
- void (*release)(void *info)
- CFStringRef (*copyDescription)(void *info)
-
- ctypedef CFTypeRef CFRunLoopRef
- ctypedef CFTypeRef CFRunLoopTimerRef
- ctypedef CFTypeRef CFRunLoopSourceRef
- ctypedef void (*CFRunLoopTimerCallBack)(CFRunLoopTimerRef timer, void *info)
-
- cdef extern CFStringRef kCFRunLoopCommonModes
-
- cdef CFRunLoopRef CFRunLoopGetCurrent()
- cdef void CFRunLoopRun()
- cdef void CFRunLoopStop(CFRunLoopRef rl)
- cdef void CFRunLoopAddSource(CFRunLoopRef rl, CFRunLoopSourceRef source, CFStringRef mode)
- cdef void CFRunLoopRemoveSource(CFRunLoopRef rl, CFRunLoopSourceRef source, CFStringRef mode)
- cdef CFStringRef CFRunLoopCopyCurrentMode(CFRunLoopRef rl)
-
- cdef void CFRunLoopAddTimer(CFRunLoopRef rl, CFRunLoopTimerRef timer, CFStringRef mode)
- cdef void CFRunLoopRemoveTimer(CFRunLoopRef rl, CFRunLoopTimerRef timer, CFStringRef mode)
-
- cdef CFRunLoopTimerRef CFRunLoopTimerCreate(CFAllocatorRef allocator, CFAbsoluteTime fireDate, CFTimeInterval interval, CFOptionFlags flags, CFIndex order, CFRunLoopTimerCallBack callout, CFRunLoopTimerContext *context)
- cdef CFAbsoluteTime CFRunLoopTimerGetNextFireDate(CFRunLoopTimerRef timer)
- cdef void CFRunLoopTimerSetNextFireDate(CFRunLoopTimerRef timer, CFAbsoluteTime fireDate)
- cdef void CFRunLoopTimerInvalidate(CFRunLoopTimerRef timer)
-
- # CFSocket
- enum kCFSocketFlags:
- kCFSocketAutomaticallyReenableReadCallBack = 1
- kCFSocketAutomaticallyReenableAcceptCallBack = 2
- kCFSocketAutomaticallyReenableDataCallBack = 3
- kCFSocketAutomaticallyReenableWriteCallBack = 8
- kCFSocketCloseOnInvalidate = 128
-
- ctypedef enum CFSocketCallBackType:
- kCFSocketNoCallBack = 0
- kCFSocketReadCallBack = 1
- kCFSocketAcceptCallBack = 2
- kCFSocketDataCallBack = 3
- kCFSocketConnectCallBack = 4
- kCFSocketWriteCallBack = 8
-
- ctypedef struct CFSocketContext:
- CFIndex version
- void *info
- void *(*retain)(void *info)
- void (*release)(void *info)
- CFStringRef (*copyDescription)(void *info)
-
- ctypedef int CFSocketNativeHandle
- ctypedef void *CFSocketRef
- ctypedef void (*CFSocketCallBack)(CFSocketRef s, CFSocketCallBackType _type, CFDataRef address, void *data, void *info)
-
- cdef CFSocketRef CFSocketCreateWithNative(CFAllocatorRef allocator, CFSocketNativeHandle sock, CFOptionFlags callbackTypes, CFSocketCallBack callout, CFSocketContext* context)
- cdef CFSocketNativeHandle CFSocketGetNative(CFSocketRef s)
- cdef CFRunLoopSourceRef CFSocketCreateRunLoopSource(CFAllocatorRef allocator, CFSocketRef s, CFIndex order)
- cdef void CFSocketEnableCallBacks(CFSocketRef s, CFOptionFlags callBackTypes)
- cdef void CFSocketDisableCallBacks(CFSocketRef s, CFOptionFlags callBackTypes)
- cdef CFOptionFlags CFSocketGetSocketFlags(CFSocketRef s)
- cdef void CFSocketSetSocketFlags(CFSocketRef s, CFOptionFlags socketFlags)
- cdef void CFSocketInvalidate(CFSocketRef s)
-
- # CFStream
- ctypedef enum CFStreamErrorDomain:
- kCFStreamErrorDomainCustom = -1
- kCFStreamErrorDomainPOSIX = 1
- kCFStreamErrorDomainMacOSStatus = 2
-
- ctypedef struct CFStreamError:
- CFStreamErrorDomain domain
- int error
-
- cdef object CFObj_New(CFTypeRef)
- cdef int CFObj_Convert(object, CFTypeRef *)
- cdef object CFTypeRefObj_New(CFTypeRef)
- cdef int CFTypeRefObj_Convert(object, CFTypeRef *)
- cdef object CFStringRefObj_New(CFStringRef)
- cdef int CFStringRefObj_Convert(object, CFStringRef *)
- cdef object CFMutableStringRefObj_New(CFMutableStringRef)
- cdef int CFMutableStringRefObj_Convert(object, CFMutableStringRef *)
- cdef object CFArrayRefObj_New(CFArrayRef)
- cdef int CFArrayRefObj_Convert(object, CFArrayRef *)
- cdef object CFMutableArrayRefObj_New(CFMutableArrayRef)
- cdef int CFMutableArrayRefObj_Convert(object, CFMutableArrayRef *)
- cdef object CFDictionaryRefObj_New(CFDictionaryRef)
- cdef int CFDictionaryRefObj_Convert(object, CFDictionaryRef *)
- cdef object CFMutableDictionaryRefObj_New(CFMutableDictionaryRef)
- cdef int CFMutableDictionaryRefObj_Convert(object, CFMutableDictionaryRef *)
- cdef object CFURLRefObj_New(CFURLRef)
- cdef int CFURLRefObj_Convert(object, CFURLRef *)
- cdef int OptionalCFURLRefObj_Convert(object, CFURLRef *)
-
- # CFNetwork
- ctypedef struct CFNetServiceClientContext:
- CFIndex version
- void *info
- void *(*retain)(void *info)
- void (*release)(void *info)
- CFStringRef (*copyDescription)(void *info)
-
- ctypedef enum CFNetServiceBrowserClientCallBackFlags:
- kCFNetServiceFlagMoreComing = 1
- kCFNetServiceFlagIsDomain = 2
- kCFNetServiceFlagIsRegistrationDomain = 4
- kCFNetServiceFlagRemove = 8
-
- ctypedef CFTypeRef CFNetServiceBrowserRef
- ctypedef CFTypeRef CFNetServiceRef
- ctypedef void (*CFNetServiceBrowserClientCallBack)(CFNetServiceBrowserRef browser, CFOptionFlags flags, CFTypeRef domainOrService, CFStreamError* error, void* info)
- ctypedef void (*CFNetServiceClientCallBack)(CFNetServiceRef theService, CFStreamError* error, void* info)
-
- cdef CFNetServiceBrowserRef CFNetServiceBrowserCreate(CFAllocatorRef alloc, CFNetServiceBrowserClientCallBack clientCB, CFNetServiceClientContext* clientContext)
- cdef void CFNetworkServiceBrowserInvalidate(CFNetServiceBrowserRef browser)
- cdef void CFNetServiceBrowserScheduleWithRunLoop(CFNetServiceBrowserRef browser, CFRunLoopRef runLoop, CFStringRef runLoopMode)
- cdef Boolean CFNetServiceBrowserSearchForDomains(CFNetServiceBrowserRef browser, Boolean registrationDomain, CFStreamError* error)
- cdef Boolean CFNetServiceBrowserSearchForServices(CFNetServiceBrowserRef browser, CFStringRef domain, CFStringRef type, CFStreamError* error)
- cdef void CFNetServiceBrowserStopSearch(CFNetServiceBrowserRef browser, CFStreamError* error)
-
- # Call this function to shut down a browser that is running asynchronously.
- # To complete the shutdown, call CFNetServiceBrowserInvalidate followed by CFNetServiceBrowserStopSearch.
- cdef void CFNetServiceBrowserUnscheduleFromRunLoop(CFNetServiceBrowserRef browser, CFRunLoopRef runLoop, CFStringRef runLoopMode)
-
- cdef void CFNetServiceCancel(CFNetServiceRef theService)
- cdef CFNetServiceRef CFNetServiceCreate(CFAllocatorRef alloc, CFStringRef domain, CFStringRef type, CFStringRef name, unsigned int port)
-
- cdef CFArrayRef CFNetServiceGetAddressing(CFNetServiceRef theService)
- cdef CFStringRef CFNetServiceGetDomain(CFNetServiceRef theService)
- cdef CFStringRef CFNetServiceGetName(CFNetServiceRef theService)
- cdef CFStringRef CFNetServiceGetProtocolSpecificInformation(CFNetServiceRef theService)
- cdef CFStringRef CFNetServiceGetType(CFNetServiceRef theService)
- cdef Boolean CFNetServiceRegister(CFNetServiceRef theService, CFStreamError* error)
- cdef Boolean CFNetServiceResolve(CFNetServiceRef theService, CFStreamError* error)
- cdef void CFNetServiceScheduleWithRunLoop(CFNetServiceRef theService, CFRunLoopRef runLoop, CFStringRef runLoopMode)
-
- # For CFNetServices that will operate asynchronously, call this function and then call CFNetServiceScheduleWithRunLoop to schedule the service on a run loop.
- # Then call CFNetServiceRegister or CFNetServiceResolve
- cdef Boolean CFNetServiceSetClient(CFNetServiceRef theService, CFNetServiceClientCallBack clientCB, CFNetServiceClientContext* clientContext)
-
- cdef void CFNetServiceSetProtocolSpecificInformation(CFNetServiceRef theService, CFStringRef theInfo)
-
- # Unschedules the specified service from the specified run loop and mode.
- # Call this function to shut down a service that is running asynchronously.
- # To complete the shutdown, call CFNetServiceSetClient and set clientCB to NULL. Then call CFNetServiceCancel.
- cdef void CFNetServiceUnscheduleFromRunLoop(CFNetServiceRef theService, CFRunLoopRef runLoop, CFStringRef runLoopMode)
diff --git a/tools/buildbot/pylibs/twisted/internet/cfsupport/cfrunloop.pxi b/tools/buildbot/pylibs/twisted/internet/cfsupport/cfrunloop.pxi
deleted file mode 100644
index 8cd40a8..0000000
--- a/tools/buildbot/pylibs/twisted/internet/cfsupport/cfrunloop.pxi
+++ /dev/null
@@ -1,104 +0,0 @@
-import traceback
-
-# possibly figure out how to subclass these or something
-
-cdef class PyCFRunLoopTimer:
- cdef CFRunLoopTimerRef cf
- cdef public object callout
- cdef CFRunLoopTimerContext context
-
- def __new__(self, double fireDate, double interval, callout):
- self.callout = callout
- self.context.version = 0
- self.context.info = <void *>self
- self.context.retain = NULL
- self.context.release = NULL
- self.context.copyDescription = NULL
- self.cf = CFRunLoopTimerCreate(kCFAllocatorDefault, fireDate, interval, 0, 0, <CFRunLoopTimerCallBack>&gilRunLoopTimerCallBack, &self.context)
- if self.cf == NULL:
- raise ValueError("Invalid Socket")
-
- def getNextFireDate(self):
- return CFRunLoopTimerGetNextFireDate(self.cf)
-
- def setNextFireDate(self, double fireDate):
- CFRunLoopTimerSetNextFireDate(self.cf, fireDate)
-
- def invalidate(self):
- CFRunLoopTimerInvalidate(self.cf)
-
- def __dealloc__(self):
- if self.cf != NULL:
- CFRelease(self.cf)
-
-cdef void runLoopTimerCallBack(CFRunLoopTimerRef timer, void *info):
- cdef PyCFRunLoopTimer obj
- obj = <PyCFRunLoopTimer>info
- try:
- if obj.callout:
- obj.callout()
- except:
- traceback.print_exc()
-
-cdef void gilRunLoopTimerCallBack(CFRunLoopTimerRef timer, void *info):
- cdef PyGILState_STATE gil
- gil = PyGILState_Ensure()
- runLoopTimerCallBack(timer, info)
- PyGILState_Release(gil)
-
-cdef class PyCFRunLoop:
- cdef public object cf
-
- def __new__(self, runLoop=None):
- cdef CFTypeRef _runLoop
- if runLoop is None:
- _runLoop = CFRunLoopGetCurrent()
- else:
- if CFObj_Convert(runLoop, &_runLoop) == 0:
- raise
- #return -1
- # this is going to leak a reference
- self.cf = CFObj_New(CFRetain(_runLoop))
-
- def run(self):
- CFRunLoopRun()
-
- def stop(self):
- cdef CFTypeRef _runLoop
- if CFObj_Convert(self.cf, &_runLoop) == 0:
- raise ValueError, "CFRunLoopReference is invalid"
- CFRunLoopStop(_runLoop)
-
- def currentMode(self):
- cdef CFTypeRef _currentMode
- cdef CFTypeRef _runLoop
- if CFObj_Convert(self.cf, &_runLoop) == 0:
- raise ValueError, "CFRunLoopReference is invalid"
- _currentMode = CFRunLoopCopyCurrentMode(_runLoop)
- if _currentMode == NULL:
- return None
- return CFObj_New(_currentMode)
-
- def addSocket(self, PyCFSocket socket not None):
- cdef CFTypeRef _runLoop
- if CFObj_Convert(self.cf, &_runLoop) == 0:
- raise ValueError, "CFRunLoopReference is invalid"
- CFRunLoopAddSource(_runLoop, socket.source, kCFRunLoopCommonModes)
-
- def removeSocket(self, PyCFSocket socket not None):
- cdef CFTypeRef _runLoop
- if CFObj_Convert(self.cf, &_runLoop) == 0:
- raise ValueError, "CFRunLoopReference is invalid"
- CFRunLoopRemoveSource(_runLoop, socket.source, kCFRunLoopCommonModes)
-
- def addTimer(self, PyCFRunLoopTimer timer not None):
- cdef CFTypeRef _runLoop
- if CFObj_Convert(self.cf, &_runLoop) == 0:
- raise ValueError, "CFRunLoopReference is invalid"
- CFRunLoopAddTimer(_runLoop, timer.cf, kCFRunLoopCommonModes)
-
- def removeTimer(self, PyCFRunLoopTimer timer not None):
- cdef CFTypeRef _runLoop
- if CFObj_Convert(self.cf, &_runLoop) == 0:
- raise ValueError, "CFRunLoopReference is invalid"
- CFRunLoopRemoveTimer(_runLoop, timer.cf, kCFRunLoopCommonModes)
diff --git a/tools/buildbot/pylibs/twisted/internet/cfsupport/cfsocket.pxi b/tools/buildbot/pylibs/twisted/internet/cfsupport/cfsocket.pxi
deleted file mode 100644
index b87cfb6..0000000
--- a/tools/buildbot/pylibs/twisted/internet/cfsupport/cfsocket.pxi
+++ /dev/null
@@ -1,111 +0,0 @@
-import traceback
-
-cdef class PyCFSocket
-
-cdef void socketCallBack(CFSocketRef s, CFSocketCallBackType _type, CFDataRef address, void *data, void *info):
- cdef PyCFSocket socket
- cdef int res
- cdef int mask
- socket = (<PyCFSocket>info)
- #print "fileno = %r" % (socket.fileno,)
- try:
- if _type == kCFSocketReadCallBack:
- if socket.readcallback:
- socket.readcallback()
- elif _type == kCFSocketWriteCallBack:
- if socket.writecallback:
- socket.writecallback()
- elif _type == kCFSocketConnectCallBack:
- if data == NULL:
- res = 0
- else:
- res = (<int*>data)[0]
- if socket.connectcallback:
- socket.connectcallback(res)
- except:
- traceback.print_exc()
-
-cdef void gilSocketCallBack(CFSocketRef s, CFSocketCallBackType _type, CFDataRef address, void *data, void *info):
- cdef PyGILState_STATE gil
- gil = PyGILState_Ensure()
- socketCallBack(s, _type, address, data, info)
- PyGILState_Release(gil)
-
-cdef class PyCFSocket:
- cdef public object readcallback
- cdef public object writecallback
- cdef public object connectcallback
- cdef public object reading
- cdef public object writing
- cdef CFSocketRef cf
- cdef CFRunLoopSourceRef source
- cdef readonly CFSocketNativeHandle fileno
- cdef CFSocketContext context
-
- def __new__(self, CFSocketNativeHandle fileno, readcallback=None, writecallback=None, connectcallback=None):
- #print "new socket %r" % (fileno,)
- self.fileno = fileno
- self.readcallback = readcallback
- self.writecallback = writecallback
- self.connectcallback = connectcallback
- self.context.version = 0
- self.context.info = <void *>self
- self.context.retain = NULL
- self.context.release = NULL
- self.context.copyDescription = NULL
- self.reading = False
- self.writing = False
- self.cf = CFSocketCreateWithNative(kCFAllocatorDefault, fileno, kCFSocketConnectCallBack | kCFSocketReadCallBack | kCFSocketWriteCallBack, <CFSocketCallBack>&gilSocketCallBack, &self.context)
- if self.cf == NULL:
- raise ValueError("Invalid Socket")
- self.source = CFSocketCreateRunLoopSource(kCFAllocatorDefault, self.cf, 10000)
- if self.source == NULL:
- raise ValueError("Couldn't create runloop source")
- #print "made new socket"
-
- def update(self):
- cdef int mask
- cdef int offmask
- cdef int automask
- mask = kCFSocketConnectCallBack | kCFSocketAcceptCallBack
- offmask = 0
- automask = kCFSocketAutomaticallyReenableAcceptCallBack
- if self.reading:
- mask = mask | kCFSocketReadCallBack
- automask = automask | kCFSocketAutomaticallyReenableReadCallBack
- else:
- offmask = offmask | kCFSocketReadCallBack
- if self.writing:
- mask = mask | kCFSocketWriteCallBack
- automask = automask | kCFSocketAutomaticallyReenableWriteCallBack
- else:
- offmask = offmask | kCFSocketWriteCallBack
- CFSocketDisableCallBacks(self.cf, offmask)
- CFSocketEnableCallBacks(self.cf, mask)
- CFSocketSetSocketFlags(self.cf, automask)
-
-
- def startReading(self):
- self.reading = True
- self.update()
-
- def stopReading(self):
- self.reading = False
- self.update()
-
- def startWriting(self):
- self.writing = True
- self.update()
-
- def stopWriting(self):
- self.writing = False
- self.update()
-
- def __dealloc__(self):
- #print "PyCFSocket(%r).__dealloc__()" % (self.fileno,)
- if self.source != NULL:
- CFRelease(self.source)
- if self.cf != NULL:
- CFSocketInvalidate(self.cf)
- CFRelease(self.cf)
- #print "__dealloc__()"
diff --git a/tools/buildbot/pylibs/twisted/internet/cfsupport/cfsupport.c b/tools/buildbot/pylibs/twisted/internet/cfsupport/cfsupport.c
deleted file mode 100644
index eb1b371..0000000
--- a/tools/buildbot/pylibs/twisted/internet/cfsupport/cfsupport.c
+++ /dev/null
@@ -1,2136 +0,0 @@
-/* Generated by Pyrex 0.9.3 on Sat Mar 12 04:43:18 2005 */
-
-#include "Python.h"
-#include "structmember.h"
-#ifndef PY_LONG_LONG
- #define PY_LONG_LONG LONG_LONG
-#endif
-#include "pymactoolbox.h"
-
-
-typedef struct {PyObject **p; char *s;} __Pyx_InternTabEntry; /*proto*/
-typedef struct {PyObject **p; char *s; long n;} __Pyx_StringTabEntry; /*proto*/
-static PyObject *__Pyx_UnpackItem(PyObject *, int); /*proto*/
-static int __Pyx_EndUnpack(PyObject *, int); /*proto*/
-static int __Pyx_PrintItem(PyObject *); /*proto*/
-static int __Pyx_PrintNewline(void); /*proto*/
-static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb); /*proto*/
-static void __Pyx_ReRaise(void); /*proto*/
-static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list); /*proto*/
-static PyObject *__Pyx_GetExcValue(void); /*proto*/
-static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, char *name); /*proto*/
-static int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/
-static int __Pyx_GetStarArgs(PyObject **args, PyObject **kwds, char *kwd_list[], int nargs, PyObject **args2, PyObject **kwds2); /*proto*/
-static void __Pyx_WriteUnraisable(char *name); /*proto*/
-static void __Pyx_AddTraceback(char *funcname); /*proto*/
-static PyTypeObject *__Pyx_ImportType(char *module_name, char *class_name, long size); /*proto*/
-static int __Pyx_SetVtable(PyObject *dict, void *vtable); /*proto*/
-static int __Pyx_GetVtable(PyObject *dict, void *vtabptr); /*proto*/
-static PyObject *__Pyx_CreateClass(PyObject *bases, PyObject *dict, PyObject *name, char *modname); /*proto*/
-static int __Pyx_InternStrings(__Pyx_InternTabEntry *t); /*proto*/
-static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/
-static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/
-
-static PyObject *__pyx_m;
-static PyObject *__pyx_b;
-static int __pyx_lineno;
-static char *__pyx_filename;
-staticforward char **__pyx_f;
-
-/* Declarations from cfsupport */
-
-staticforward PyTypeObject __pyx_type_9cfsupport_PyCFSocket;
-
-struct __pyx_obj_9cfsupport_PyCFSocket {
- PyObject_HEAD
- PyObject *readcallback;
- PyObject *writecallback;
- PyObject *connectcallback;
- PyObject *reading;
- PyObject *writing;
- CFSocketRef cf;
- CFRunLoopSourceRef source;
- CFSocketNativeHandle fileno;
- CFSocketContext context;
-};
-
-staticforward PyTypeObject __pyx_type_9cfsupport_PyCFRunLoopTimer;
-
-struct __pyx_obj_9cfsupport_PyCFRunLoopTimer {
- PyObject_HEAD
- CFRunLoopTimerRef cf;
- PyObject *callout;
- CFRunLoopTimerContext context;
-};
-
-staticforward PyTypeObject __pyx_type_9cfsupport_PyCFRunLoop;
-
-struct __pyx_obj_9cfsupport_PyCFRunLoop {
- PyObject_HEAD
- PyObject *cf;
-};
-
-static PyTypeObject *__pyx_ptype_9cfsupport_PyCFSocket = 0;
-static PyTypeObject *__pyx_ptype_9cfsupport_PyCFRunLoopTimer = 0;
-static PyTypeObject *__pyx_ptype_9cfsupport_PyCFRunLoop = 0;
-static PyObject *__pyx_k2;
-static PyObject *__pyx_k3;
-static PyObject *__pyx_k4;
-static PyObject *__pyx_k6;
-static void (__pyx_f_9cfsupport_socketCallBack(CFSocketRef ,CFSocketCallBackType ,CFDataRef ,void (*),void (*))); /*proto*/
-static void (__pyx_f_9cfsupport_gilSocketCallBack(CFSocketRef ,CFSocketCallBackType ,CFDataRef ,void (*),void (*))); /*proto*/
-static void (__pyx_f_9cfsupport_runLoopTimerCallBack(CFRunLoopTimerRef ,void (*))); /*proto*/
-static void (__pyx_f_9cfsupport_gilRunLoopTimerCallBack(CFRunLoopTimerRef ,void (*))); /*proto*/
-
-/* Implementation of cfsupport */
-
-static char (__pyx_k7[]) = "0.4";
-
-static PyObject *__pyx_n_now;
-static PyObject *__pyx_n_traceback;
-static PyObject *__pyx_n___version__;
-
-static PyObject *__pyx_k7p;
-
-static PyObject *__pyx_f_9cfsupport_now(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static PyObject *__pyx_f_9cfsupport_now(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- PyObject *__pyx_r;
- PyObject *__pyx_1 = 0;
- static char *__pyx_argnames[] = {0};
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "", __pyx_argnames)) return 0;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfdate.pxi":2 */
- __pyx_1 = PyFloat_FromDouble(CFAbsoluteTimeGetCurrent()); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; goto __pyx_L1;}
- __pyx_r = __pyx_1;
- __pyx_1 = 0;
- goto __pyx_L0;
-
- __pyx_r = Py_None; Py_INCREF(__pyx_r);
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_1);
- __Pyx_AddTraceback("cfsupport.now");
- __pyx_r = 0;
- __pyx_L0:;
- return __pyx_r;
-}
-
-static PyObject *__pyx_n_print_exc;
-
-static void __pyx_f_9cfsupport_socketCallBack(CFSocketRef __pyx_v_s,CFSocketCallBackType __pyx_v__type,CFDataRef __pyx_v_address,void (*__pyx_v_data),void (*__pyx_v_info)) {
- struct __pyx_obj_9cfsupport_PyCFSocket *__pyx_v_socket;
- int __pyx_v_res;
- int __pyx_v_mask;
- PyObject *__pyx_1 = 0;
- int __pyx_2;
- PyObject *__pyx_3 = 0;
- PyObject *__pyx_4 = 0;
- ((PyObject*)__pyx_v_socket) = Py_None; Py_INCREF(((PyObject*)__pyx_v_socket));
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":9 */
- __pyx_1 = (PyObject *)__pyx_v_info;
- Py_INCREF(__pyx_1);
- Py_DECREF(((PyObject *)__pyx_v_socket));
- ((PyObject *)__pyx_v_socket) = __pyx_1;
- __pyx_1 = 0;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":11 */
- /*try:*/ {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":12 */
- __pyx_2 = (__pyx_v__type == kCFSocketReadCallBack);
- if (__pyx_2) {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":13 */
- __pyx_2 = PyObject_IsTrue(__pyx_v_socket->readcallback); if (__pyx_2 < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 13; goto __pyx_L2;}
- if (__pyx_2) {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":14 */
- __pyx_1 = PyTuple_New(0); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 14; goto __pyx_L2;}
- __pyx_3 = PyObject_CallObject(__pyx_v_socket->readcallback, __pyx_1); if (!__pyx_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 14; goto __pyx_L2;}
- Py_DECREF(__pyx_1); __pyx_1 = 0;
- Py_DECREF(__pyx_3); __pyx_3 = 0;
- goto __pyx_L5;
- }
- __pyx_L5:;
- goto __pyx_L4;
- }
- __pyx_2 = (__pyx_v__type == kCFSocketWriteCallBack);
- if (__pyx_2) {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":16 */
- __pyx_2 = PyObject_IsTrue(__pyx_v_socket->writecallback); if (__pyx_2 < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 16; goto __pyx_L2;}
- if (__pyx_2) {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":17 */
- __pyx_1 = PyTuple_New(0); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 17; goto __pyx_L2;}
- __pyx_3 = PyObject_CallObject(__pyx_v_socket->writecallback, __pyx_1); if (!__pyx_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 17; goto __pyx_L2;}
- Py_DECREF(__pyx_1); __pyx_1 = 0;
- Py_DECREF(__pyx_3); __pyx_3 = 0;
- goto __pyx_L6;
- }
- __pyx_L6:;
- goto __pyx_L4;
- }
- __pyx_2 = (__pyx_v__type == kCFSocketConnectCallBack);
- if (__pyx_2) {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":19 */
- __pyx_2 = (__pyx_v_data == 0);
- if (__pyx_2) {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":20 */
- __pyx_v_res = 0;
- goto __pyx_L7;
- }
- /*else*/ {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":22 */
- __pyx_v_res = (((int (*))__pyx_v_data)[0]);
- }
- __pyx_L7:;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":23 */
- __pyx_2 = PyObject_IsTrue(__pyx_v_socket->connectcallback); if (__pyx_2 < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 23; goto __pyx_L2;}
- if (__pyx_2) {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":24 */
- __pyx_1 = PyInt_FromLong(__pyx_v_res); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 24; goto __pyx_L2;}
- __pyx_3 = PyTuple_New(1); if (!__pyx_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 24; goto __pyx_L2;}
- PyTuple_SET_ITEM(__pyx_3, 0, __pyx_1);
- __pyx_1 = 0;
- __pyx_1 = PyObject_CallObject(__pyx_v_socket->connectcallback, __pyx_3); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 24; goto __pyx_L2;}
- Py_DECREF(__pyx_3); __pyx_3 = 0;
- Py_DECREF(__pyx_1); __pyx_1 = 0;
- goto __pyx_L8;
- }
- __pyx_L8:;
- goto __pyx_L4;
- }
- __pyx_L4:;
- }
- goto __pyx_L3;
- __pyx_L2:;
- Py_XDECREF(__pyx_3); __pyx_3 = 0;
- Py_XDECREF(__pyx_1); __pyx_1 = 0;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":25 */
- /*except:*/ {
- __Pyx_AddTraceback("cfsupport.socketCallBack");
- __pyx_3 = __Pyx_GetExcValue(); if (!__pyx_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 25; goto __pyx_L1;}
- Py_DECREF(__pyx_3); __pyx_3 = 0;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":26 */
- __pyx_1 = __Pyx_GetName(__pyx_m, __pyx_n_traceback); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 26; goto __pyx_L1;}
- __pyx_3 = PyObject_GetAttr(__pyx_1, __pyx_n_print_exc); if (!__pyx_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 26; goto __pyx_L1;}
- Py_DECREF(__pyx_1); __pyx_1 = 0;
- __pyx_1 = PyTuple_New(0); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 26; goto __pyx_L1;}
- __pyx_4 = PyObject_CallObject(__pyx_3, __pyx_1); if (!__pyx_4) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 26; goto __pyx_L1;}
- Py_DECREF(__pyx_3); __pyx_3 = 0;
- Py_DECREF(__pyx_1); __pyx_1 = 0;
- Py_DECREF(__pyx_4); __pyx_4 = 0;
- goto __pyx_L3;
- }
- __pyx_L3:;
-
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_1);
- Py_XDECREF(__pyx_3);
- Py_XDECREF(__pyx_4);
- __Pyx_WriteUnraisable("cfsupport.socketCallBack");
- __pyx_L0:;
- Py_DECREF(__pyx_v_socket);
-}
-
-static void __pyx_f_9cfsupport_gilSocketCallBack(CFSocketRef __pyx_v_s,CFSocketCallBackType __pyx_v__type,CFDataRef __pyx_v_address,void (*__pyx_v_data),void (*__pyx_v_info)) {
- PyGILState_STATE __pyx_v_gil;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":30 */
- __pyx_v_gil = PyGILState_Ensure();
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":31 */
- __pyx_f_9cfsupport_socketCallBack(__pyx_v_s,__pyx_v__type,__pyx_v_address,__pyx_v_data,__pyx_v_info);
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":32 */
- PyGILState_Release(__pyx_v_gil);
-
- goto __pyx_L0;
- __pyx_L1:;
- __Pyx_WriteUnraisable("cfsupport.gilSocketCallBack");
- __pyx_L0:;
-}
-
-static PyObject *__pyx_n_False;
-static PyObject *__pyx_n_ValueError;
-
-static PyObject *__pyx_k8p;
-static PyObject *__pyx_k9p;
-
-static char (__pyx_k8[]) = "Invalid Socket";
-static char (__pyx_k9[]) = "Couldn't create runloop source";
-
-static int __pyx_f_9cfsupport_10PyCFSocket___new__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static int __pyx_f_9cfsupport_10PyCFSocket___new__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- int __pyx_v_fileno;
- PyObject *__pyx_v_readcallback = 0;
- PyObject *__pyx_v_writecallback = 0;
- PyObject *__pyx_v_connectcallback = 0;
- int __pyx_r;
- PyObject *__pyx_1 = 0;
- int __pyx_2;
- PyObject *__pyx_3 = 0;
- PyObject *__pyx_4 = 0;
- static char *__pyx_argnames[] = {"fileno","readcallback","writecallback","connectcallback",0};
- __pyx_v_readcallback = __pyx_k2;
- __pyx_v_writecallback = __pyx_k3;
- __pyx_v_connectcallback = __pyx_k4;
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "i|OOO", __pyx_argnames, &__pyx_v_fileno, &__pyx_v_readcallback, &__pyx_v_writecallback, &__pyx_v_connectcallback)) return -1;
- Py_INCREF(__pyx_v_self);
- Py_INCREF(__pyx_v_readcallback);
- Py_INCREF(__pyx_v_writecallback);
- Py_INCREF(__pyx_v_connectcallback);
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":47 */
- ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->fileno = __pyx_v_fileno;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":48 */
- Py_INCREF(__pyx_v_readcallback);
- Py_DECREF(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->readcallback);
- ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->readcallback = __pyx_v_readcallback;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":49 */
- Py_INCREF(__pyx_v_writecallback);
- Py_DECREF(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->writecallback);
- ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->writecallback = __pyx_v_writecallback;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":50 */
- Py_INCREF(__pyx_v_connectcallback);
- Py_DECREF(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->connectcallback);
- ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->connectcallback = __pyx_v_connectcallback;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":51 */
- ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->context.version = 0;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":52 */
- ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->context.info = ((void (*))__pyx_v_self);
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":53 */
- ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->context.retain = 0;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":54 */
- ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->context.release = 0;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":55 */
- ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->context.copyDescription = 0;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":56 */
- __pyx_1 = __Pyx_GetName(__pyx_b, __pyx_n_False); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 56; goto __pyx_L1;}
- Py_DECREF(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->reading);
- ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->reading = __pyx_1;
- __pyx_1 = 0;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":57 */
- __pyx_1 = __Pyx_GetName(__pyx_b, __pyx_n_False); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 57; goto __pyx_L1;}
- Py_DECREF(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->writing);
- ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->writing = __pyx_1;
- __pyx_1 = 0;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":58 */
- ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->cf = CFSocketCreateWithNative(kCFAllocatorDefault,__pyx_v_fileno,((kCFSocketConnectCallBack | kCFSocketReadCallBack) | kCFSocketWriteCallBack),((CFSocketCallBack )(&__pyx_f_9cfsupport_gilSocketCallBack)),(&((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->context));
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":59 */
- __pyx_2 = (((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->cf == 0);
- if (__pyx_2) {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":60 */
- __pyx_1 = __Pyx_GetName(__pyx_b, __pyx_n_ValueError); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 60; goto __pyx_L1;}
- __pyx_3 = PyTuple_New(1); if (!__pyx_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 60; goto __pyx_L1;}
- Py_INCREF(__pyx_k8p);
- PyTuple_SET_ITEM(__pyx_3, 0, __pyx_k8p);
- __pyx_4 = PyObject_CallObject(__pyx_1, __pyx_3); if (!__pyx_4) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 60; goto __pyx_L1;}
- Py_DECREF(__pyx_1); __pyx_1 = 0;
- Py_DECREF(__pyx_3); __pyx_3 = 0;
- __Pyx_Raise(__pyx_4, 0, 0);
- Py_DECREF(__pyx_4); __pyx_4 = 0;
- {__pyx_filename = __pyx_f[1]; __pyx_lineno = 60; goto __pyx_L1;}
- goto __pyx_L2;
- }
- __pyx_L2:;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":61 */
- ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->source = CFSocketCreateRunLoopSource(kCFAllocatorDefault,((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->cf,10000);
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":62 */
- __pyx_2 = (((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->source == 0);
- if (__pyx_2) {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":63 */
- __pyx_1 = __Pyx_GetName(__pyx_b, __pyx_n_ValueError); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 63; goto __pyx_L1;}
- __pyx_3 = PyTuple_New(1); if (!__pyx_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 63; goto __pyx_L1;}
- Py_INCREF(__pyx_k9p);
- PyTuple_SET_ITEM(__pyx_3, 0, __pyx_k9p);
- __pyx_4 = PyObject_CallObject(__pyx_1, __pyx_3); if (!__pyx_4) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 63; goto __pyx_L1;}
- Py_DECREF(__pyx_1); __pyx_1 = 0;
- Py_DECREF(__pyx_3); __pyx_3 = 0;
- __Pyx_Raise(__pyx_4, 0, 0);
- Py_DECREF(__pyx_4); __pyx_4 = 0;
- {__pyx_filename = __pyx_f[1]; __pyx_lineno = 63; goto __pyx_L1;}
- goto __pyx_L3;
- }
- __pyx_L3:;
-
- __pyx_r = 0;
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_1);
- Py_XDECREF(__pyx_3);
- Py_XDECREF(__pyx_4);
- __Pyx_AddTraceback("cfsupport.PyCFSocket.__new__");
- __pyx_r = -1;
- __pyx_L0:;
- Py_DECREF(__pyx_v_self);
- Py_DECREF(__pyx_v_readcallback);
- Py_DECREF(__pyx_v_writecallback);
- Py_DECREF(__pyx_v_connectcallback);
- return __pyx_r;
-}
-
-static PyObject *__pyx_f_9cfsupport_10PyCFSocket_update(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static PyObject *__pyx_f_9cfsupport_10PyCFSocket_update(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- int __pyx_v_mask;
- int __pyx_v_offmask;
- int __pyx_v_automask;
- PyObject *__pyx_r;
- int __pyx_1;
- static char *__pyx_argnames[] = {0};
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "", __pyx_argnames)) return 0;
- Py_INCREF(__pyx_v_self);
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":70 */
- __pyx_v_mask = (kCFSocketConnectCallBack | kCFSocketAcceptCallBack);
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":71 */
- __pyx_v_offmask = 0;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":72 */
- __pyx_v_automask = kCFSocketAutomaticallyReenableAcceptCallBack;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":73 */
- __pyx_1 = PyObject_IsTrue(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->reading); if (__pyx_1 < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 73; goto __pyx_L1;}
- if (__pyx_1) {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":74 */
- __pyx_v_mask = (__pyx_v_mask | kCFSocketReadCallBack);
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":75 */
- __pyx_v_automask = (__pyx_v_automask | kCFSocketAutomaticallyReenableReadCallBack);
- goto __pyx_L2;
- }
- /*else*/ {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":77 */
- __pyx_v_offmask = (__pyx_v_offmask | kCFSocketReadCallBack);
- }
- __pyx_L2:;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":78 */
- __pyx_1 = PyObject_IsTrue(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->writing); if (__pyx_1 < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 78; goto __pyx_L1;}
- if (__pyx_1) {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":79 */
- __pyx_v_mask = (__pyx_v_mask | kCFSocketWriteCallBack);
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":80 */
- __pyx_v_automask = (__pyx_v_automask | kCFSocketAutomaticallyReenableWriteCallBack);
- goto __pyx_L3;
- }
- /*else*/ {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":82 */
- __pyx_v_offmask = (__pyx_v_offmask | kCFSocketWriteCallBack);
- }
- __pyx_L3:;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":83 */
- CFSocketDisableCallBacks(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->cf,__pyx_v_offmask);
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":84 */
- CFSocketEnableCallBacks(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->cf,__pyx_v_mask);
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":85 */
- CFSocketSetSocketFlags(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->cf,__pyx_v_automask);
-
- __pyx_r = Py_None; Py_INCREF(__pyx_r);
- goto __pyx_L0;
- __pyx_L1:;
- __Pyx_AddTraceback("cfsupport.PyCFSocket.update");
- __pyx_r = 0;
- __pyx_L0:;
- Py_DECREF(__pyx_v_self);
- return __pyx_r;
-}
-
-static PyObject *__pyx_n_True;
-static PyObject *__pyx_n_update;
-
-static PyObject *__pyx_f_9cfsupport_10PyCFSocket_startReading(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static PyObject *__pyx_f_9cfsupport_10PyCFSocket_startReading(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- PyObject *__pyx_r;
- PyObject *__pyx_1 = 0;
- PyObject *__pyx_2 = 0;
- PyObject *__pyx_3 = 0;
- static char *__pyx_argnames[] = {0};
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "", __pyx_argnames)) return 0;
- Py_INCREF(__pyx_v_self);
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":89 */
- __pyx_1 = __Pyx_GetName(__pyx_b, __pyx_n_True); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 89; goto __pyx_L1;}
- Py_DECREF(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->reading);
- ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->reading = __pyx_1;
- __pyx_1 = 0;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":90 */
- __pyx_1 = PyObject_GetAttr(__pyx_v_self, __pyx_n_update); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 90; goto __pyx_L1;}
- __pyx_2 = PyTuple_New(0); if (!__pyx_2) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 90; goto __pyx_L1;}
- __pyx_3 = PyObject_CallObject(__pyx_1, __pyx_2); if (!__pyx_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 90; goto __pyx_L1;}
- Py_DECREF(__pyx_1); __pyx_1 = 0;
- Py_DECREF(__pyx_2); __pyx_2 = 0;
- Py_DECREF(__pyx_3); __pyx_3 = 0;
-
- __pyx_r = Py_None; Py_INCREF(__pyx_r);
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_1);
- Py_XDECREF(__pyx_2);
- Py_XDECREF(__pyx_3);
- __Pyx_AddTraceback("cfsupport.PyCFSocket.startReading");
- __pyx_r = 0;
- __pyx_L0:;
- Py_DECREF(__pyx_v_self);
- return __pyx_r;
-}
-
-static PyObject *__pyx_f_9cfsupport_10PyCFSocket_stopReading(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static PyObject *__pyx_f_9cfsupport_10PyCFSocket_stopReading(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- PyObject *__pyx_r;
- PyObject *__pyx_1 = 0;
- PyObject *__pyx_2 = 0;
- PyObject *__pyx_3 = 0;
- static char *__pyx_argnames[] = {0};
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "", __pyx_argnames)) return 0;
- Py_INCREF(__pyx_v_self);
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":93 */
- __pyx_1 = __Pyx_GetName(__pyx_b, __pyx_n_False); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 93; goto __pyx_L1;}
- Py_DECREF(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->reading);
- ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->reading = __pyx_1;
- __pyx_1 = 0;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":94 */
- __pyx_1 = PyObject_GetAttr(__pyx_v_self, __pyx_n_update); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 94; goto __pyx_L1;}
- __pyx_2 = PyTuple_New(0); if (!__pyx_2) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 94; goto __pyx_L1;}
- __pyx_3 = PyObject_CallObject(__pyx_1, __pyx_2); if (!__pyx_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 94; goto __pyx_L1;}
- Py_DECREF(__pyx_1); __pyx_1 = 0;
- Py_DECREF(__pyx_2); __pyx_2 = 0;
- Py_DECREF(__pyx_3); __pyx_3 = 0;
-
- __pyx_r = Py_None; Py_INCREF(__pyx_r);
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_1);
- Py_XDECREF(__pyx_2);
- Py_XDECREF(__pyx_3);
- __Pyx_AddTraceback("cfsupport.PyCFSocket.stopReading");
- __pyx_r = 0;
- __pyx_L0:;
- Py_DECREF(__pyx_v_self);
- return __pyx_r;
-}
-
-static PyObject *__pyx_f_9cfsupport_10PyCFSocket_startWriting(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static PyObject *__pyx_f_9cfsupport_10PyCFSocket_startWriting(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- PyObject *__pyx_r;
- PyObject *__pyx_1 = 0;
- PyObject *__pyx_2 = 0;
- PyObject *__pyx_3 = 0;
- static char *__pyx_argnames[] = {0};
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "", __pyx_argnames)) return 0;
- Py_INCREF(__pyx_v_self);
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":97 */
- __pyx_1 = __Pyx_GetName(__pyx_b, __pyx_n_True); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 97; goto __pyx_L1;}
- Py_DECREF(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->writing);
- ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->writing = __pyx_1;
- __pyx_1 = 0;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":98 */
- __pyx_1 = PyObject_GetAttr(__pyx_v_self, __pyx_n_update); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 98; goto __pyx_L1;}
- __pyx_2 = PyTuple_New(0); if (!__pyx_2) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 98; goto __pyx_L1;}
- __pyx_3 = PyObject_CallObject(__pyx_1, __pyx_2); if (!__pyx_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 98; goto __pyx_L1;}
- Py_DECREF(__pyx_1); __pyx_1 = 0;
- Py_DECREF(__pyx_2); __pyx_2 = 0;
- Py_DECREF(__pyx_3); __pyx_3 = 0;
-
- __pyx_r = Py_None; Py_INCREF(__pyx_r);
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_1);
- Py_XDECREF(__pyx_2);
- Py_XDECREF(__pyx_3);
- __Pyx_AddTraceback("cfsupport.PyCFSocket.startWriting");
- __pyx_r = 0;
- __pyx_L0:;
- Py_DECREF(__pyx_v_self);
- return __pyx_r;
-}
-
-static PyObject *__pyx_f_9cfsupport_10PyCFSocket_stopWriting(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static PyObject *__pyx_f_9cfsupport_10PyCFSocket_stopWriting(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- PyObject *__pyx_r;
- PyObject *__pyx_1 = 0;
- PyObject *__pyx_2 = 0;
- PyObject *__pyx_3 = 0;
- static char *__pyx_argnames[] = {0};
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "", __pyx_argnames)) return 0;
- Py_INCREF(__pyx_v_self);
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":101 */
- __pyx_1 = __Pyx_GetName(__pyx_b, __pyx_n_False); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 101; goto __pyx_L1;}
- Py_DECREF(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->writing);
- ((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->writing = __pyx_1;
- __pyx_1 = 0;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":102 */
- __pyx_1 = PyObject_GetAttr(__pyx_v_self, __pyx_n_update); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 102; goto __pyx_L1;}
- __pyx_2 = PyTuple_New(0); if (!__pyx_2) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 102; goto __pyx_L1;}
- __pyx_3 = PyObject_CallObject(__pyx_1, __pyx_2); if (!__pyx_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 102; goto __pyx_L1;}
- Py_DECREF(__pyx_1); __pyx_1 = 0;
- Py_DECREF(__pyx_2); __pyx_2 = 0;
- Py_DECREF(__pyx_3); __pyx_3 = 0;
-
- __pyx_r = Py_None; Py_INCREF(__pyx_r);
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_1);
- Py_XDECREF(__pyx_2);
- Py_XDECREF(__pyx_3);
- __Pyx_AddTraceback("cfsupport.PyCFSocket.stopWriting");
- __pyx_r = 0;
- __pyx_L0:;
- Py_DECREF(__pyx_v_self);
- return __pyx_r;
-}
-
-static void __pyx_f_9cfsupport_10PyCFSocket___dealloc__(PyObject *__pyx_v_self); /*proto*/
-static void __pyx_f_9cfsupport_10PyCFSocket___dealloc__(PyObject *__pyx_v_self) {
- int __pyx_1;
- Py_INCREF(__pyx_v_self);
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":106 */
- __pyx_1 = (((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->source != 0);
- if (__pyx_1) {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":107 */
- CFRelease(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->source);
- goto __pyx_L2;
- }
- __pyx_L2:;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":108 */
- __pyx_1 = (((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->cf != 0);
- if (__pyx_1) {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":109 */
- CFSocketInvalidate(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->cf);
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":110 */
- CFRelease(((struct __pyx_obj_9cfsupport_PyCFSocket *)__pyx_v_self)->cf);
- goto __pyx_L3;
- }
- __pyx_L3:;
-
- goto __pyx_L0;
- __pyx_L1:;
- __Pyx_AddTraceback("cfsupport.PyCFSocket.__dealloc__");
- __pyx_L0:;
- Py_DECREF(__pyx_v_self);
-}
-
-static PyObject *__pyx_k10p;
-
-static char (__pyx_k10[]) = "Invalid Socket";
-
-static int __pyx_f_9cfsupport_16PyCFRunLoopTimer___new__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static int __pyx_f_9cfsupport_16PyCFRunLoopTimer___new__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- double __pyx_v_fireDate;
- double __pyx_v_interval;
- PyObject *__pyx_v_callout = 0;
- int __pyx_r;
- int __pyx_1;
- PyObject *__pyx_2 = 0;
- PyObject *__pyx_3 = 0;
- PyObject *__pyx_4 = 0;
- static char *__pyx_argnames[] = {"fireDate","interval","callout",0};
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "ddO", __pyx_argnames, &__pyx_v_fireDate, &__pyx_v_interval, &__pyx_v_callout)) return -1;
- Py_INCREF(__pyx_v_self);
- Py_INCREF(__pyx_v_callout);
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":11 */
- Py_INCREF(__pyx_v_callout);
- Py_DECREF(((struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)__pyx_v_self)->callout);
- ((struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)__pyx_v_self)->callout = __pyx_v_callout;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":12 */
- ((struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)__pyx_v_self)->context.version = 0;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":13 */
- ((struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)__pyx_v_self)->context.info = ((void (*))__pyx_v_self);
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":14 */
- ((struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)__pyx_v_self)->context.retain = 0;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":15 */
- ((struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)__pyx_v_self)->context.release = 0;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":16 */
- ((struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)__pyx_v_self)->context.copyDescription = 0;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":17 */
- ((struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)__pyx_v_self)->cf = CFRunLoopTimerCreate(kCFAllocatorDefault,__pyx_v_fireDate,__pyx_v_interval,0,0,((CFRunLoopTimerCallBack )(&__pyx_f_9cfsupport_gilRunLoopTimerCallBack)),(&((struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)__pyx_v_self)->context));
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":18 */
- __pyx_1 = (((struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)__pyx_v_self)->cf == 0);
- if (__pyx_1) {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":19 */
- __pyx_2 = __Pyx_GetName(__pyx_b, __pyx_n_ValueError); if (!__pyx_2) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 19; goto __pyx_L1;}
- __pyx_3 = PyTuple_New(1); if (!__pyx_3) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 19; goto __pyx_L1;}
- Py_INCREF(__pyx_k10p);
- PyTuple_SET_ITEM(__pyx_3, 0, __pyx_k10p);
- __pyx_4 = PyObject_CallObject(__pyx_2, __pyx_3); if (!__pyx_4) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 19; goto __pyx_L1;}
- Py_DECREF(__pyx_2); __pyx_2 = 0;
- Py_DECREF(__pyx_3); __pyx_3 = 0;
- __Pyx_Raise(__pyx_4, 0, 0);
- Py_DECREF(__pyx_4); __pyx_4 = 0;
- {__pyx_filename = __pyx_f[2]; __pyx_lineno = 19; goto __pyx_L1;}
- goto __pyx_L2;
- }
- __pyx_L2:;
-
- __pyx_r = 0;
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_2);
- Py_XDECREF(__pyx_3);
- Py_XDECREF(__pyx_4);
- __Pyx_AddTraceback("cfsupport.PyCFRunLoopTimer.__new__");
- __pyx_r = -1;
- __pyx_L0:;
- Py_DECREF(__pyx_v_self);
- Py_DECREF(__pyx_v_callout);
- return __pyx_r;
-}
-
-static PyObject *__pyx_f_9cfsupport_16PyCFRunLoopTimer_getNextFireDate(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static PyObject *__pyx_f_9cfsupport_16PyCFRunLoopTimer_getNextFireDate(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- PyObject *__pyx_r;
- PyObject *__pyx_1 = 0;
- static char *__pyx_argnames[] = {0};
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "", __pyx_argnames)) return 0;
- Py_INCREF(__pyx_v_self);
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":22 */
- __pyx_1 = PyFloat_FromDouble(CFRunLoopTimerGetNextFireDate(((struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)__pyx_v_self)->cf)); if (!__pyx_1) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 22; goto __pyx_L1;}
- __pyx_r = __pyx_1;
- __pyx_1 = 0;
- goto __pyx_L0;
-
- __pyx_r = Py_None; Py_INCREF(__pyx_r);
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_1);
- __Pyx_AddTraceback("cfsupport.PyCFRunLoopTimer.getNextFireDate");
- __pyx_r = 0;
- __pyx_L0:;
- Py_DECREF(__pyx_v_self);
- return __pyx_r;
-}
-
-static PyObject *__pyx_f_9cfsupport_16PyCFRunLoopTimer_setNextFireDate(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static PyObject *__pyx_f_9cfsupport_16PyCFRunLoopTimer_setNextFireDate(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- double __pyx_v_fireDate;
- PyObject *__pyx_r;
- static char *__pyx_argnames[] = {"fireDate",0};
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "d", __pyx_argnames, &__pyx_v_fireDate)) return 0;
- Py_INCREF(__pyx_v_self);
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":25 */
- CFRunLoopTimerSetNextFireDate(((struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)__pyx_v_self)->cf,__pyx_v_fireDate);
-
- __pyx_r = Py_None; Py_INCREF(__pyx_r);
- goto __pyx_L0;
- __pyx_L1:;
- __Pyx_AddTraceback("cfsupport.PyCFRunLoopTimer.setNextFireDate");
- __pyx_r = 0;
- __pyx_L0:;
- Py_DECREF(__pyx_v_self);
- return __pyx_r;
-}
-
-static PyObject *__pyx_f_9cfsupport_16PyCFRunLoopTimer_invalidate(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static PyObject *__pyx_f_9cfsupport_16PyCFRunLoopTimer_invalidate(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- PyObject *__pyx_r;
- static char *__pyx_argnames[] = {0};
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "", __pyx_argnames)) return 0;
- Py_INCREF(__pyx_v_self);
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":28 */
- CFRunLoopTimerInvalidate(((struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)__pyx_v_self)->cf);
-
- __pyx_r = Py_None; Py_INCREF(__pyx_r);
- goto __pyx_L0;
- __pyx_L1:;
- __Pyx_AddTraceback("cfsupport.PyCFRunLoopTimer.invalidate");
- __pyx_r = 0;
- __pyx_L0:;
- Py_DECREF(__pyx_v_self);
- return __pyx_r;
-}
-
-static void __pyx_f_9cfsupport_16PyCFRunLoopTimer___dealloc__(PyObject *__pyx_v_self); /*proto*/
-static void __pyx_f_9cfsupport_16PyCFRunLoopTimer___dealloc__(PyObject *__pyx_v_self) {
- int __pyx_1;
- Py_INCREF(__pyx_v_self);
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":31 */
- __pyx_1 = (((struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)__pyx_v_self)->cf != 0);
- if (__pyx_1) {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":32 */
- CFRelease(((struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)__pyx_v_self)->cf);
- goto __pyx_L2;
- }
- __pyx_L2:;
-
- goto __pyx_L0;
- __pyx_L1:;
- __Pyx_AddTraceback("cfsupport.PyCFRunLoopTimer.__dealloc__");
- __pyx_L0:;
- Py_DECREF(__pyx_v_self);
-}
-
-static void __pyx_f_9cfsupport_runLoopTimerCallBack(CFRunLoopTimerRef __pyx_v_timer,void (*__pyx_v_info)) {
- struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *__pyx_v_obj;
- PyObject *__pyx_1 = 0;
- int __pyx_2;
- PyObject *__pyx_3 = 0;
- PyObject *__pyx_4 = 0;
- ((PyObject*)__pyx_v_obj) = Py_None; Py_INCREF(((PyObject*)__pyx_v_obj));
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":36 */
- __pyx_1 = (PyObject *)__pyx_v_info;
- Py_INCREF(__pyx_1);
- Py_DECREF(((PyObject *)__pyx_v_obj));
- ((PyObject *)__pyx_v_obj) = __pyx_1;
- __pyx_1 = 0;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":37 */
- /*try:*/ {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":38 */
- __pyx_2 = PyObject_IsTrue(__pyx_v_obj->callout); if (__pyx_2 < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 38; goto __pyx_L2;}
- if (__pyx_2) {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":39 */
- __pyx_1 = PyTuple_New(0); if (!__pyx_1) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 39; goto __pyx_L2;}
- __pyx_3 = PyObject_CallObject(__pyx_v_obj->callout, __pyx_1); if (!__pyx_3) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 39; goto __pyx_L2;}
- Py_DECREF(__pyx_1); __pyx_1 = 0;
- Py_DECREF(__pyx_3); __pyx_3 = 0;
- goto __pyx_L4;
- }
- __pyx_L4:;
- }
- goto __pyx_L3;
- __pyx_L2:;
- Py_XDECREF(__pyx_1); __pyx_1 = 0;
- Py_XDECREF(__pyx_3); __pyx_3 = 0;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":40 */
- /*except:*/ {
- __Pyx_AddTraceback("cfsupport.runLoopTimerCallBack");
- __pyx_1 = __Pyx_GetExcValue(); if (!__pyx_1) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 40; goto __pyx_L1;}
- Py_DECREF(__pyx_1); __pyx_1 = 0;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":41 */
- __pyx_3 = __Pyx_GetName(__pyx_m, __pyx_n_traceback); if (!__pyx_3) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 41; goto __pyx_L1;}
- __pyx_1 = PyObject_GetAttr(__pyx_3, __pyx_n_print_exc); if (!__pyx_1) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 41; goto __pyx_L1;}
- Py_DECREF(__pyx_3); __pyx_3 = 0;
- __pyx_3 = PyTuple_New(0); if (!__pyx_3) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 41; goto __pyx_L1;}
- __pyx_4 = PyObject_CallObject(__pyx_1, __pyx_3); if (!__pyx_4) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 41; goto __pyx_L1;}
- Py_DECREF(__pyx_1); __pyx_1 = 0;
- Py_DECREF(__pyx_3); __pyx_3 = 0;
- Py_DECREF(__pyx_4); __pyx_4 = 0;
- goto __pyx_L3;
- }
- __pyx_L3:;
-
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_1);
- Py_XDECREF(__pyx_3);
- Py_XDECREF(__pyx_4);
- __Pyx_WriteUnraisable("cfsupport.runLoopTimerCallBack");
- __pyx_L0:;
- Py_DECREF(__pyx_v_obj);
-}
-
-static void __pyx_f_9cfsupport_gilRunLoopTimerCallBack(CFRunLoopTimerRef __pyx_v_timer,void (*__pyx_v_info)) {
- PyGILState_STATE __pyx_v_gil;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":45 */
- __pyx_v_gil = PyGILState_Ensure();
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":46 */
- __pyx_f_9cfsupport_runLoopTimerCallBack(__pyx_v_timer,__pyx_v_info);
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":47 */
- PyGILState_Release(__pyx_v_gil);
-
- goto __pyx_L0;
- __pyx_L1:;
- __Pyx_WriteUnraisable("cfsupport.gilRunLoopTimerCallBack");
- __pyx_L0:;
-}
-
-static int __pyx_f_9cfsupport_11PyCFRunLoop___new__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static int __pyx_f_9cfsupport_11PyCFRunLoop___new__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- PyObject *__pyx_v_runLoop = 0;
- CFTypeRef __pyx_v__runLoop;
- int __pyx_r;
- int __pyx_1;
- PyObject *__pyx_2 = 0;
- static char *__pyx_argnames[] = {"runLoop",0};
- __pyx_v_runLoop = __pyx_k6;
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "|O", __pyx_argnames, &__pyx_v_runLoop)) return -1;
- Py_INCREF(__pyx_v_self);
- Py_INCREF(__pyx_v_runLoop);
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":54 */
- __pyx_1 = __pyx_v_runLoop == Py_None;
- if (__pyx_1) {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":55 */
- __pyx_v__runLoop = CFRunLoopGetCurrent();
- goto __pyx_L2;
- }
- /*else*/ {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":57 */
- __pyx_1 = (CFObj_Convert(__pyx_v_runLoop,(&__pyx_v__runLoop)) == 0);
- if (__pyx_1) {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":58 */
- __Pyx_ReRaise();
- {__pyx_filename = __pyx_f[2]; __pyx_lineno = 58; goto __pyx_L1;}
- goto __pyx_L3;
- }
- __pyx_L3:;
- }
- __pyx_L2:;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":61 */
- __pyx_2 = CFObj_New(CFRetain(__pyx_v__runLoop)); if (!__pyx_2) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 61; goto __pyx_L1;}
- Py_DECREF(((struct __pyx_obj_9cfsupport_PyCFRunLoop *)__pyx_v_self)->cf);
- ((struct __pyx_obj_9cfsupport_PyCFRunLoop *)__pyx_v_self)->cf = __pyx_2;
- __pyx_2 = 0;
-
- __pyx_r = 0;
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_2);
- __Pyx_AddTraceback("cfsupport.PyCFRunLoop.__new__");
- __pyx_r = -1;
- __pyx_L0:;
- Py_DECREF(__pyx_v_self);
- Py_DECREF(__pyx_v_runLoop);
- return __pyx_r;
-}
-
-static PyObject *__pyx_f_9cfsupport_11PyCFRunLoop_run(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static PyObject *__pyx_f_9cfsupport_11PyCFRunLoop_run(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- PyObject *__pyx_r;
- static char *__pyx_argnames[] = {0};
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "", __pyx_argnames)) return 0;
- Py_INCREF(__pyx_v_self);
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":64 */
- CFRunLoopRun();
-
- __pyx_r = Py_None; Py_INCREF(__pyx_r);
- goto __pyx_L0;
- __pyx_L1:;
- __Pyx_AddTraceback("cfsupport.PyCFRunLoop.run");
- __pyx_r = 0;
- __pyx_L0:;
- Py_DECREF(__pyx_v_self);
- return __pyx_r;
-}
-
-static PyObject *__pyx_k11p;
-
-static char (__pyx_k11[]) = "CFRunLoopReference is invalid";
-
-static PyObject *__pyx_f_9cfsupport_11PyCFRunLoop_stop(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static PyObject *__pyx_f_9cfsupport_11PyCFRunLoop_stop(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- CFTypeRef __pyx_v__runLoop;
- PyObject *__pyx_r;
- int __pyx_1;
- PyObject *__pyx_2 = 0;
- static char *__pyx_argnames[] = {0};
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "", __pyx_argnames)) return 0;
- Py_INCREF(__pyx_v_self);
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":68 */
- __pyx_1 = (CFObj_Convert(((struct __pyx_obj_9cfsupport_PyCFRunLoop *)__pyx_v_self)->cf,(&__pyx_v__runLoop)) == 0);
- if (__pyx_1) {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":69 */
- __pyx_2 = __Pyx_GetName(__pyx_b, __pyx_n_ValueError); if (!__pyx_2) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 69; goto __pyx_L1;}
- __Pyx_Raise(__pyx_2, __pyx_k11p, 0);
- Py_DECREF(__pyx_2); __pyx_2 = 0;
- {__pyx_filename = __pyx_f[2]; __pyx_lineno = 69; goto __pyx_L1;}
- goto __pyx_L2;
- }
- __pyx_L2:;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":70 */
- CFRunLoopStop(__pyx_v__runLoop);
-
- __pyx_r = Py_None; Py_INCREF(__pyx_r);
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_2);
- __Pyx_AddTraceback("cfsupport.PyCFRunLoop.stop");
- __pyx_r = 0;
- __pyx_L0:;
- Py_DECREF(__pyx_v_self);
- return __pyx_r;
-}
-
-static PyObject *__pyx_k12p;
-
-static char (__pyx_k12[]) = "CFRunLoopReference is invalid";
-
-static PyObject *__pyx_f_9cfsupport_11PyCFRunLoop_currentMode(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static PyObject *__pyx_f_9cfsupport_11PyCFRunLoop_currentMode(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- CFTypeRef __pyx_v__currentMode;
- CFTypeRef __pyx_v__runLoop;
- PyObject *__pyx_r;
- int __pyx_1;
- PyObject *__pyx_2 = 0;
- static char *__pyx_argnames[] = {0};
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "", __pyx_argnames)) return 0;
- Py_INCREF(__pyx_v_self);
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":75 */
- __pyx_1 = (CFObj_Convert(((struct __pyx_obj_9cfsupport_PyCFRunLoop *)__pyx_v_self)->cf,(&__pyx_v__runLoop)) == 0);
- if (__pyx_1) {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":76 */
- __pyx_2 = __Pyx_GetName(__pyx_b, __pyx_n_ValueError); if (!__pyx_2) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 76; goto __pyx_L1;}
- __Pyx_Raise(__pyx_2, __pyx_k12p, 0);
- Py_DECREF(__pyx_2); __pyx_2 = 0;
- {__pyx_filename = __pyx_f[2]; __pyx_lineno = 76; goto __pyx_L1;}
- goto __pyx_L2;
- }
- __pyx_L2:;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":77 */
- __pyx_v__currentMode = CFRunLoopCopyCurrentMode(__pyx_v__runLoop);
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":78 */
- __pyx_1 = (__pyx_v__currentMode == 0);
- if (__pyx_1) {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":79 */
- Py_INCREF(Py_None);
- __pyx_r = Py_None;
- goto __pyx_L0;
- goto __pyx_L3;
- }
- __pyx_L3:;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":80 */
- __pyx_2 = CFObj_New(__pyx_v__currentMode); if (!__pyx_2) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 80; goto __pyx_L1;}
- __pyx_r = __pyx_2;
- __pyx_2 = 0;
- goto __pyx_L0;
-
- __pyx_r = Py_None; Py_INCREF(__pyx_r);
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_2);
- __Pyx_AddTraceback("cfsupport.PyCFRunLoop.currentMode");
- __pyx_r = 0;
- __pyx_L0:;
- Py_DECREF(__pyx_v_self);
- return __pyx_r;
-}
-
-static PyObject *__pyx_k13p;
-
-static char (__pyx_k13[]) = "CFRunLoopReference is invalid";
-
-static PyObject *__pyx_f_9cfsupport_11PyCFRunLoop_addSocket(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static PyObject *__pyx_f_9cfsupport_11PyCFRunLoop_addSocket(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- struct __pyx_obj_9cfsupport_PyCFSocket *__pyx_v_socket = 0;
- CFTypeRef __pyx_v__runLoop;
- PyObject *__pyx_r;
- int __pyx_1;
- PyObject *__pyx_2 = 0;
- static char *__pyx_argnames[] = {"socket",0};
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "O", __pyx_argnames, &__pyx_v_socket)) return 0;
- Py_INCREF(__pyx_v_self);
- Py_INCREF(__pyx_v_socket);
- if (!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_socket), __pyx_ptype_9cfsupport_PyCFSocket, 0, "socket")) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 82; goto __pyx_L1;}
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":84 */
- __pyx_1 = (CFObj_Convert(((struct __pyx_obj_9cfsupport_PyCFRunLoop *)__pyx_v_self)->cf,(&__pyx_v__runLoop)) == 0);
- if (__pyx_1) {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":85 */
- __pyx_2 = __Pyx_GetName(__pyx_b, __pyx_n_ValueError); if (!__pyx_2) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 85; goto __pyx_L1;}
- __Pyx_Raise(__pyx_2, __pyx_k13p, 0);
- Py_DECREF(__pyx_2); __pyx_2 = 0;
- {__pyx_filename = __pyx_f[2]; __pyx_lineno = 85; goto __pyx_L1;}
- goto __pyx_L2;
- }
- __pyx_L2:;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":86 */
- CFRunLoopAddSource(__pyx_v__runLoop,__pyx_v_socket->source,kCFRunLoopCommonModes);
-
- __pyx_r = Py_None; Py_INCREF(__pyx_r);
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_2);
- __Pyx_AddTraceback("cfsupport.PyCFRunLoop.addSocket");
- __pyx_r = 0;
- __pyx_L0:;
- Py_DECREF(__pyx_v_self);
- Py_DECREF(__pyx_v_socket);
- return __pyx_r;
-}
-
-static PyObject *__pyx_k14p;
-
-static char (__pyx_k14[]) = "CFRunLoopReference is invalid";
-
-static PyObject *__pyx_f_9cfsupport_11PyCFRunLoop_removeSocket(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static PyObject *__pyx_f_9cfsupport_11PyCFRunLoop_removeSocket(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- struct __pyx_obj_9cfsupport_PyCFSocket *__pyx_v_socket = 0;
- CFTypeRef __pyx_v__runLoop;
- PyObject *__pyx_r;
- int __pyx_1;
- PyObject *__pyx_2 = 0;
- static char *__pyx_argnames[] = {"socket",0};
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "O", __pyx_argnames, &__pyx_v_socket)) return 0;
- Py_INCREF(__pyx_v_self);
- Py_INCREF(__pyx_v_socket);
- if (!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_socket), __pyx_ptype_9cfsupport_PyCFSocket, 0, "socket")) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 88; goto __pyx_L1;}
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":90 */
- __pyx_1 = (CFObj_Convert(((struct __pyx_obj_9cfsupport_PyCFRunLoop *)__pyx_v_self)->cf,(&__pyx_v__runLoop)) == 0);
- if (__pyx_1) {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":91 */
- __pyx_2 = __Pyx_GetName(__pyx_b, __pyx_n_ValueError); if (!__pyx_2) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 91; goto __pyx_L1;}
- __Pyx_Raise(__pyx_2, __pyx_k14p, 0);
- Py_DECREF(__pyx_2); __pyx_2 = 0;
- {__pyx_filename = __pyx_f[2]; __pyx_lineno = 91; goto __pyx_L1;}
- goto __pyx_L2;
- }
- __pyx_L2:;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":92 */
- CFRunLoopRemoveSource(__pyx_v__runLoop,__pyx_v_socket->source,kCFRunLoopCommonModes);
-
- __pyx_r = Py_None; Py_INCREF(__pyx_r);
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_2);
- __Pyx_AddTraceback("cfsupport.PyCFRunLoop.removeSocket");
- __pyx_r = 0;
- __pyx_L0:;
- Py_DECREF(__pyx_v_self);
- Py_DECREF(__pyx_v_socket);
- return __pyx_r;
-}
-
-static PyObject *__pyx_k15p;
-
-static char (__pyx_k15[]) = "CFRunLoopReference is invalid";
-
-static PyObject *__pyx_f_9cfsupport_11PyCFRunLoop_addTimer(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static PyObject *__pyx_f_9cfsupport_11PyCFRunLoop_addTimer(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *__pyx_v_timer = 0;
- CFTypeRef __pyx_v__runLoop;
- PyObject *__pyx_r;
- int __pyx_1;
- PyObject *__pyx_2 = 0;
- static char *__pyx_argnames[] = {"timer",0};
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "O", __pyx_argnames, &__pyx_v_timer)) return 0;
- Py_INCREF(__pyx_v_self);
- Py_INCREF(__pyx_v_timer);
- if (!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_timer), __pyx_ptype_9cfsupport_PyCFRunLoopTimer, 0, "timer")) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 94; goto __pyx_L1;}
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":96 */
- __pyx_1 = (CFObj_Convert(((struct __pyx_obj_9cfsupport_PyCFRunLoop *)__pyx_v_self)->cf,(&__pyx_v__runLoop)) == 0);
- if (__pyx_1) {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":97 */
- __pyx_2 = __Pyx_GetName(__pyx_b, __pyx_n_ValueError); if (!__pyx_2) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 97; goto __pyx_L1;}
- __Pyx_Raise(__pyx_2, __pyx_k15p, 0);
- Py_DECREF(__pyx_2); __pyx_2 = 0;
- {__pyx_filename = __pyx_f[2]; __pyx_lineno = 97; goto __pyx_L1;}
- goto __pyx_L2;
- }
- __pyx_L2:;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":98 */
- CFRunLoopAddTimer(__pyx_v__runLoop,__pyx_v_timer->cf,kCFRunLoopCommonModes);
-
- __pyx_r = Py_None; Py_INCREF(__pyx_r);
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_2);
- __Pyx_AddTraceback("cfsupport.PyCFRunLoop.addTimer");
- __pyx_r = 0;
- __pyx_L0:;
- Py_DECREF(__pyx_v_self);
- Py_DECREF(__pyx_v_timer);
- return __pyx_r;
-}
-
-static PyObject *__pyx_k16p;
-
-static char (__pyx_k16[]) = "CFRunLoopReference is invalid";
-
-static PyObject *__pyx_f_9cfsupport_11PyCFRunLoop_removeTimer(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static PyObject *__pyx_f_9cfsupport_11PyCFRunLoop_removeTimer(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *__pyx_v_timer = 0;
- CFTypeRef __pyx_v__runLoop;
- PyObject *__pyx_r;
- int __pyx_1;
- PyObject *__pyx_2 = 0;
- static char *__pyx_argnames[] = {"timer",0};
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "O", __pyx_argnames, &__pyx_v_timer)) return 0;
- Py_INCREF(__pyx_v_self);
- Py_INCREF(__pyx_v_timer);
- if (!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_timer), __pyx_ptype_9cfsupport_PyCFRunLoopTimer, 0, "timer")) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 100; goto __pyx_L1;}
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":102 */
- __pyx_1 = (CFObj_Convert(((struct __pyx_obj_9cfsupport_PyCFRunLoop *)__pyx_v_self)->cf,(&__pyx_v__runLoop)) == 0);
- if (__pyx_1) {
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":103 */
- __pyx_2 = __Pyx_GetName(__pyx_b, __pyx_n_ValueError); if (!__pyx_2) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 103; goto __pyx_L1;}
- __Pyx_Raise(__pyx_2, __pyx_k16p, 0);
- Py_DECREF(__pyx_2); __pyx_2 = 0;
- {__pyx_filename = __pyx_f[2]; __pyx_lineno = 103; goto __pyx_L1;}
- goto __pyx_L2;
- }
- __pyx_L2:;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":104 */
- CFRunLoopRemoveTimer(__pyx_v__runLoop,__pyx_v_timer->cf,kCFRunLoopCommonModes);
-
- __pyx_r = Py_None; Py_INCREF(__pyx_r);
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_2);
- __Pyx_AddTraceback("cfsupport.PyCFRunLoop.removeTimer");
- __pyx_r = 0;
- __pyx_L0:;
- Py_DECREF(__pyx_v_self);
- Py_DECREF(__pyx_v_timer);
- return __pyx_r;
-}
-
-static __Pyx_InternTabEntry __pyx_intern_tab[] = {
- {&__pyx_n_False, "False"},
- {&__pyx_n_True, "True"},
- {&__pyx_n_ValueError, "ValueError"},
- {&__pyx_n___version__, "__version__"},
- {&__pyx_n_now, "now"},
- {&__pyx_n_print_exc, "print_exc"},
- {&__pyx_n_traceback, "traceback"},
- {&__pyx_n_update, "update"},
- {0, 0}
-};
-
-static __Pyx_StringTabEntry __pyx_string_tab[] = {
- {&__pyx_k7p, __pyx_k7, sizeof(__pyx_k7)},
- {&__pyx_k8p, __pyx_k8, sizeof(__pyx_k8)},
- {&__pyx_k9p, __pyx_k9, sizeof(__pyx_k9)},
- {&__pyx_k10p, __pyx_k10, sizeof(__pyx_k10)},
- {&__pyx_k11p, __pyx_k11, sizeof(__pyx_k11)},
- {&__pyx_k12p, __pyx_k12, sizeof(__pyx_k12)},
- {&__pyx_k13p, __pyx_k13, sizeof(__pyx_k13)},
- {&__pyx_k14p, __pyx_k14, sizeof(__pyx_k14)},
- {&__pyx_k15p, __pyx_k15, sizeof(__pyx_k15)},
- {&__pyx_k16p, __pyx_k16, sizeof(__pyx_k16)},
- {0, 0, 0}
-};
-
-static PyObject *__pyx_tp_new_9cfsupport_PyCFSocket(PyTypeObject *t, PyObject *a, PyObject *k) {
- PyObject *o = (*t->tp_alloc)(t, 0);
- struct __pyx_obj_9cfsupport_PyCFSocket *p = (struct __pyx_obj_9cfsupport_PyCFSocket *)o;
- p->readcallback = Py_None; Py_INCREF(p->readcallback);
- p->writecallback = Py_None; Py_INCREF(p->writecallback);
- p->connectcallback = Py_None; Py_INCREF(p->connectcallback);
- p->reading = Py_None; Py_INCREF(p->reading);
- p->writing = Py_None; Py_INCREF(p->writing);
- if (__pyx_f_9cfsupport_10PyCFSocket___new__(o, a, k) < 0) {
- Py_DECREF(o); o = 0;
- }
- return o;
-}
-
-static void __pyx_tp_dealloc_9cfsupport_PyCFSocket(PyObject *o) {
- struct __pyx_obj_9cfsupport_PyCFSocket *p = (struct __pyx_obj_9cfsupport_PyCFSocket *)o;
- {
- PyObject *etype, *eval, *etb;
- PyErr_Fetch(&etype, &eval, &etb);
- ++o->ob_refcnt;
- __pyx_f_9cfsupport_10PyCFSocket___dealloc__(o);
- if (PyErr_Occurred()) PyErr_WriteUnraisable(o);
- --o->ob_refcnt;
- PyErr_Restore(etype, eval, etb);
- }
- Py_XDECREF(p->readcallback);
- Py_XDECREF(p->writecallback);
- Py_XDECREF(p->connectcallback);
- Py_XDECREF(p->reading);
- Py_XDECREF(p->writing);
- (*o->ob_type->tp_free)(o);
-}
-
-static int __pyx_tp_traverse_9cfsupport_PyCFSocket(PyObject *o, visitproc v, void *a) {
- int e;
- struct __pyx_obj_9cfsupport_PyCFSocket *p = (struct __pyx_obj_9cfsupport_PyCFSocket *)o;
- if (p->readcallback) {
- e = (*v)(p->readcallback, a); if (e) return e;
- }
- if (p->writecallback) {
- e = (*v)(p->writecallback, a); if (e) return e;
- }
- if (p->connectcallback) {
- e = (*v)(p->connectcallback, a); if (e) return e;
- }
- if (p->reading) {
- e = (*v)(p->reading, a); if (e) return e;
- }
- if (p->writing) {
- e = (*v)(p->writing, a); if (e) return e;
- }
- return 0;
-}
-
-static int __pyx_tp_clear_9cfsupport_PyCFSocket(PyObject *o) {
- struct __pyx_obj_9cfsupport_PyCFSocket *p = (struct __pyx_obj_9cfsupport_PyCFSocket *)o;
- Py_XDECREF(p->readcallback);
- p->readcallback = Py_None; Py_INCREF(p->readcallback);
- Py_XDECREF(p->writecallback);
- p->writecallback = Py_None; Py_INCREF(p->writecallback);
- Py_XDECREF(p->connectcallback);
- p->connectcallback = Py_None; Py_INCREF(p->connectcallback);
- Py_XDECREF(p->reading);
- p->reading = Py_None; Py_INCREF(p->reading);
- Py_XDECREF(p->writing);
- p->writing = Py_None; Py_INCREF(p->writing);
- return 0;
-}
-
-static struct PyMethodDef __pyx_methods_9cfsupport_PyCFSocket[] = {
- {"update", (PyCFunction)__pyx_f_9cfsupport_10PyCFSocket_update, METH_VARARGS|METH_KEYWORDS, 0},
- {"startReading", (PyCFunction)__pyx_f_9cfsupport_10PyCFSocket_startReading, METH_VARARGS|METH_KEYWORDS, 0},
- {"stopReading", (PyCFunction)__pyx_f_9cfsupport_10PyCFSocket_stopReading, METH_VARARGS|METH_KEYWORDS, 0},
- {"startWriting", (PyCFunction)__pyx_f_9cfsupport_10PyCFSocket_startWriting, METH_VARARGS|METH_KEYWORDS, 0},
- {"stopWriting", (PyCFunction)__pyx_f_9cfsupport_10PyCFSocket_stopWriting, METH_VARARGS|METH_KEYWORDS, 0},
- {0, 0, 0, 0}
-};
-
-static struct PyMemberDef __pyx_members_9cfsupport_PyCFSocket[] = {
- {"readcallback", T_OBJECT, offsetof(struct __pyx_obj_9cfsupport_PyCFSocket, readcallback), 0, 0},
- {"writecallback", T_OBJECT, offsetof(struct __pyx_obj_9cfsupport_PyCFSocket, writecallback), 0, 0},
- {"connectcallback", T_OBJECT, offsetof(struct __pyx_obj_9cfsupport_PyCFSocket, connectcallback), 0, 0},
- {"reading", T_OBJECT, offsetof(struct __pyx_obj_9cfsupport_PyCFSocket, reading), 0, 0},
- {"writing", T_OBJECT, offsetof(struct __pyx_obj_9cfsupport_PyCFSocket, writing), 0, 0},
- {"fileno", T_INT, offsetof(struct __pyx_obj_9cfsupport_PyCFSocket, fileno), READONLY, 0},
- {0, 0, 0, 0, 0}
-};
-
-static PyNumberMethods __pyx_tp_as_number_PyCFSocket = {
- 0, /*nb_add*/
- 0, /*nb_subtract*/
- 0, /*nb_multiply*/
- 0, /*nb_divide*/
- 0, /*nb_remainder*/
- 0, /*nb_divmod*/
- 0, /*nb_power*/
- 0, /*nb_negative*/
- 0, /*nb_positive*/
- 0, /*nb_absolute*/
- 0, /*nb_nonzero*/
- 0, /*nb_invert*/
- 0, /*nb_lshift*/
- 0, /*nb_rshift*/
- 0, /*nb_and*/
- 0, /*nb_xor*/
- 0, /*nb_or*/
- 0, /*nb_coerce*/
- 0, /*nb_int*/
- 0, /*nb_long*/
- 0, /*nb_float*/
- 0, /*nb_oct*/
- 0, /*nb_hex*/
- 0, /*nb_inplace_add*/
- 0, /*nb_inplace_subtract*/
- 0, /*nb_inplace_multiply*/
- 0, /*nb_inplace_divide*/
- 0, /*nb_inplace_remainder*/
- 0, /*nb_inplace_power*/
- 0, /*nb_inplace_lshift*/
- 0, /*nb_inplace_rshift*/
- 0, /*nb_inplace_and*/
- 0, /*nb_inplace_xor*/
- 0, /*nb_inplace_or*/
- 0, /*nb_floor_divide*/
- 0, /*nb_true_divide*/
- 0, /*nb_inplace_floor_divide*/
- 0, /*nb_inplace_true_divide*/
-};
-
-static PySequenceMethods __pyx_tp_as_sequence_PyCFSocket = {
- 0, /*sq_length*/
- 0, /*sq_concat*/
- 0, /*sq_repeat*/
- 0, /*sq_item*/
- 0, /*sq_slice*/
- 0, /*sq_ass_item*/
- 0, /*sq_ass_slice*/
- 0, /*sq_contains*/
- 0, /*sq_inplace_concat*/
- 0, /*sq_inplace_repeat*/
-};
-
-static PyMappingMethods __pyx_tp_as_mapping_PyCFSocket = {
- 0, /*mp_length*/
- 0, /*mp_subscript*/
- 0, /*mp_ass_subscript*/
-};
-
-static PyBufferProcs __pyx_tp_as_buffer_PyCFSocket = {
- 0, /*bf_getreadbuffer*/
- 0, /*bf_getwritebuffer*/
- 0, /*bf_getsegcount*/
- 0, /*bf_getcharbuffer*/
-};
-
-statichere PyTypeObject __pyx_type_9cfsupport_PyCFSocket = {
- PyObject_HEAD_INIT(0)
- 0, /*ob_size*/
- "cfsupport.PyCFSocket", /*tp_name*/
- sizeof(struct __pyx_obj_9cfsupport_PyCFSocket), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- __pyx_tp_dealloc_9cfsupport_PyCFSocket, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- &__pyx_tp_as_number_PyCFSocket, /*tp_as_number*/
- &__pyx_tp_as_sequence_PyCFSocket, /*tp_as_sequence*/
- &__pyx_tp_as_mapping_PyCFSocket, /*tp_as_mapping*/
- 0, /*tp_hash*/
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- &__pyx_tp_as_buffer_PyCFSocket, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/
- 0, /*tp_doc*/
- __pyx_tp_traverse_9cfsupport_PyCFSocket, /*tp_traverse*/
- __pyx_tp_clear_9cfsupport_PyCFSocket, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- __pyx_methods_9cfsupport_PyCFSocket, /*tp_methods*/
- __pyx_members_9cfsupport_PyCFSocket, /*tp_members*/
- 0, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- 0, /*tp_init*/
- 0, /*tp_alloc*/
- __pyx_tp_new_9cfsupport_PyCFSocket, /*tp_new*/
- 0, /*tp_free*/
- 0, /*tp_is_gc*/
- 0, /*tp_bases*/
- 0, /*tp_mro*/
- 0, /*tp_cache*/
- 0, /*tp_subclasses*/
- 0, /*tp_weaklist*/
-};
-
-static PyObject *__pyx_tp_new_9cfsupport_PyCFRunLoopTimer(PyTypeObject *t, PyObject *a, PyObject *k) {
- PyObject *o = (*t->tp_alloc)(t, 0);
- struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *p = (struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)o;
- p->callout = Py_None; Py_INCREF(p->callout);
- if (__pyx_f_9cfsupport_16PyCFRunLoopTimer___new__(o, a, k) < 0) {
- Py_DECREF(o); o = 0;
- }
- return o;
-}
-
-static void __pyx_tp_dealloc_9cfsupport_PyCFRunLoopTimer(PyObject *o) {
- struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *p = (struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)o;
- {
- PyObject *etype, *eval, *etb;
- PyErr_Fetch(&etype, &eval, &etb);
- ++o->ob_refcnt;
- __pyx_f_9cfsupport_16PyCFRunLoopTimer___dealloc__(o);
- if (PyErr_Occurred()) PyErr_WriteUnraisable(o);
- --o->ob_refcnt;
- PyErr_Restore(etype, eval, etb);
- }
- Py_XDECREF(p->callout);
- (*o->ob_type->tp_free)(o);
-}
-
-static int __pyx_tp_traverse_9cfsupport_PyCFRunLoopTimer(PyObject *o, visitproc v, void *a) {
- int e;
- struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *p = (struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)o;
- if (p->callout) {
- e = (*v)(p->callout, a); if (e) return e;
- }
- return 0;
-}
-
-static int __pyx_tp_clear_9cfsupport_PyCFRunLoopTimer(PyObject *o) {
- struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *p = (struct __pyx_obj_9cfsupport_PyCFRunLoopTimer *)o;
- Py_XDECREF(p->callout);
- p->callout = Py_None; Py_INCREF(p->callout);
- return 0;
-}
-
-static struct PyMethodDef __pyx_methods_9cfsupport_PyCFRunLoopTimer[] = {
- {"getNextFireDate", (PyCFunction)__pyx_f_9cfsupport_16PyCFRunLoopTimer_getNextFireDate, METH_VARARGS|METH_KEYWORDS, 0},
- {"setNextFireDate", (PyCFunction)__pyx_f_9cfsupport_16PyCFRunLoopTimer_setNextFireDate, METH_VARARGS|METH_KEYWORDS, 0},
- {"invalidate", (PyCFunction)__pyx_f_9cfsupport_16PyCFRunLoopTimer_invalidate, METH_VARARGS|METH_KEYWORDS, 0},
- {0, 0, 0, 0}
-};
-
-static struct PyMemberDef __pyx_members_9cfsupport_PyCFRunLoopTimer[] = {
- {"callout", T_OBJECT, offsetof(struct __pyx_obj_9cfsupport_PyCFRunLoopTimer, callout), 0, 0},
- {0, 0, 0, 0, 0}
-};
-
-static PyNumberMethods __pyx_tp_as_number_PyCFRunLoopTimer = {
- 0, /*nb_add*/
- 0, /*nb_subtract*/
- 0, /*nb_multiply*/
- 0, /*nb_divide*/
- 0, /*nb_remainder*/
- 0, /*nb_divmod*/
- 0, /*nb_power*/
- 0, /*nb_negative*/
- 0, /*nb_positive*/
- 0, /*nb_absolute*/
- 0, /*nb_nonzero*/
- 0, /*nb_invert*/
- 0, /*nb_lshift*/
- 0, /*nb_rshift*/
- 0, /*nb_and*/
- 0, /*nb_xor*/
- 0, /*nb_or*/
- 0, /*nb_coerce*/
- 0, /*nb_int*/
- 0, /*nb_long*/
- 0, /*nb_float*/
- 0, /*nb_oct*/
- 0, /*nb_hex*/
- 0, /*nb_inplace_add*/
- 0, /*nb_inplace_subtract*/
- 0, /*nb_inplace_multiply*/
- 0, /*nb_inplace_divide*/
- 0, /*nb_inplace_remainder*/
- 0, /*nb_inplace_power*/
- 0, /*nb_inplace_lshift*/
- 0, /*nb_inplace_rshift*/
- 0, /*nb_inplace_and*/
- 0, /*nb_inplace_xor*/
- 0, /*nb_inplace_or*/
- 0, /*nb_floor_divide*/
- 0, /*nb_true_divide*/
- 0, /*nb_inplace_floor_divide*/
- 0, /*nb_inplace_true_divide*/
-};
-
-static PySequenceMethods __pyx_tp_as_sequence_PyCFRunLoopTimer = {
- 0, /*sq_length*/
- 0, /*sq_concat*/
- 0, /*sq_repeat*/
- 0, /*sq_item*/
- 0, /*sq_slice*/
- 0, /*sq_ass_item*/
- 0, /*sq_ass_slice*/
- 0, /*sq_contains*/
- 0, /*sq_inplace_concat*/
- 0, /*sq_inplace_repeat*/
-};
-
-static PyMappingMethods __pyx_tp_as_mapping_PyCFRunLoopTimer = {
- 0, /*mp_length*/
- 0, /*mp_subscript*/
- 0, /*mp_ass_subscript*/
-};
-
-static PyBufferProcs __pyx_tp_as_buffer_PyCFRunLoopTimer = {
- 0, /*bf_getreadbuffer*/
- 0, /*bf_getwritebuffer*/
- 0, /*bf_getsegcount*/
- 0, /*bf_getcharbuffer*/
-};
-
-statichere PyTypeObject __pyx_type_9cfsupport_PyCFRunLoopTimer = {
- PyObject_HEAD_INIT(0)
- 0, /*ob_size*/
- "cfsupport.PyCFRunLoopTimer", /*tp_name*/
- sizeof(struct __pyx_obj_9cfsupport_PyCFRunLoopTimer), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- __pyx_tp_dealloc_9cfsupport_PyCFRunLoopTimer, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- &__pyx_tp_as_number_PyCFRunLoopTimer, /*tp_as_number*/
- &__pyx_tp_as_sequence_PyCFRunLoopTimer, /*tp_as_sequence*/
- &__pyx_tp_as_mapping_PyCFRunLoopTimer, /*tp_as_mapping*/
- 0, /*tp_hash*/
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- &__pyx_tp_as_buffer_PyCFRunLoopTimer, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/
- 0, /*tp_doc*/
- __pyx_tp_traverse_9cfsupport_PyCFRunLoopTimer, /*tp_traverse*/
- __pyx_tp_clear_9cfsupport_PyCFRunLoopTimer, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- __pyx_methods_9cfsupport_PyCFRunLoopTimer, /*tp_methods*/
- __pyx_members_9cfsupport_PyCFRunLoopTimer, /*tp_members*/
- 0, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- 0, /*tp_init*/
- 0, /*tp_alloc*/
- __pyx_tp_new_9cfsupport_PyCFRunLoopTimer, /*tp_new*/
- 0, /*tp_free*/
- 0, /*tp_is_gc*/
- 0, /*tp_bases*/
- 0, /*tp_mro*/
- 0, /*tp_cache*/
- 0, /*tp_subclasses*/
- 0, /*tp_weaklist*/
-};
-
-static PyObject *__pyx_tp_new_9cfsupport_PyCFRunLoop(PyTypeObject *t, PyObject *a, PyObject *k) {
- PyObject *o = (*t->tp_alloc)(t, 0);
- struct __pyx_obj_9cfsupport_PyCFRunLoop *p = (struct __pyx_obj_9cfsupport_PyCFRunLoop *)o;
- p->cf = Py_None; Py_INCREF(p->cf);
- if (__pyx_f_9cfsupport_11PyCFRunLoop___new__(o, a, k) < 0) {
- Py_DECREF(o); o = 0;
- }
- return o;
-}
-
-static void __pyx_tp_dealloc_9cfsupport_PyCFRunLoop(PyObject *o) {
- struct __pyx_obj_9cfsupport_PyCFRunLoop *p = (struct __pyx_obj_9cfsupport_PyCFRunLoop *)o;
- Py_XDECREF(p->cf);
- (*o->ob_type->tp_free)(o);
-}
-
-static int __pyx_tp_traverse_9cfsupport_PyCFRunLoop(PyObject *o, visitproc v, void *a) {
- int e;
- struct __pyx_obj_9cfsupport_PyCFRunLoop *p = (struct __pyx_obj_9cfsupport_PyCFRunLoop *)o;
- if (p->cf) {
- e = (*v)(p->cf, a); if (e) return e;
- }
- return 0;
-}
-
-static int __pyx_tp_clear_9cfsupport_PyCFRunLoop(PyObject *o) {
- struct __pyx_obj_9cfsupport_PyCFRunLoop *p = (struct __pyx_obj_9cfsupport_PyCFRunLoop *)o;
- Py_XDECREF(p->cf);
- p->cf = Py_None; Py_INCREF(p->cf);
- return 0;
-}
-
-static struct PyMethodDef __pyx_methods_9cfsupport_PyCFRunLoop[] = {
- {"run", (PyCFunction)__pyx_f_9cfsupport_11PyCFRunLoop_run, METH_VARARGS|METH_KEYWORDS, 0},
- {"stop", (PyCFunction)__pyx_f_9cfsupport_11PyCFRunLoop_stop, METH_VARARGS|METH_KEYWORDS, 0},
- {"currentMode", (PyCFunction)__pyx_f_9cfsupport_11PyCFRunLoop_currentMode, METH_VARARGS|METH_KEYWORDS, 0},
- {"addSocket", (PyCFunction)__pyx_f_9cfsupport_11PyCFRunLoop_addSocket, METH_VARARGS|METH_KEYWORDS, 0},
- {"removeSocket", (PyCFunction)__pyx_f_9cfsupport_11PyCFRunLoop_removeSocket, METH_VARARGS|METH_KEYWORDS, 0},
- {"addTimer", (PyCFunction)__pyx_f_9cfsupport_11PyCFRunLoop_addTimer, METH_VARARGS|METH_KEYWORDS, 0},
- {"removeTimer", (PyCFunction)__pyx_f_9cfsupport_11PyCFRunLoop_removeTimer, METH_VARARGS|METH_KEYWORDS, 0},
- {0, 0, 0, 0}
-};
-
-static struct PyMemberDef __pyx_members_9cfsupport_PyCFRunLoop[] = {
- {"cf", T_OBJECT, offsetof(struct __pyx_obj_9cfsupport_PyCFRunLoop, cf), 0, 0},
- {0, 0, 0, 0, 0}
-};
-
-static PyNumberMethods __pyx_tp_as_number_PyCFRunLoop = {
- 0, /*nb_add*/
- 0, /*nb_subtract*/
- 0, /*nb_multiply*/
- 0, /*nb_divide*/
- 0, /*nb_remainder*/
- 0, /*nb_divmod*/
- 0, /*nb_power*/
- 0, /*nb_negative*/
- 0, /*nb_positive*/
- 0, /*nb_absolute*/
- 0, /*nb_nonzero*/
- 0, /*nb_invert*/
- 0, /*nb_lshift*/
- 0, /*nb_rshift*/
- 0, /*nb_and*/
- 0, /*nb_xor*/
- 0, /*nb_or*/
- 0, /*nb_coerce*/
- 0, /*nb_int*/
- 0, /*nb_long*/
- 0, /*nb_float*/
- 0, /*nb_oct*/
- 0, /*nb_hex*/
- 0, /*nb_inplace_add*/
- 0, /*nb_inplace_subtract*/
- 0, /*nb_inplace_multiply*/
- 0, /*nb_inplace_divide*/
- 0, /*nb_inplace_remainder*/
- 0, /*nb_inplace_power*/
- 0, /*nb_inplace_lshift*/
- 0, /*nb_inplace_rshift*/
- 0, /*nb_inplace_and*/
- 0, /*nb_inplace_xor*/
- 0, /*nb_inplace_or*/
- 0, /*nb_floor_divide*/
- 0, /*nb_true_divide*/
- 0, /*nb_inplace_floor_divide*/
- 0, /*nb_inplace_true_divide*/
-};
-
-static PySequenceMethods __pyx_tp_as_sequence_PyCFRunLoop = {
- 0, /*sq_length*/
- 0, /*sq_concat*/
- 0, /*sq_repeat*/
- 0, /*sq_item*/
- 0, /*sq_slice*/
- 0, /*sq_ass_item*/
- 0, /*sq_ass_slice*/
- 0, /*sq_contains*/
- 0, /*sq_inplace_concat*/
- 0, /*sq_inplace_repeat*/
-};
-
-static PyMappingMethods __pyx_tp_as_mapping_PyCFRunLoop = {
- 0, /*mp_length*/
- 0, /*mp_subscript*/
- 0, /*mp_ass_subscript*/
-};
-
-static PyBufferProcs __pyx_tp_as_buffer_PyCFRunLoop = {
- 0, /*bf_getreadbuffer*/
- 0, /*bf_getwritebuffer*/
- 0, /*bf_getsegcount*/
- 0, /*bf_getcharbuffer*/
-};
-
-statichere PyTypeObject __pyx_type_9cfsupport_PyCFRunLoop = {
- PyObject_HEAD_INIT(0)
- 0, /*ob_size*/
- "cfsupport.PyCFRunLoop", /*tp_name*/
- sizeof(struct __pyx_obj_9cfsupport_PyCFRunLoop), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- __pyx_tp_dealloc_9cfsupport_PyCFRunLoop, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- &__pyx_tp_as_number_PyCFRunLoop, /*tp_as_number*/
- &__pyx_tp_as_sequence_PyCFRunLoop, /*tp_as_sequence*/
- &__pyx_tp_as_mapping_PyCFRunLoop, /*tp_as_mapping*/
- 0, /*tp_hash*/
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- &__pyx_tp_as_buffer_PyCFRunLoop, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/
- 0, /*tp_doc*/
- __pyx_tp_traverse_9cfsupport_PyCFRunLoop, /*tp_traverse*/
- __pyx_tp_clear_9cfsupport_PyCFRunLoop, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- __pyx_methods_9cfsupport_PyCFRunLoop, /*tp_methods*/
- __pyx_members_9cfsupport_PyCFRunLoop, /*tp_members*/
- 0, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- 0, /*tp_init*/
- 0, /*tp_alloc*/
- __pyx_tp_new_9cfsupport_PyCFRunLoop, /*tp_new*/
- 0, /*tp_free*/
- 0, /*tp_is_gc*/
- 0, /*tp_bases*/
- 0, /*tp_mro*/
- 0, /*tp_cache*/
- 0, /*tp_subclasses*/
- 0, /*tp_weaklist*/
-};
-
-static struct PyMethodDef __pyx_methods[] = {
- {"now", (PyCFunction)__pyx_f_9cfsupport_now, METH_VARARGS|METH_KEYWORDS, 0},
- {0, 0, 0, 0}
-};
-
-DL_EXPORT(void) initcfsupport(void); /*proto*/
-DL_EXPORT(void) initcfsupport(void) {
- PyObject *__pyx_1 = 0;
- __pyx_m = Py_InitModule4("cfsupport", __pyx_methods, 0, 0, PYTHON_API_VERSION);
- if (!__pyx_m) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1; goto __pyx_L1;};
- __pyx_b = PyImport_AddModule("__builtin__");
- if (!__pyx_b) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1; goto __pyx_L1;};
- if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1; goto __pyx_L1;};
- if (__Pyx_InternStrings(__pyx_intern_tab) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1; goto __pyx_L1;};
- if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 1; goto __pyx_L1;};
- __pyx_type_9cfsupport_PyCFSocket.tp_free = _PyObject_GC_Del;
- if (PyType_Ready(&__pyx_type_9cfsupport_PyCFSocket) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 34; goto __pyx_L1;}
- if (PyObject_SetAttrString(__pyx_m, "PyCFSocket", (PyObject *)&__pyx_type_9cfsupport_PyCFSocket) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 34; goto __pyx_L1;}
- __pyx_ptype_9cfsupport_PyCFSocket = &__pyx_type_9cfsupport_PyCFSocket;
- __pyx_type_9cfsupport_PyCFRunLoopTimer.tp_free = _PyObject_GC_Del;
- if (PyType_Ready(&__pyx_type_9cfsupport_PyCFRunLoopTimer) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 5; goto __pyx_L1;}
- if (PyObject_SetAttrString(__pyx_m, "PyCFRunLoopTimer", (PyObject *)&__pyx_type_9cfsupport_PyCFRunLoopTimer) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 5; goto __pyx_L1;}
- __pyx_ptype_9cfsupport_PyCFRunLoopTimer = &__pyx_type_9cfsupport_PyCFRunLoopTimer;
- __pyx_type_9cfsupport_PyCFRunLoop.tp_free = _PyObject_GC_Del;
- if (PyType_Ready(&__pyx_type_9cfsupport_PyCFRunLoop) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 49; goto __pyx_L1;}
- if (PyObject_SetAttrString(__pyx_m, "PyCFRunLoop", (PyObject *)&__pyx_type_9cfsupport_PyCFRunLoop) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 49; goto __pyx_L1;}
- __pyx_ptype_9cfsupport_PyCFRunLoop = &__pyx_type_9cfsupport_PyCFRunLoop;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":1 */
- __pyx_1 = __Pyx_Import(__pyx_n_traceback, 0); if (!__pyx_1) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; goto __pyx_L1;}
- if (PyObject_SetAttr(__pyx_m, __pyx_n_traceback, __pyx_1) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1; goto __pyx_L1;}
- Py_DECREF(__pyx_1); __pyx_1 = 0;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsocket.pxi":45 */
- Py_INCREF(Py_None);
- __pyx_k2 = Py_None;
- Py_INCREF(Py_None);
- __pyx_k3 = Py_None;
- Py_INCREF(Py_None);
- __pyx_k4 = Py_None;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":1 */
- __pyx_1 = __Pyx_Import(__pyx_n_traceback, 0); if (!__pyx_1) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1; goto __pyx_L1;}
- if (PyObject_SetAttr(__pyx_m, __pyx_n_traceback, __pyx_1) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1; goto __pyx_L1;}
- Py_DECREF(__pyx_1); __pyx_1 = 0;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfrunloop.pxi":52 */
- Py_INCREF(Py_None);
- __pyx_k6 = Py_None;
-
- /* "/Volumes/Crack/src/Twisted/twisted/internet/cfsupport/cfsupport.pyx":6 */
- if (PyObject_SetAttr(__pyx_m, __pyx_n___version__, __pyx_k7p) < 0) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 6; goto __pyx_L1;}
- return;
- __pyx_L1:;
- Py_XDECREF(__pyx_1);
- __Pyx_AddTraceback("cfsupport");
-}
-
-static char *__pyx_filenames[] = {
- "cfdate.pxi",
- "cfsocket.pxi",
- "cfrunloop.pxi",
- "cfsupport.pyx",
-};
-statichere char **__pyx_f = __pyx_filenames;
-
-/* Runtime support code */
-
-static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, char *name) {
- if (!type) {
- PyErr_Format(PyExc_SystemError, "Missing type object");
- return 0;
- }
- if ((none_allowed && obj == Py_None) || PyObject_TypeCheck(obj, type))
- return 1;
- PyErr_Format(PyExc_TypeError,
- "Argument '%s' has incorrect type (expected %s, got %s)",
- name, type->tp_name, obj->ob_type->tp_name);
- return 0;
-}
-
-static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list) {
- PyObject *__import__ = 0;
- PyObject *empty_list = 0;
- PyObject *module = 0;
- PyObject *global_dict = 0;
- PyObject *empty_dict = 0;
- PyObject *list;
- __import__ = PyObject_GetAttrString(__pyx_b, "__import__");
- if (!__import__)
- goto bad;
- if (from_list)
- list = from_list;
- else {
- empty_list = PyList_New(0);
- if (!empty_list)
- goto bad;
- list = empty_list;
- }
- global_dict = PyModule_GetDict(__pyx_m);
- if (!global_dict)
- goto bad;
- empty_dict = PyDict_New();
- if (!empty_dict)
- goto bad;
- module = PyObject_CallFunction(__import__, "OOOO",
- name, global_dict, empty_dict, list);
-bad:
- Py_XDECREF(empty_list);
- Py_XDECREF(__import__);
- Py_XDECREF(empty_dict);
- return module;
-}
-
-static PyObject *__Pyx_GetExcValue(void) {
- PyObject *type = 0, *value = 0, *tb = 0;
- PyObject *result = 0;
- PyThreadState *tstate = PyThreadState_Get();
- PyErr_Fetch(&type, &value, &tb);
- PyErr_NormalizeException(&type, &value, &tb);
- if (PyErr_Occurred())
- goto bad;
- if (!value) {
- value = Py_None;
- Py_INCREF(value);
- }
- Py_XDECREF(tstate->exc_type);
- Py_XDECREF(tstate->exc_value);
- Py_XDECREF(tstate->exc_traceback);
- tstate->exc_type = type;
- tstate->exc_value = value;
- tstate->exc_traceback = tb;
- result = value;
- Py_XINCREF(result);
- type = 0;
- value = 0;
- tb = 0;
-bad:
- Py_XDECREF(type);
- Py_XDECREF(value);
- Py_XDECREF(tb);
- return result;
-}
-
-static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) {
- PyObject *result;
- result = PyObject_GetAttr(dict, name);
- if (!result)
- PyErr_SetObject(PyExc_NameError, name);
- return result;
-}
-
-static void __Pyx_WriteUnraisable(char *name) {
- PyObject *old_exc, *old_val, *old_tb;
- PyObject *ctx;
- PyErr_Fetch(&old_exc, &old_val, &old_tb);
- ctx = PyString_FromString(name);
- PyErr_Restore(old_exc, old_val, old_tb);
- if (!ctx)
- ctx = Py_None;
- PyErr_WriteUnraisable(ctx);
-}
-
-static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb) {
- Py_XINCREF(type);
- Py_XINCREF(value);
- Py_XINCREF(tb);
- /* First, check the traceback argument, replacing None with NULL. */
- if (tb == Py_None) {
- Py_DECREF(tb);
- tb = 0;
- }
- else if (tb != NULL && !PyTraceBack_Check(tb)) {
- PyErr_SetString(PyExc_TypeError,
- "raise: arg 3 must be a traceback or None");
- goto raise_error;
- }
- /* Next, replace a missing value with None */
- if (value == NULL) {
- value = Py_None;
- Py_INCREF(value);
- }
- /* Next, repeatedly, replace a tuple exception with its first item */
- while (PyTuple_Check(type) && PyTuple_Size(type) > 0) {
- PyObject *tmp = type;
- type = PyTuple_GET_ITEM(type, 0);
- Py_INCREF(type);
- Py_DECREF(tmp);
- }
- if (PyString_Check(type))
- ;
- else if (PyClass_Check(type))
- ; /*PyErr_NormalizeException(&type, &value, &tb);*/
- else if (PyInstance_Check(type)) {
- /* Raising an instance. The value should be a dummy. */
- if (value != Py_None) {
- PyErr_SetString(PyExc_TypeError,
- "instance exception may not have a separate value");
- goto raise_error;
- }
- else {
- /* Normalize to raise <class>, <instance> */
- Py_DECREF(value);
- value = type;
- type = (PyObject*) ((PyInstanceObject*)type)->in_class;
- Py_INCREF(type);
- }
- }
- else {
- /* Not something you can raise. You get an exception
- anyway, just not what you specified :-) */
- PyErr_Format(PyExc_TypeError,
- "exceptions must be strings, classes, or "
- "instances, not %s", type->ob_type->tp_name);
- goto raise_error;
- }
- PyErr_Restore(type, value, tb);
- return;
-raise_error:
- Py_XDECREF(value);
- Py_XDECREF(type);
- Py_XDECREF(tb);
- return;
-}
-
-static void __Pyx_ReRaise(void) {
- PyThreadState *tstate = PyThreadState_Get();
- PyObject *type = tstate->exc_type;
- PyObject *value = tstate->exc_value;
- PyObject *tb = tstate->exc_traceback;
- Py_XINCREF(type);
- Py_XINCREF(value);
- Py_XINCREF(tb);
- PyErr_Restore(type, value, tb);
-}
-
-static int __Pyx_InternStrings(__Pyx_InternTabEntry *t) {
- while (t->p) {
- *t->p = PyString_InternFromString(t->s);
- if (!*t->p)
- return -1;
- ++t;
- }
- return 0;
-}
-
-static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) {
- while (t->p) {
- *t->p = PyString_FromStringAndSize(t->s, t->n - 1);
- if (!*t->p)
- return -1;
- ++t;
- }
- return 0;
-}
-
-#include "compile.h"
-#include "frameobject.h"
-#include "traceback.h"
-
-static void __Pyx_AddTraceback(char *funcname) {
- PyObject *py_srcfile = 0;
- PyObject *py_funcname = 0;
- PyObject *py_globals = 0;
- PyObject *empty_tuple = 0;
- PyObject *empty_string = 0;
- PyCodeObject *py_code = 0;
- PyFrameObject *py_frame = 0;
-
- py_srcfile = PyString_FromString(__pyx_filename);
- if (!py_srcfile) goto bad;
- py_funcname = PyString_FromString(funcname);
- if (!py_funcname) goto bad;
- py_globals = PyModule_GetDict(__pyx_m);
- if (!py_globals) goto bad;
- empty_tuple = PyTuple_New(0);
- if (!empty_tuple) goto bad;
- empty_string = PyString_FromString("");
- if (!empty_string) goto bad;
- py_code = PyCode_New(
- 0, /*int argcount,*/
- 0, /*int nlocals,*/
- 0, /*int stacksize,*/
- 0, /*int flags,*/
- empty_string, /*PyObject *code,*/
- empty_tuple, /*PyObject *consts,*/
- empty_tuple, /*PyObject *names,*/
- empty_tuple, /*PyObject *varnames,*/
- empty_tuple, /*PyObject *freevars,*/
- empty_tuple, /*PyObject *cellvars,*/
- py_srcfile, /*PyObject *filename,*/
- py_funcname, /*PyObject *name,*/
- __pyx_lineno, /*int firstlineno,*/
- empty_string /*PyObject *lnotab*/
- );
- if (!py_code) goto bad;
- py_frame = PyFrame_New(
- PyThreadState_Get(), /*PyThreadState *tstate,*/
- py_code, /*PyCodeObject *code,*/
- py_globals, /*PyObject *globals,*/
- 0 /*PyObject *locals*/
- );
- if (!py_frame) goto bad;
- py_frame->f_lineno = __pyx_lineno;
- PyTraceBack_Here(py_frame);
-bad:
- Py_XDECREF(py_srcfile);
- Py_XDECREF(py_funcname);
- Py_XDECREF(empty_tuple);
- Py_XDECREF(empty_string);
- Py_XDECREF(py_code);
- Py_XDECREF(py_frame);
-}
diff --git a/tools/buildbot/pylibs/twisted/internet/cfsupport/cfsupport.pyx b/tools/buildbot/pylibs/twisted/internet/cfsupport/cfsupport.pyx
deleted file mode 100644
index 0b2afd5..0000000
--- a/tools/buildbot/pylibs/twisted/internet/cfsupport/cfsupport.pyx
+++ /dev/null
@@ -1,6 +0,0 @@
-include "python.pxi"
-include "cfdecl.pxi"
-include "cfdate.pxi"
-include "cfsocket.pxi"
-include "cfrunloop.pxi"
-__version__ = '0.4'
diff --git a/tools/buildbot/pylibs/twisted/internet/cfsupport/python.pxi b/tools/buildbot/pylibs/twisted/internet/cfsupport/python.pxi
deleted file mode 100644
index 2f97458..0000000
--- a/tools/buildbot/pylibs/twisted/internet/cfsupport/python.pxi
+++ /dev/null
@@ -1,5 +0,0 @@
-cdef extern from "Python.h":
- ctypedef void *PyGILState_STATE
- void PyErr_Clear()
- PyGILState_STATE PyGILState_Ensure()
- void PyGILState_Release(PyGILState_STATE)
diff --git a/tools/buildbot/pylibs/twisted/internet/cfsupport/setup.py b/tools/buildbot/pylibs/twisted/internet/cfsupport/setup.py
deleted file mode 100644
index e5b3b2d..0000000
--- a/tools/buildbot/pylibs/twisted/internet/cfsupport/setup.py
+++ /dev/null
@@ -1,50 +0,0 @@
-from distutils.core import setup
-from distutils.extension import Extension
-try:
- from Pyrex.Distutils import build_ext
- # pyrex is available
- setup(
- name = 'cfsupport',
- version = '0.4',
- description = "Enough CoreFoundation wrappers to deal with CFRunLoop",
- long_description = "Pythonic wrappers for pieces of Apple's CoreFoundation API's that are not otherwise wrapped by MacPython.\nPrimarily useful for dealing with CFRunLoop.",
- maintainer = 'Bob Ippolito',
- maintainer_email = 'bob@redivi.com',
- license = 'Python',
- platforms = ['Mac OSX'],
- keywords = ['CoreFoundation', 'CFRunLoop', 'Cocoa', 'GUI'],
- ext_modules=[
- Extension(
- 'cfsupport',
- ['cfsupport.pyx'],
- extra_link_args=[
- '-framework','CoreFoundation',
- '-framework','CoreServices',
- ],
- ),
- ],
- cmdclass = {'build_ext': build_ext}
- )
-except ImportError:
- # pyrex is not available, use existing .c
- setup(
- name = 'cfsupport',
- version = '0.4',
- description = "Enough CoreFoundation wrappers to deal with CFRunLoop",
- long_description = "Pythonic wrappers for pieces of Apple's CoreFoundation API's that are not otherwise wrapped by MacPython.\nPrimarily useful for dealing with CFRunLoop.",
- maintainer = 'Bob Ippolito',
- maintainer_email = 'bob@redivi.com',
- license = 'Python',
- platforms = ['Mac OSX'],
- keywords = ['CoreFoundation', 'CFRunLoop', 'Cocoa', 'GUI'],
- ext_modules=[
- Extension(
- 'cfsupport',
- ['cfsupport.c'],
- extra_link_args=[
- '-framework','CoreFoundation',
- '-framework','CoreServices',
- ],
- ),
- ],
- )
diff --git a/tools/buildbot/pylibs/twisted/internet/default.py b/tools/buildbot/pylibs/twisted/internet/default.py
deleted file mode 100644
index 6207525..0000000
--- a/tools/buildbot/pylibs/twisted/internet/default.py
+++ /dev/null
@@ -1,21 +0,0 @@
-# -*- test-case-name: twisted.test.test_internet -*-
-# $Id: default.py,v 1.90 2004/01/06 22:35:22 warner Exp $
-#
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-Deprecated module that used to contain SelectReactor and PosixReactorBase
-
-Maintainer: U{Itamar Shtull-Trauring<mailto:twisted@itamarst.org>}
-"""
-
-import warnings
-warnings.warn("twisted.internet.default is deprecated. Use posixbase or selectreactor instead.", category=DeprecationWarning)
-
-# Backwards compat
-from posixbase import PosixReactorBase
-from selectreactor import SelectReactor, install
-
-__all__ = ["install", "PosixReactorBase", "SelectReactor"]
diff --git a/tools/buildbot/pylibs/twisted/internet/defer.py b/tools/buildbot/pylibs/twisted/internet/defer.py
deleted file mode 100644
index 8980a13..0000000
--- a/tools/buildbot/pylibs/twisted/internet/defer.py
+++ /dev/null
@@ -1,1107 +0,0 @@
-# -*- test-case-name: twisted.test.test_defer -*-
-#
-# Copyright (c) 2001-2007 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Support for results that aren't immediately available.
-
-Maintainer: U{Glyph Lefkowitz<mailto:glyph@twistedmatrix.com>}
-"""
-
-from __future__ import nested_scopes, generators
-import traceback
-import warnings
-
-# Twisted imports
-from twisted.python import log, failure, lockfile
-from twisted.python.util import unsignedID, mergeFunctionMetadata
-
-class AlreadyCalledError(Exception):
- pass
-
-class TimeoutError(Exception):
- pass
-
-def logError(err):
- log.err(err)
- return err
-
-def succeed(result):
- """
- Return a Deferred that has already had '.callback(result)' called.
-
- This is useful when you're writing synchronous code to an
- asynchronous interface: i.e., some code is calling you expecting a
- Deferred result, but you don't actually need to do anything
- asynchronous. Just return defer.succeed(theResult).
-
- See L{fail} for a version of this function that uses a failing
- Deferred rather than a successful one.
-
- @param result: The result to give to the Deferred's 'callback'
- method.
-
- @rtype: L{Deferred}
- """
- d = Deferred()
- d.callback(result)
- return d
-
-
-def fail(result=None):
- """
- Return a Deferred that has already had '.errback(result)' called.
-
- See L{succeed}'s docstring for rationale.
-
- @param result: The same argument that L{Deferred.errback} takes.
-
- @raise NoCurrentExceptionError: If C{result} is C{None} but there is no
- current exception state.
-
- @rtype: L{Deferred}
- """
- d = Deferred()
- d.errback(result)
- return d
-
-
-def execute(callable, *args, **kw):
- """Create a deferred from a callable and arguments.
-
- Call the given function with the given arguments. Return a deferred which
- has been fired with its callback as the result of that invocation or its
- errback with a Failure for the exception thrown.
- """
- try:
- result = callable(*args, **kw)
- except:
- return fail()
- else:
- return succeed(result)
-
-def maybeDeferred(f, *args, **kw):
- """Invoke a function that may or may not return a deferred.
-
- Call the given function with the given arguments. If the returned
- object is a C{Deferred}, return it. If the returned object is a C{Failure},
- wrap it with C{fail} and return it. Otherwise, wrap it in C{succeed} and
- return it. If an exception is raised, convert it to a C{Failure}, wrap it
- in C{fail}, and then return it.
-
- @type f: Any callable
- @param f: The callable to invoke
-
- @param args: The arguments to pass to C{f}
- @param kw: The keyword arguments to pass to C{f}
-
- @rtype: C{Deferred}
- @return: The result of the function call, wrapped in a C{Deferred} if
- necessary.
- """
- deferred = None
-
- try:
- result = f(*args, **kw)
- except:
- return fail(failure.Failure())
- else:
- if isinstance(result, Deferred):
- return result
- elif isinstance(result, failure.Failure):
- return fail(result)
- else:
- return succeed(result)
- return deferred
-
-def timeout(deferred):
- deferred.errback(failure.Failure(TimeoutError("Callback timed out")))
-
-def passthru(arg):
- return arg
-
-def setDebugging(on):
- """Enable or disable Deferred debugging.
-
- When debugging is on, the call stacks from creation and invocation are
- recorded, and added to any AlreadyCalledErrors we raise.
- """
- Deferred.debug=bool(on)
-
-def getDebugging():
- """Determine whether Deferred debugging is enabled.
- """
- return Deferred.debug
-
-class Deferred:
- """This is a callback which will be put off until later.
-
- Why do we want this? Well, in cases where a function in a threaded
- program would block until it gets a result, for Twisted it should
- not block. Instead, it should return a Deferred.
-
- This can be implemented for protocols that run over the network by
- writing an asynchronous protocol for twisted.internet. For methods
- that come from outside packages that are not under our control, we use
- threads (see for example L{twisted.enterprise.adbapi}).
-
- For more information about Deferreds, see doc/howto/defer.html or
- U{http://twistedmatrix.com/projects/core/documentation/howto/defer.html}
- """
- called = 0
- paused = 0
- timeoutCall = None
- _debugInfo = None
-
- # Are we currently running a user-installed callback? Meant to prevent
- # recursive running of callbacks when a reentrant call to add a callback is
- # used.
- _runningCallbacks = False
-
- # Keep this class attribute for now, for compatibility with code that
- # sets it directly.
- debug = False
-
- def __init__(self):
- self.callbacks = []
- if self.debug:
- self._debugInfo = DebugInfo()
- self._debugInfo.creator = traceback.format_stack()[:-1]
-
- def addCallbacks(self, callback, errback=None,
- callbackArgs=None, callbackKeywords=None,
- errbackArgs=None, errbackKeywords=None):
- """Add a pair of callbacks (success and error) to this Deferred.
-
- These will be executed when the 'master' callback is run.
- """
- assert callable(callback)
- assert errback == None or callable(errback)
- cbs = ((callback, callbackArgs, callbackKeywords),
- (errback or (passthru), errbackArgs, errbackKeywords))
- self.callbacks.append(cbs)
-
- if self.called:
- self._runCallbacks()
- return self
-
- def addCallback(self, callback, *args, **kw):
- """Convenience method for adding just a callback.
-
- See L{addCallbacks}.
- """
- return self.addCallbacks(callback, callbackArgs=args,
- callbackKeywords=kw)
-
- def addErrback(self, errback, *args, **kw):
- """Convenience method for adding just an errback.
-
- See L{addCallbacks}.
- """
- return self.addCallbacks(passthru, errback,
- errbackArgs=args,
- errbackKeywords=kw)
-
- def addBoth(self, callback, *args, **kw):
- """Convenience method for adding a single callable as both a callback
- and an errback.
-
- See L{addCallbacks}.
- """
- return self.addCallbacks(callback, callback,
- callbackArgs=args, errbackArgs=args,
- callbackKeywords=kw, errbackKeywords=kw)
-
- def chainDeferred(self, d):
- """Chain another Deferred to this Deferred.
-
- This method adds callbacks to this Deferred to call d's callback or
- errback, as appropriate. It is merely a shorthand way of performing
- the following::
-
- self.addCallbacks(d.callback, d.errback)
-
- When you chain a deferred d2 to another deferred d1 with
- d1.chainDeferred(d2), you are making d2 participate in the callback
- chain of d1. Thus any event that fires d1 will also fire d2.
- However, the converse is B{not} true; if d2 is fired d1 will not be
- affected.
- """
- return self.addCallbacks(d.callback, d.errback)
-
- def callback(self, result):
- """Run all success callbacks that have been added to this Deferred.
-
- Each callback will have its result passed as the first
- argument to the next; this way, the callbacks act as a
- 'processing chain'. Also, if the success-callback returns a Failure
- or raises an Exception, processing will continue on the *error*-
- callback chain.
- """
- assert not isinstance(result, Deferred)
- self._startRunCallbacks(result)
-
-
- def errback(self, fail=None):
- """
- Run all error callbacks that have been added to this Deferred.
-
- Each callback will have its result passed as the first
- argument to the next; this way, the callbacks act as a
- 'processing chain'. Also, if the error-callback returns a non-Failure
- or doesn't raise an Exception, processing will continue on the
- *success*-callback chain.
-
- If the argument that's passed to me is not a failure.Failure instance,
- it will be embedded in one. If no argument is passed, a failure.Failure
- instance will be created based on the current traceback stack.
-
- Passing a string as `fail' is deprecated, and will be punished with
- a warning message.
-
- @raise NoCurrentExceptionError: If C{fail} is C{None} but there is
- no current exception state.
- """
- if not isinstance(fail, failure.Failure):
- fail = failure.Failure(fail)
-
- self._startRunCallbacks(fail)
-
-
- def pause(self):
- """Stop processing on a Deferred until L{unpause}() is called.
- """
- self.paused = self.paused + 1
-
-
- def unpause(self):
- """Process all callbacks made since L{pause}() was called.
- """
- self.paused = self.paused - 1
- if self.paused:
- return
- if self.called:
- self._runCallbacks()
-
- def _continue(self, result):
- self.result = result
- self.unpause()
-
- def _startRunCallbacks(self, result):
- if self.called:
- if self.debug:
- if self._debugInfo is None:
- self._debugInfo = DebugInfo()
- extra = "\n" + self._debugInfo._getDebugTracebacks()
- raise AlreadyCalledError(extra)
- raise AlreadyCalledError
- if self.debug:
- if self._debugInfo is None:
- self._debugInfo = DebugInfo()
- self._debugInfo.invoker = traceback.format_stack()[:-2]
- self.called = True
- self.result = result
- if self.timeoutCall:
- try:
- self.timeoutCall.cancel()
- except:
- pass
-
- del self.timeoutCall
- self._runCallbacks()
-
- def _runCallbacks(self):
- if self._runningCallbacks:
- # Don't recursively run callbacks
- return
- if not self.paused:
- while self.callbacks:
- item = self.callbacks.pop(0)
- callback, args, kw = item[
- isinstance(self.result, failure.Failure)]
- args = args or ()
- kw = kw or {}
- try:
- self._runningCallbacks = True
- try:
- self.result = callback(self.result, *args, **kw)
- finally:
- self._runningCallbacks = False
- if isinstance(self.result, Deferred):
- # note: this will cause _runCallbacks to be called
- # recursively if self.result already has a result.
- # This shouldn't cause any problems, since there is no
- # relevant state in this stack frame at this point.
- # The recursive call will continue to process
- # self.callbacks until it is empty, then return here,
- # where there is no more work to be done, so this call
- # will return as well.
- self.pause()
- self.result.addBoth(self._continue)
- break
- except:
- self.result = failure.Failure()
-
- if isinstance(self.result, failure.Failure):
- self.result.cleanFailure()
- if self._debugInfo is None:
- self._debugInfo = DebugInfo()
- self._debugInfo.failResult = self.result
- else:
- if self._debugInfo is not None:
- self._debugInfo.failResult = None
-
- def setTimeout(self, seconds, timeoutFunc=timeout, *args, **kw):
- """Set a timeout function to be triggered if I am not called.
-
- @param seconds: How long to wait (from now) before firing the
- timeoutFunc.
-
- @param timeoutFunc: will receive the Deferred and *args, **kw as its
- arguments. The default timeoutFunc will call the errback with a
- L{TimeoutError}.
- """
- warnings.warn(
- "Deferred.setTimeout is deprecated. Look for timeout "
- "support specific to the API you are using instead.",
- DeprecationWarning, stacklevel=2)
-
- if self.called:
- return
- assert not self.timeoutCall, "Don't call setTimeout twice on the same Deferred."
-
- from twisted.internet import reactor
- self.timeoutCall = reactor.callLater(
- seconds,
- lambda: self.called or timeoutFunc(self, *args, **kw))
- return self.timeoutCall
-
- def __str__(self):
- cname = self.__class__.__name__
- if hasattr(self, 'result'):
- return "<%s at %s current result: %r>" % (cname, hex(unsignedID(self)),
- self.result)
- return "<%s at %s>" % (cname, hex(unsignedID(self)))
- __repr__ = __str__
-
-class DebugInfo:
- """Deferred debug helper"""
- failResult = None
-
- def _getDebugTracebacks(self):
- info = ''
- if hasattr(self, "creator"):
- info += " C: Deferred was created:\n C:"
- info += "".join(self.creator).rstrip().replace("\n","\n C:")
- info += "\n"
- if hasattr(self, "invoker"):
- info += " I: First Invoker was:\n I:"
- info += "".join(self.invoker).rstrip().replace("\n","\n I:")
- info += "\n"
- return info
-
- def __del__(self):
- """Print tracebacks and die.
-
- If the *last* (and I do mean *last*) callback leaves me in an error
- state, print a traceback (if said errback is a Failure).
- """
- if self.failResult is not None:
- log.msg("Unhandled error in Deferred:", isError=True)
- debugInfo = self._getDebugTracebacks()
- if debugInfo != '':
- log.msg("(debug: " + debugInfo + ")", isError=True)
- log.err(self.failResult)
-
-class FirstError(Exception):
- """First error to occur in a DeferredList if fireOnOneErrback is set.
-
- @ivar subFailure: the L{Failure} that occurred.
- @ivar index: the index of the Deferred in the DeferredList where it
- happened.
- """
- def __init__(self, failure, index):
- self.subFailure = failure
- self.index = index
-
- def __repr__(self):
- return 'FirstError(%r, %d)' % (self.subFailure, self.index)
-
- def __str__(self):
- return repr(self)
-
- def __getitem__(self, index):
- warnings.warn("FirstError.__getitem__ is deprecated. "
- "Use attributes instead.",
- category=DeprecationWarning, stacklevel=2)
- return [self.subFailure, self.index][index]
-
- def __getslice__(self, start, stop):
- warnings.warn("FirstError.__getslice__ is deprecated. "
- "Use attributes instead.",
- category=DeprecationWarning, stacklevel=2)
- return [self.subFailure, self.index][start:stop]
-
- def __eq__(self, other):
- if isinstance(other, tuple):
- return tuple(self) == other
- elif isinstance(other, FirstError):
- return (self.subFailure == other.subFailure and
- self.index == other.index)
- return False
-
-class DeferredList(Deferred):
- """I combine a group of deferreds into one callback.
-
- I track a list of L{Deferred}s for their callbacks, and make a single
- callback when they have all completed, a list of (success, result)
- tuples, 'success' being a boolean.
-
- Note that you can still use a L{Deferred} after putting it in a
- DeferredList. For example, you can suppress 'Unhandled error in Deferred'
- messages by adding errbacks to the Deferreds *after* putting them in the
- DeferredList, as a DeferredList won't swallow the errors. (Although a more
- convenient way to do this is simply to set the consumeErrors flag)
- """
-
- fireOnOneCallback = 0
- fireOnOneErrback = 0
-
- def __init__(self, deferredList, fireOnOneCallback=0, fireOnOneErrback=0,
- consumeErrors=0):
- """Initialize a DeferredList.
-
- @type deferredList: C{list} of L{Deferred}s
- @param deferredList: The list of deferreds to track.
- @param fireOnOneCallback: (keyword param) a flag indicating that
- only one callback needs to be fired for me to call
- my callback
- @param fireOnOneErrback: (keyword param) a flag indicating that
- only one errback needs to be fired for me to call
- my errback
- @param consumeErrors: (keyword param) a flag indicating that any errors
- raised in the original deferreds should be
- consumed by this DeferredList. This is useful to
- prevent spurious warnings being logged.
- """
- self.resultList = [None] * len(deferredList)
- Deferred.__init__(self)
- if len(deferredList) == 0 and not fireOnOneCallback:
- self.callback(self.resultList)
-
- # These flags need to be set *before* attaching callbacks to the
- # deferreds, because the callbacks use these flags, and will run
- # synchronously if any of the deferreds are already fired.
- self.fireOnOneCallback = fireOnOneCallback
- self.fireOnOneErrback = fireOnOneErrback
- self.consumeErrors = consumeErrors
- self.finishedCount = 0
-
- index = 0
- for deferred in deferredList:
- deferred.addCallbacks(self._cbDeferred, self._cbDeferred,
- callbackArgs=(index,SUCCESS),
- errbackArgs=(index,FAILURE))
- index = index + 1
-
- def _cbDeferred(self, result, index, succeeded):
- """(internal) Callback for when one of my deferreds fires.
- """
- self.resultList[index] = (succeeded, result)
-
- self.finishedCount += 1
- if not self.called:
- if succeeded == SUCCESS and self.fireOnOneCallback:
- self.callback((result, index))
- elif succeeded == FAILURE and self.fireOnOneErrback:
- self.errback(failure.Failure(FirstError(result, index)))
- elif self.finishedCount == len(self.resultList):
- self.callback(self.resultList)
-
- if succeeded == FAILURE and self.consumeErrors:
- result = None
-
- return result
-
-
-def _parseDListResult(l, fireOnOneErrback=0):
- if __debug__:
- for success, value in l:
- assert success
- return [x[1] for x in l]
-
-def gatherResults(deferredList):
- """Returns list with result of given Deferreds.
-
- This builds on C{DeferredList} but is useful since you don't
- need to parse the result for success/failure.
-
- @type deferredList: C{list} of L{Deferred}s
- """
- d = DeferredList(deferredList, fireOnOneErrback=1)
- d.addCallback(_parseDListResult)
- return d
-
-# Constants for use with DeferredList
-
-SUCCESS = True
-FAILURE = False
-
-
-
-## deferredGenerator
-
-class waitForDeferred:
- """
- See L{deferredGenerator}.
- """
-
- def __init__(self, d):
- if not isinstance(d, Deferred):
- raise TypeError("You must give waitForDeferred a Deferred. You gave it %r." % (d,))
- self.d = d
-
-
- def getResult(self):
- if isinstance(self.result, failure.Failure):
- self.result.raiseException()
- return self.result
-
-
-
-def _deferGenerator(g, deferred):
- """
- See L{deferredGenerator}.
- """
- result = None
-
- # This function is complicated by the need to prevent unbounded recursion
- # arising from repeatedly yielding immediately ready deferreds. This while
- # loop and the waiting variable solve that by manually unfolding the
- # recursion.
-
- waiting = [True, # defgen is waiting for result?
- None] # result
-
- while 1:
- try:
- result = g.next()
- except StopIteration:
- deferred.callback(result)
- return deferred
- except:
- deferred.errback()
- return deferred
-
- # Deferred.callback(Deferred) raises an error; we catch this case
- # early here and give a nicer error message to the user in case
- # they yield a Deferred.
- if isinstance(result, Deferred):
- return fail(TypeError("Yield waitForDeferred(d), not d!"))
-
- if isinstance(result, waitForDeferred):
- # a waitForDeferred was yielded, get the result.
- # Pass result in so it don't get changed going around the loop
- # This isn't a problem for waiting, as it's only reused if
- # gotResult has already been executed.
- def gotResult(r, result=result):
- result.result = r
- if waiting[0]:
- waiting[0] = False
- waiting[1] = r
- else:
- _deferGenerator(g, deferred)
- result.d.addBoth(gotResult)
- if waiting[0]:
- # Haven't called back yet, set flag so that we get reinvoked
- # and return from the loop
- waiting[0] = False
- return deferred
- # Reset waiting to initial values for next loop
- waiting[0] = True
- waiting[1] = None
-
- result = None
-
-
-
-def deferredGenerator(f):
- """
- Maintainer: U{Christopher Armstrong<mailto:radix@twistedmatrix.com>}
-
- deferredGenerator and waitForDeferred help you write Deferred-using code
- that looks like a regular sequential function. If your code has a minimum
- requirement of Python 2.5, consider the use of L{inlineCallbacks} instead,
- which can accomplish the same thing in a more concise manner.
-
- There are two important functions involved: waitForDeferred, and
- deferredGenerator. They are used together, like this::
-
- def thingummy():
- thing = waitForDeferred(makeSomeRequestResultingInDeferred())
- yield thing
- thing = thing.getResult()
- print thing #the result! hoorj!
- thingummy = deferredGenerator(thingummy)
-
- waitForDeferred returns something that you should immediately yield; when
- your generator is resumed, calling thing.getResult() will either give you
- the result of the Deferred if it was a success, or raise an exception if it
- was a failure. Calling C{getResult} is B{absolutely mandatory}. If you do
- not call it, I{your program will not work}.
-
- deferredGenerator takes one of these waitForDeferred-using generator
- functions and converts it into a function that returns a Deferred. The
- result of the Deferred will be the last value that your generator yielded
- unless the last value is a waitForDeferred instance, in which case the
- result will be C{None}. If the function raises an unhandled exception, the
- Deferred will errback instead. Remember that 'return result' won't work;
- use 'yield result; return' in place of that.
-
- Note that not yielding anything from your generator will make the Deferred
- result in None. Yielding a Deferred from your generator is also an error
- condition; always yield waitForDeferred(d) instead.
-
- The Deferred returned from your deferred generator may also errback if your
- generator raised an exception. For example::
-
- def thingummy():
- thing = waitForDeferred(makeSomeRequestResultingInDeferred())
- yield thing
- thing = thing.getResult()
- if thing == 'I love Twisted':
- # will become the result of the Deferred
- yield 'TWISTED IS GREAT!'
- return
- else:
- # will trigger an errback
- raise Exception('DESTROY ALL LIFE')
- thingummy = deferredGenerator(thingummy)
-
- Put succinctly, these functions connect deferred-using code with this 'fake
- blocking' style in both directions: waitForDeferred converts from a
- Deferred to the 'blocking' style, and deferredGenerator converts from the
- 'blocking' style to a Deferred.
- """
- def unwindGenerator(*args, **kwargs):
- return _deferGenerator(f(*args, **kwargs), Deferred())
- return mergeFunctionMetadata(f, unwindGenerator)
-
-
-## inlineCallbacks
-
-# BaseException is only in Py 2.5.
-try:
- BaseException
-except NameError:
- BaseException=Exception
-
-class _DefGen_Return(BaseException):
- def __init__(self, value):
- self.value = value
-
-def returnValue(val):
- """
- Return val from a L{inlineCallbacks} generator.
-
- Note: this is currently implemented by raising an exception
- derived from BaseException. You might want to change any
- 'except:' clauses to an 'except Exception:' clause so as not to
- catch this exception.
-
- Also: while this function currently will work when called from
- within arbitrary functions called from within the generator, do
- not rely upon this behavior.
- """
- raise _DefGen_Return(val)
-
-def _inlineCallbacks(result, g, deferred):
- """
- See L{inlineCallbacks}.
- """
- # This function is complicated by the need to prevent unbounded recursion
- # arising from repeatedly yielding immediately ready deferreds. This while
- # loop and the waiting variable solve that by manually unfolding the
- # recursion.
-
- waiting = [True, # waiting for result?
- None] # result
-
- while 1:
- try:
- # Send the last result back as the result of the yield expression.
- if isinstance(result, failure.Failure):
- result = result.throwExceptionIntoGenerator(g)
- else:
- result = g.send(result)
- except StopIteration:
- # fell off the end, or "return" statement
- deferred.callback(None)
- return deferred
- except _DefGen_Return, e:
- # returnValue call
- deferred.callback(e.value)
- return deferred
- except:
- deferred.errback()
- return deferred
-
- if isinstance(result, Deferred):
- # a deferred was yielded, get the result.
- def gotResult(r):
- if waiting[0]:
- waiting[0] = False
- waiting[1] = r
- else:
- _inlineCallbacks(r, g, deferred)
-
- result.addBoth(gotResult)
- if waiting[0]:
- # Haven't called back yet, set flag so that we get reinvoked
- # and return from the loop
- waiting[0] = False
- return deferred
-
- result = waiting[1]
- # Reset waiting to initial values for next loop. gotResult uses
- # waiting, but this isn't a problem because gotResult is only
- # executed once, and if it hasn't been executed yet, the return
- # branch above would have been taken.
-
-
- waiting[0] = True
- waiting[1] = None
-
-
- return deferred
-
-def inlineCallbacks(f):
- """
- Maintainer: U{Christopher Armstrong<mailto:radix@twistedmatrix.com>}
-
- WARNING: this function will not work in Python 2.4 and earlier!
-
- inlineCallbacks helps you write Deferred-using code that looks like a
- regular sequential function. This function uses features of Python 2.5
- generators. If you need to be compatible with Python 2.4 or before, use
- the L{deferredGenerator} function instead, which accomplishes the same
- thing, but with somewhat more boilerplate. For example::
-
- def thingummy():
- thing = yield makeSomeRequestResultingInDeferred()
- print thing #the result! hoorj!
- thingummy = inlineCallbacks(thingummy)
-
- When you call anything that results in a Deferred, you can simply yield it;
- your generator will automatically be resumed when the Deferred's result is
- available. The generator will be sent the result of the Deferred with the
- 'send' method on generators, or if the result was a failure, 'throw'.
-
- Your inlineCallbacks-enabled generator will return a Deferred object, which
- will result in the return value of the generator (or will fail with a
- failure object if your generator raises an unhandled exception). Note that
- you can't use 'return result' to return a value; use 'returnValue(result)'
- instead. Falling off the end of the generator, or simply using 'return'
- will cause the Deferred to have a result of None.
-
- The Deferred returned from your deferred generator may errback if your
- generator raised an exception::
-
- def thingummy():
- thing = yield makeSomeRequestResultingInDeferred()
- if thing == 'I love Twisted':
- # will become the result of the Deferred
- returnValue('TWISTED IS GREAT!')
- else:
- # will trigger an errback
- raise Exception('DESTROY ALL LIFE')
- thingummy = inlineCallbacks(thingummy)
- """
- def unwindGenerator(*args, **kwargs):
- return _inlineCallbacks(None, f(*args, **kwargs), Deferred())
- return mergeFunctionMetadata(f, unwindGenerator)
-
-
-## DeferredLock/DeferredQueue
-
-class _ConcurrencyPrimitive(object):
- def __init__(self):
- self.waiting = []
-
- def _releaseAndReturn(self, r):
- self.release()
- return r
-
- def run(*args, **kwargs):
- """Acquire, run, release.
-
- This function takes a callable as its first argument and any
- number of other positional and keyword arguments. When the
- lock or semaphore is acquired, the callable will be invoked
- with those arguments.
-
- The callable may return a Deferred; if it does, the lock or
- semaphore won't be released until that Deferred fires.
-
- @return: Deferred of function result.
- """
- if len(args) < 2:
- if not args:
- raise TypeError("run() takes at least 2 arguments, none given.")
- raise TypeError("%s.run() takes at least 2 arguments, 1 given" % (
- args[0].__class__.__name__,))
- self, f = args[:2]
- args = args[2:]
-
- def execute(ignoredResult):
- d = maybeDeferred(f, *args, **kwargs)
- d.addBoth(self._releaseAndReturn)
- return d
-
- d = self.acquire()
- d.addCallback(execute)
- return d
-
-
-class DeferredLock(_ConcurrencyPrimitive):
- """
- A lock for event driven systems.
-
- @ivar locked: True when this Lock has been acquired, false at all
- other times. Do not change this value, but it is useful to
- examine for the equivalent of a \"non-blocking\" acquisition.
- """
-
- locked = 0
-
- def acquire(self):
- """Attempt to acquire the lock.
-
- @return: a Deferred which fires on lock acquisition.
- """
- d = Deferred()
- if self.locked:
- self.waiting.append(d)
- else:
- self.locked = 1
- d.callback(self)
- return d
-
- def release(self):
- """Release the lock.
-
- Should be called by whomever did the acquire() when the shared
- resource is free.
- """
- assert self.locked, "Tried to release an unlocked lock"
- self.locked = 0
- if self.waiting:
- # someone is waiting to acquire lock
- self.locked = 1
- d = self.waiting.pop(0)
- d.callback(self)
-
-class DeferredSemaphore(_ConcurrencyPrimitive):
- """
- A semaphore for event driven systems.
- """
-
- def __init__(self, tokens):
- _ConcurrencyPrimitive.__init__(self)
- self.tokens = tokens
- self.limit = tokens
-
- def acquire(self):
- """Attempt to acquire the token.
-
- @return: a Deferred which fires on token acquisition.
- """
- assert self.tokens >= 0, "Internal inconsistency?? tokens should never be negative"
- d = Deferred()
- if not self.tokens:
- self.waiting.append(d)
- else:
- self.tokens = self.tokens - 1
- d.callback(self)
- return d
-
- def release(self):
- """Release the token.
-
- Should be called by whoever did the acquire() when the shared
- resource is free.
- """
- assert self.tokens < self.limit, "Someone released me too many times: too many tokens!"
- self.tokens = self.tokens + 1
- if self.waiting:
- # someone is waiting to acquire token
- self.tokens = self.tokens - 1
- d = self.waiting.pop(0)
- d.callback(self)
-
-class QueueOverflow(Exception):
- pass
-
-class QueueUnderflow(Exception):
- pass
-
-
-class DeferredQueue(object):
- """
- An event driven queue.
-
- Objects may be added as usual to this queue. When an attempt is
- made to retrieve an object when the queue is empty, a Deferred is
- returned which will fire when an object becomes available.
-
- @ivar size: The maximum number of objects to allow into the queue
- at a time. When an attempt to add a new object would exceed this
- limit, QueueOverflow is raised synchronously. None for no limit.
-
- @ivar backlog: The maximum number of Deferred gets to allow at
- one time. When an attempt is made to get an object which would
- exceed this limit, QueueUnderflow is raised synchronously. None
- for no limit.
- """
-
- def __init__(self, size=None, backlog=None):
- self.waiting = []
- self.pending = []
- self.size = size
- self.backlog = backlog
-
- def put(self, obj):
- """Add an object to this queue.
-
- @raise QueueOverflow: Too many objects are in this queue.
- """
- if self.waiting:
- self.waiting.pop(0).callback(obj)
- elif self.size is None or len(self.pending) < self.size:
- self.pending.append(obj)
- else:
- raise QueueOverflow()
-
- def get(self):
- """Attempt to retrieve and remove an object from the queue.
-
- @return: a Deferred which fires with the next object available in the queue.
-
- @raise QueueUnderflow: Too many (more than C{backlog})
- Deferreds are already waiting for an object from this queue.
- """
- if self.pending:
- return succeed(self.pending.pop(0))
- elif self.backlog is None or len(self.waiting) < self.backlog:
- d = Deferred()
- self.waiting.append(d)
- return d
- else:
- raise QueueUnderflow()
-
-
-class AlreadyTryingToLockError(Exception):
- """
- Raised when DeferredFilesystemLock.deferUntilLocked is called twice on a
- single DeferredFilesystemLock.
- """
-
-
-class DeferredFilesystemLock(lockfile.FilesystemLock):
- """
- A FilesystemLock that allows for a deferred to be fired when the lock is
- acquired.
-
- @ivar _scheduler: The object in charge of scheduling retries. In this
- implementation this is parameterized for testing.
-
- @ivar _interval: The retry interval for an L{IReactorTime} based scheduler.
-
- @ivar _tryLockCall: A L{DelayedCall} based on _interval that will managex
- the next retry for aquiring the lock.
-
- @ivar _timeoutCall: A L{DelayedCall} based on deferUntilLocked's timeout
- argument. This is in charge of timing out our attempt to acquire the
- lock.
- """
- _interval = 1
- _tryLockCall = None
- _timeoutCall = None
-
- def __init__(self, name, scheduler=None):
- """
- @param name: The name of the lock to acquire
- @param scheduler: An object which provides L{IReactorTime}
- """
- lockfile.FilesystemLock.__init__(self, name)
-
- if scheduler is None:
- from twisted.internet import reactor
- scheduler = reactor
-
- self._scheduler = scheduler
-
- def deferUntilLocked(self, timeout=None):
- """
- Wait until we acquire this lock. This method is not safe for
- concurrent use.
-
- @type timeout: C{float} or C{int}
- @param timeout: the number of seconds after which to time out if the
- lock has not been acquired.
-
- @return: a deferred which will callback when the lock is acquired, or
- errback with a L{TimeoutError} after timing out or an
- L{AlreadyTryingToLockError} if the L{deferUntilLocked} has already
- been called and not successfully locked the file.
- """
- if self._tryLockCall is not None:
- return fail(
- AlreadyTryingToLockError(
- "deferUntilLocked isn't safe for concurrent use."))
-
- d = Deferred()
-
- def _cancelLock():
- self._tryLockCall.cancel()
- self._tryLockCall = None
- self._timeoutCall = None
-
- if self.lock():
- d.callback(None)
- else:
- d.errback(failure.Failure(
- TimeoutError("Timed out aquiring lock: %s after %fs" % (
- self.name,
- timeout))))
-
- def _tryLock():
- if self.lock():
- if self._timeoutCall is not None:
- self._timeoutCall.cancel()
- self._timeoutCall = None
-
- self._tryLockCall = None
-
- d.callback(None)
- else:
- if timeout is not None and self._timeoutCall is None:
- self._timeoutCall = self._scheduler.callLater(
- timeout, _cancelLock)
-
- self._tryLockCall = self._scheduler.callLater(
- self._interval, _tryLock)
-
- _tryLock()
-
- return d
-
-
-__all__ = ["Deferred", "DeferredList", "succeed", "fail", "FAILURE", "SUCCESS",
- "AlreadyCalledError", "TimeoutError", "gatherResults",
- "maybeDeferred",
- "waitForDeferred", "deferredGenerator", "inlineCallbacks",
- "DeferredLock", "DeferredSemaphore", "DeferredQueue",
- "DeferredFilesystemLock", "AlreadyTryingToLockError",
- ]
diff --git a/tools/buildbot/pylibs/twisted/internet/epollreactor.py b/tools/buildbot/pylibs/twisted/internet/epollreactor.py
deleted file mode 100644
index 051bf71..0000000
--- a/tools/buildbot/pylibs/twisted/internet/epollreactor.py
+++ /dev/null
@@ -1,256 +0,0 @@
-# Copyright (c) 2001-2007 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-An epoll() based implementation of the twisted main loop.
-
-To install the event loop (and you should do this before any connections,
-listeners or connectors are added)::
-
- from twisted.internet import epollreactor
- epollreactor.install()
-
-Maintainer: U{Jp Calderone <mailto:exarkun@twistedmatrix.com>}
-"""
-
-import sys, errno
-
-from zope.interface import implements
-
-from twisted.internet.interfaces import IReactorFDSet
-
-from twisted.python import _epoll
-from twisted.python import log
-from twisted.internet import posixbase, error
-from twisted.internet.main import CONNECTION_LOST
-
-
-_POLL_DISCONNECTED = (_epoll.HUP | _epoll.ERR)
-
-class EPollReactor(posixbase.PosixReactorBase):
- """
- A reactor that uses epoll(4).
-
- @ivar _poller: A L{poll} which will be used to check for I/O
- readiness.
-
- @ivar _selectables: A dictionary mapping integer file descriptors to
- instances of L{FileDescriptor} which have been registered with the
- reactor. All L{FileDescriptors} which are currently receiving read or
- write readiness notifications will be present as values in this
- dictionary.
-
- @ivar _reads: A dictionary mapping integer file descriptors to arbitrary
- values (this is essentially a set). Keys in this dictionary will be
- registered with C{_poller} for read readiness notifications which will
- be dispatched to the corresponding L{FileDescriptor} instances in
- C{_selectables}.
-
- @ivar _writes: A dictionary mapping integer file descriptors to arbitrary
- values (this is essentially a set). Keys in this dictionary will be
- registered with C{_poller} for write readiness notifications which will
- be dispatched to the corresponding L{FileDescriptor} instances in
- C{_selectables}.
- """
- implements(IReactorFDSet)
-
- def __init__(self):
- """
- Initialize epoll object, file descriptor tracking dictionaries, and the
- base class.
- """
- # Create the poller we're going to use. The 1024 here is just a hint
- # to the kernel, it is not a hard maximum.
- self._poller = _epoll.epoll(1024)
- self._reads = {}
- self._writes = {}
- self._selectables = {}
- posixbase.PosixReactorBase.__init__(self)
-
-
- def _add(self, xer, primary, other, selectables, event, antievent):
- """
- Private method for adding a descriptor from the event loop.
-
- It takes care of adding it if new or modifying it if already added
- for another state (read -> read/write for example).
- """
- fd = xer.fileno()
- if fd not in primary:
- cmd = _epoll.CTL_ADD
- flags = event
- if fd in other:
- flags |= antievent
- cmd = _epoll.CTL_MOD
- primary[fd] = 1
- selectables[fd] = xer
- # epoll_ctl can raise all kinds of IOErrors, and every one
- # indicates a bug either in the reactor or application-code.
- # Let them all through so someone sees a traceback and fixes
- # something. We'll do the same thing for every other call to
- # this method in this file.
- self._poller._control(cmd, fd, flags)
-
-
- def addReader(self, reader):
- """
- Add a FileDescriptor for notification of data available to read.
- """
- self._add(reader, self._reads, self._writes, self._selectables, _epoll.IN, _epoll.OUT)
-
-
- def addWriter(self, writer):
- """
- Add a FileDescriptor for notification of data available to write.
- """
- self._add(writer, self._writes, self._reads, self._selectables, _epoll.OUT, _epoll.IN)
-
-
- def _remove(self, xer, primary, other, selectables, event, antievent):
- """
- Private method for removing a descriptor from the event loop.
-
- It does the inverse job of _add, and also add a check in case of the fd
- has gone away.
- """
- fd = xer.fileno()
- if fd == -1:
- for fd, fdes in selectables.items():
- if xer is fdes:
- break
- else:
- return
- if fd in primary:
- cmd = _epoll.CTL_DEL
- flags = event
- if fd in other:
- flags = antievent
- cmd = _epoll.CTL_MOD
- else:
- del selectables[fd]
- del primary[fd]
- # See comment above _control call in _add.
- self._poller._control(cmd, fd, flags)
-
-
- def removeReader(self, reader):
- """
- Remove a Selectable for notification of data available to read.
- """
- self._remove(reader, self._reads, self._writes, self._selectables, _epoll.IN, _epoll.OUT)
-
-
- def removeWriter(self, writer):
- """
- Remove a Selectable for notification of data available to write.
- """
- self._remove(writer, self._writes, self._reads, self._selectables, _epoll.OUT, _epoll.IN)
-
- def removeAll(self):
- """
- Remove all selectables, and return a list of them.
- """
- if self.waker is not None:
- fd = self.waker.fileno()
- if fd in self._reads:
- del self._reads[fd]
- del self._selectables[fd]
- result = self._selectables.values()
- fds = self._selectables.keys()
- self._reads.clear()
- self._writes.clear()
- self._selectables.clear()
- for fd in fds:
- try:
- # Actually, we'll ignore all errors from this, since it's
- # just last-chance cleanup.
- self._poller._control(_epoll.CTL_DEL, fd, 0)
- except IOError:
- pass
- if self.waker is not None:
- fd = self.waker.fileno()
- self._reads[fd] = 1
- self._selectables[fd] = self.waker
- return result
-
-
- def getReaders(self):
- return [self._selectables[fd] for fd in self._reads]
-
-
- def getWriters(self):
- return [self._selectables[fd] for fd in self._writes]
-
-
- def doPoll(self, timeout):
- """
- Poll the poller for new events.
- """
- if timeout is None:
- timeout = 1
- timeout = int(timeout * 1000) # convert seconds to milliseconds
-
- try:
- # Limit the number of events to the number of io objects we're
- # currently tracking (because that's maybe a good heuristic) and
- # the amount of time we block to the value specified by our
- # caller.
- l = self._poller.wait(len(self._selectables), timeout)
- except IOError, err:
- if err.errno == errno.EINTR:
- return
- # See epoll_wait(2) for documentation on the other conditions
- # under which this can fail. They can only be due to a serious
- # programming error on our part, so let's just announce them
- # loudly.
- raise
-
- _drdw = self._doReadOrWrite
- for fd, event in l:
- try:
- selectable = self._selectables[fd]
- except KeyError:
- pass
- else:
- log.callWithLogger(selectable, _drdw, selectable, fd, event)
-
- doIteration = doPoll
-
- def _doReadOrWrite(self, selectable, fd, event):
- """
- fd is available for read or write, make the work and raise errors
- if necessary.
- """
- why = None
- inRead = False
- if event & _POLL_DISCONNECTED and not (event & _epoll.IN):
- why = CONNECTION_LOST
- else:
- try:
- if event & _epoll.IN:
- why = selectable.doRead()
- inRead = True
- if not why and event & _epoll.OUT:
- why = selectable.doWrite()
- inRead = False
- if selectable.fileno() != fd:
- why = error.ConnectionFdescWentAway(
- 'Filedescriptor went away')
- inRead = False
- except:
- log.err()
- why = sys.exc_info()[1]
- if why:
- self._disconnectSelectable(selectable, why, inRead)
-
-def install():
- """
- Install the epoll() reactor.
- """
- p = EPollReactor()
- from twisted.internet.main import installReactor
- installReactor(p)
-
-
-__all__ = ["EPollReactor", "install"]
-
diff --git a/tools/buildbot/pylibs/twisted/internet/error.py b/tools/buildbot/pylibs/twisted/internet/error.py
deleted file mode 100644
index 7c043f6..0000000
--- a/tools/buildbot/pylibs/twisted/internet/error.py
+++ /dev/null
@@ -1,305 +0,0 @@
-# Copyright (c) 2001-2008 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-Exceptions and errors for use in twisted.internet modules.
-
-Maintainer: U{Itamar Shtull-Trauring<mailto:twisted@itamarst.org>}
-"""
-
-import socket
-
-
-class BindError(Exception):
- """An error occurred binding to an interface"""
-
- def __str__(self):
- s = self.__doc__
- if self.args:
- s = '%s: %s' % (s, ' '.join(self.args))
- s = '%s.' % s
- return s
-
-class CannotListenError(BindError):
- """This gets raised by a call to startListening, when the object cannot start listening.
-
- @ivar interface: the interface I tried to listen on
- @ivar port: the port I tried to listen on
- @ivar socketError: the exception I got when I tried to listen
- @type socketError: L{socket.error}
- """
- def __init__(self, interface, port, socketError):
- BindError.__init__(self, interface, port, socketError)
- self.interface = interface
- self.port = port
- self.socketError = socketError
-
- def __str__(self):
- iface = self.interface or 'any'
- return "Couldn't listen on %s:%s: %s." % (iface, self.port,
- self.socketError)
-
-
-class MulticastJoinError(Exception):
- """
- An attempt to join a multicast group failed.
- """
-
-
-class MessageLengthError(Exception):
- """Message is too long to send"""
-
- def __str__(self):
- s = self.__doc__
- if self.args:
- s = '%s: %s' % (s, ' '.join(self.args))
- s = '%s.' % s
- return s
-
-
-class DNSLookupError(IOError):
- """DNS lookup failed"""
-
- def __str__(self):
- s = self.__doc__
- if self.args:
- s = '%s: %s' % (s, ' '.join(self.args))
- s = '%s.' % s
- return s
-
-
-class ConnectInProgressError(Exception):
- """A connect operation was started and isn't done yet."""
-
-
-# connection errors
-
-class ConnectError(Exception):
- """An error occurred while connecting"""
-
- def __init__(self, osError=None, string=""):
- self.osError = osError
- Exception.__init__(self, string)
-
- def __str__(self):
- s = self.__doc__ or self.__class__.__name__
- if self.osError:
- s = '%s: %s' % (s, self.osError)
- if self[0]:
- s = '%s: %s' % (s, self[0])
- s = '%s.' % s
- return s
-
-
-class ConnectBindError(ConnectError):
- """Couldn't bind"""
-
-
-class UnknownHostError(ConnectError):
- """Hostname couldn't be looked up"""
-
-
-class NoRouteError(ConnectError):
- """No route to host"""
-
-
-class ConnectionRefusedError(ConnectError):
- """Connection was refused by other side"""
-
-
-class TCPTimedOutError(ConnectError):
- """TCP connection timed out"""
-
-
-class BadFileError(ConnectError):
- """File used for UNIX socket is no good"""
-
-
-class ServiceNameUnknownError(ConnectError):
- """Service name given as port is unknown"""
-
-
-class UserError(ConnectError):
- """User aborted connection"""
-
-
-class TimeoutError(UserError):
- """User timeout caused connection failure"""
-
-class SSLError(ConnectError):
- """An SSL error occurred"""
-
-class VerifyError(Exception):
- """Could not verify something that was supposed to be signed.
- """
-
-class PeerVerifyError(VerifyError):
- """The peer rejected our verify error.
- """
-
-class CertificateError(Exception):
- """
- We did not find a certificate where we expected to find one.
- """
-
-try:
- import errno
- errnoMapping = {
- errno.ENETUNREACH: NoRouteError,
- errno.ECONNREFUSED: ConnectionRefusedError,
- errno.ETIMEDOUT: TCPTimedOutError,
- }
- if hasattr(errno, "WSAECONNREFUSED"):
- errnoMapping[errno.WSAECONNREFUSED] = ConnectionRefusedError
- errnoMapping[errno.WSAENETUNREACH] = NoRouteError
-except ImportError:
- errnoMapping = {}
-
-def getConnectError(e):
- """Given a socket exception, return connection error."""
- try:
- number, string = e
- except ValueError:
- return ConnectError(string=e)
-
- if hasattr(socket, 'gaierror') and isinstance(e, socket.gaierror):
- # only works in 2.2
- klass = UnknownHostError
- else:
- klass = errnoMapping.get(number, ConnectError)
- return klass(number, string)
-
-
-
-class ConnectionClosed(Exception):
- """
- Connection was closed, whether cleanly or non-cleanly.
- """
-
-
-
-class ConnectionLost(ConnectionClosed):
- """Connection to the other side was lost in a non-clean fashion"""
-
- def __str__(self):
- s = self.__doc__
- if self.args:
- s = '%s: %s' % (s, ' '.join(self.args))
- s = '%s.' % s
- return s
-
-
-
-class ConnectionDone(ConnectionClosed):
- """Connection was closed cleanly"""
-
- def __str__(self):
- s = self.__doc__
- if self.args:
- s = '%s: %s' % (s, ' '.join(self.args))
- s = '%s.' % s
- return s
-
-
-class ConnectionFdescWentAway(ConnectionLost):
- """Uh""" #TODO
-
-
-class AlreadyCalled(ValueError):
- """Tried to cancel an already-called event"""
-
- def __str__(self):
- s = self.__doc__
- if self.args:
- s = '%s: %s' % (s, ' '.join(self.args))
- s = '%s.' % s
- return s
-
-
-class AlreadyCancelled(ValueError):
- """Tried to cancel an already-cancelled event"""
-
- def __str__(self):
- s = self.__doc__
- if self.args:
- s = '%s: %s' % (s, ' '.join(self.args))
- s = '%s.' % s
- return s
-
-
-
-class PotentialZombieWarning(Warning):
- """
- Emitted when L{IReactorProcess.spawnProcess} is called in a way which may
- result in termination of the created child process not being reported.
- """
- MESSAGE = (
- "spawnProcess called, but the SIGCHLD handler is not "
- "installed. This probably means you have not yet "
- "called reactor.run, or called "
- "reactor.run(installSignalHandler=0). You will probably "
- "never see this process finish, and it may become a "
- "zombie process.")
-
-
-
-class ProcessDone(ConnectionDone):
- """A process has ended without apparent errors"""
-
- def __init__(self, status):
- Exception.__init__(self, "process finished with exit code 0")
- self.exitCode = 0
- self.signal = None
- self.status = status
-
-
-class ProcessTerminated(ConnectionLost):
- """A process has ended with a probable error condition"""
-
- def __init__(self, exitCode=None, signal=None, status=None):
- self.exitCode = exitCode
- self.signal = signal
- self.status = status
- s = "process ended"
- if exitCode is not None: s = s + " with exit code %s" % exitCode
- if signal is not None: s = s + " by signal %s" % signal
- Exception.__init__(self, s)
-
-
-class ProcessExitedAlready(Exception):
- """The process has already excited, and the operation requested can no longer be performed."""
-
-
-class NotConnectingError(RuntimeError):
- """The Connector was not connecting when it was asked to stop connecting"""
-
- def __str__(self):
- s = self.__doc__
- if self.args:
- s = '%s: %s' % (s, ' '.join(self.args))
- s = '%s.' % s
- return s
-
-class NotListeningError(RuntimeError):
- """The Port was not listening when it was asked to stop listening"""
-
- def __str__(self):
- s = self.__doc__
- if self.args:
- s = '%s: %s' % (s, ' '.join(self.args))
- s = '%s.' % s
- return s
-
-
-class ReactorNotRunning(RuntimeError):
- """
- Error raised when trying to stop a reactor which is not running.
- """
-
-
-class ReactorAlreadyRunning(RuntimeError):
- """
- Error raised when trying to start the reactor multiple times.
- """
-
diff --git a/tools/buildbot/pylibs/twisted/internet/fdesc.py b/tools/buildbot/pylibs/twisted/internet/fdesc.py
deleted file mode 100644
index 4d990bb..0000000
--- a/tools/buildbot/pylibs/twisted/internet/fdesc.py
+++ /dev/null
@@ -1,93 +0,0 @@
-# -*- test-case-name: twisted.test.test_fdesc -*-
-
-# Copyright (c) 2001-2007 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-Utility functions for dealing with POSIX file descriptors.
-"""
-
-import sys
-import os
-import errno
-import fcntl
-if (sys.hexversion >> 16) >= 0x202:
- FCNTL = fcntl
-else:
- import FCNTL
-
-# twisted imports
-from twisted.internet.main import CONNECTION_LOST, CONNECTION_DONE
-
-
-def setNonBlocking(fd):
- """
- Make a file descriptor non-blocking.
- """
- flags = fcntl.fcntl(fd, FCNTL.F_GETFL)
- flags = flags | os.O_NONBLOCK
- fcntl.fcntl(fd, FCNTL.F_SETFL, flags)
-
-
-def setBlocking(fd):
- """
- Make a file descriptor blocking.
- """
- flags = fcntl.fcntl(fd, FCNTL.F_GETFL)
- flags = flags & ~os.O_NONBLOCK
- fcntl.fcntl(fd, FCNTL.F_SETFL, flags)
-
-
-def readFromFD(fd, callback):
- """
- Read from file descriptor, calling callback with resulting data.
-
- Returns same thing FileDescriptor.doRead would.
-
- @type fd: C{int}
- @param fd: non-blocking file descriptor to be read from.
- @param callback: a callable which accepts a single argument. If
- data is read from the file descriptor it will be called with this
- data. Handling exceptions from calling the callback is up to the
- caller.
-
- Note that if the descriptor is still connected but no data is read,
- None will be returned but callback will not be called.
-
- @return: CONNECTION_LOST on error, CONNECTION_DONE when fd is
- closed, otherwise None.
- """
- try:
- output = os.read(fd, 8192)
- except (OSError, IOError), ioe:
- if ioe.args[0] in (errno.EAGAIN, errno.EINTR):
- return
- else:
- return CONNECTION_LOST
- if not output:
- return CONNECTION_DONE
- callback(output)
-
-def writeToFD(fd, data):
- """
- Write data to file descriptor.
-
- Returns same thing FileDescriptor.writeSomeData would.
-
- @type fd: C{int}
- @param fd: non-blocking file descriptor to be written to.
- @type data: C{str} or C{buffer}
- @param data: bytes to write to fd.
-
- @return: number of bytes written, or CONNECTION_LOST.
- """
- try:
- return os.write(fd, data)
- except (OSError, IOError), io:
- if io.errno in (errno.EAGAIN, errno.EINTR):
- return 0
- return CONNECTION_LOST
-
-
-__all__ = ["setNonBlocking", "setBlocking", "readFromFD", "writeToFD"]
diff --git a/tools/buildbot/pylibs/twisted/internet/glib2reactor.py b/tools/buildbot/pylibs/twisted/internet/glib2reactor.py
deleted file mode 100644
index a759107..0000000
--- a/tools/buildbot/pylibs/twisted/internet/glib2reactor.py
+++ /dev/null
@@ -1,49 +0,0 @@
-
-"""
-This module provides support for Twisted to interact with the glib mainloop.
-This is like gtk2, but slightly faster and does not require a working
-$DISPLAY. However, you cannot run GUIs under this reactor: for that you must
-use the gtk2reactor instead.
-
-In order to use this support, simply do the following::
-
- | from twisted.internet import glib2reactor
- | glib2reactor.install()
-
-Then use twisted.internet APIs as usual. The other methods here are not
-intended to be called directly.
-
-When installing the reactor, you can choose whether to use the glib
-event loop or the GTK+ event loop which is based on it but adds GUI
-integration.
-
-Maintainer: U{Itamar Shtull-Trauring<mailto:twisted@itamarst.org>}
-"""
-
-from twisted.internet import gtk2reactor
-
-
-
-class Glib2Reactor(gtk2reactor.Gtk2Reactor):
- """
- The reactor using the glib mainloop.
- """
-
- def __init__(self):
- """
- Override init to set the C{useGtk} flag.
- """
- gtk2reactor.Gtk2Reactor.__init__(self, useGtk=False)
-
-
-
-def install():
- """
- Configure the twisted mainloop to be run inside the glib mainloop.
- """
- reactor = Glib2Reactor()
- from twisted.internet.main import installReactor
- installReactor(reactor)
-
-__all__ = ['install']
-
diff --git a/tools/buildbot/pylibs/twisted/internet/gtk2reactor.py b/tools/buildbot/pylibs/twisted/internet/gtk2reactor.py
deleted file mode 100644
index d2aaf03..0000000
--- a/tools/buildbot/pylibs/twisted/internet/gtk2reactor.py
+++ /dev/null
@@ -1,295 +0,0 @@
-# -*- test-case-name: twisted.internet.test.test_gtk2reactor -*-
-# Copyright (c) 2001-2008 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-This module provides support for Twisted to interact with the glib/gtk2
-mainloop.
-
-In order to use this support, simply do the following::
-
- | from twisted.internet import gtk2reactor
- | gtk2reactor.install()
-
-Then use twisted.internet APIs as usual. The other methods here are not
-intended to be called directly.
-
-When installing the reactor, you can choose whether to use the glib
-event loop or the GTK+ event loop which is based on it but adds GUI
-integration.
-
-Maintainer: U{Itamar Shtull-Trauring<mailto:twisted@itamarst.org>}
-"""
-
-# System Imports
-import sys
-from zope.interface import implements
-try:
- if not hasattr(sys, 'frozen'):
- # Don't want to check this for py2exe
- import pygtk
- pygtk.require('2.0')
-except (ImportError, AttributeError):
- pass # maybe we're using pygtk before this hack existed.
-import gobject
-if hasattr(gobject, "threads_init"):
- # recent versions of python-gtk expose this. python-gtk=2.4.1
- # (wrapping glib-2.4.7) does. python-gtk=2.0.0 (wrapping
- # glib-2.2.3) does not.
- gobject.threads_init()
-
-# Twisted Imports
-from twisted.python import log, runtime, failure
-from twisted.internet.interfaces import IReactorFDSet
-from twisted.internet import main, posixbase, error, selectreactor
-
-POLL_DISCONNECTED = gobject.IO_HUP | gobject.IO_ERR | gobject.IO_NVAL
-
-# glib's iochannel sources won't tell us about any events that we haven't
-# asked for, even if those events aren't sensible inputs to the poll()
-# call.
-INFLAGS = gobject.IO_IN | POLL_DISCONNECTED
-OUTFLAGS = gobject.IO_OUT | POLL_DISCONNECTED
-
-def _our_mainquit():
- # XXX: gtk.main_quit() (which is used for crash()) raises an exception if
- # gtk.main_level() == 0; however, all the tests freeze if we use this
- # function to stop the reactor. what gives? (I believe this may have been
- # a stupid mistake where I forgot to import gtk here... I will remove this
- # comment if the tests pass)
- import gtk
- if gtk.main_level():
- gtk.main_quit()
-
-class Gtk2Reactor(posixbase.PosixReactorBase):
- """
- GTK+-2 event loop reactor.
-
- @ivar _reads: A dictionary mapping L{FileDescriptor} instances to gtk
- INPUT_READ watch handles.
-
- @ivar _writes: A dictionary mapping L{FileDescriptor} instances to gtk
- INTPUT_WRITE watch handles.
-
- @ivar _simtag: A gtk timeout handle for the next L{simulate} call.
- """
- implements(IReactorFDSet)
-
- def __init__(self, useGtk=True):
- self.context = gobject.main_context_default()
- self.loop = gobject.MainLoop()
- self._simtag = None
- self._reads = {}
- self._writes = {}
- posixbase.PosixReactorBase.__init__(self)
- # pre 2.3.91 the glib iteration and mainloop functions didn't release
- # global interpreter lock, thus breaking thread and signal support.
- if (hasattr(gobject, "pygtk_version") and gobject.pygtk_version >= (2, 3, 91)
- and not useGtk):
- self.__pending = self.context.pending
- self.__iteration = self.context.iteration
- self.__crash = self.loop.quit
- self.__run = self.loop.run
- else:
- import gtk
- self.__pending = gtk.events_pending
- self.__iteration = gtk.main_iteration
- self.__crash = _our_mainquit
- self.__run = gtk.main
-
- # The input_add function in pygtk1 checks for objects with a
- # 'fileno' method and, if present, uses the result of that method
- # as the input source. The pygtk2 input_add does not do this. The
- # function below replicates the pygtk1 functionality.
-
- # In addition, pygtk maps gtk.input_add to _gobject.io_add_watch, and
- # g_io_add_watch() takes different condition bitfields than
- # gtk_input_add(). We use g_io_add_watch() here in case pygtk fixes this
- # bug.
- def input_add(self, source, condition, callback):
- if hasattr(source, 'fileno'):
- # handle python objects
- def wrapper(source, condition, real_s=source, real_cb=callback):
- return real_cb(real_s, condition)
- return gobject.io_add_watch(source.fileno(), condition, wrapper)
- else:
- return gobject.io_add_watch(source, condition, callback)
-
- def addReader(self, reader):
- if reader not in self._reads:
- self._reads[reader] = self.input_add(reader, INFLAGS, self.callback)
-
- def addWriter(self, writer):
- if writer not in self._writes:
- self._writes[writer] = self.input_add(writer, OUTFLAGS, self.callback)
-
-
- def getReaders(self):
- return self._reads.keys()
-
-
- def getWriters(self):
- return self._writes.keys()
-
-
- def removeAll(self):
- return self._removeAll(self._reads, self._writes)
-
- def removeReader(self, reader):
- if reader in self._reads:
- gobject.source_remove(self._reads[reader])
- del self._reads[reader]
-
- def removeWriter(self, writer):
- if writer in self._writes:
- gobject.source_remove(self._writes[writer])
- del self._writes[writer]
-
- doIterationTimer = None
-
- def doIterationTimeout(self, *args):
- self.doIterationTimer = None
- return 0 # auto-remove
-
- def doIteration(self, delay):
- # flush some pending events, return if there was something to do
- # don't use the usual "while self.context.pending(): self.context.iteration()"
- # idiom because lots of IO (in particular test_tcp's
- # ProperlyCloseFilesTestCase) can keep us from ever exiting.
- log.msg(channel='system', event='iteration', reactor=self)
- if self.__pending():
- self.__iteration(0)
- return
- # nothing to do, must delay
- if delay == 0:
- return # shouldn't delay, so just return
- self.doIterationTimer = gobject.timeout_add(int(delay * 1000),
- self.doIterationTimeout)
- # This will either wake up from IO or from a timeout.
- self.__iteration(1) # block
- # note: with the .simulate timer below, delays > 0.1 will always be
- # woken up by the .simulate timer
- if self.doIterationTimer:
- # if woken by IO, need to cancel the timer
- gobject.source_remove(self.doIterationTimer)
- self.doIterationTimer = None
-
- def crash(self):
- posixbase.PosixReactorBase.crash(self)
- self.__crash()
-
- def run(self, installSignalHandlers=1):
- self.startRunning(installSignalHandlers=installSignalHandlers)
- gobject.timeout_add(0, self.simulate)
- if not self._stopped:
- self.__run()
-
- def _doReadOrWrite(self, source, condition, faildict={
- error.ConnectionDone: failure.Failure(error.ConnectionDone()),
- error.ConnectionLost: failure.Failure(error.ConnectionLost()),
- }):
- why = None
- didRead = None
- if condition & POLL_DISCONNECTED and \
- not (condition & gobject.IO_IN):
- why = main.CONNECTION_LOST
- else:
- try:
- if condition & gobject.IO_IN:
- why = source.doRead()
- didRead = source.doRead
- if not why and condition & gobject.IO_OUT:
- # if doRead caused connectionLost, don't call doWrite
- # if doRead is doWrite, don't call it again.
- if not source.disconnected and source.doWrite != didRead:
- why = source.doWrite()
- didRead = source.doWrite # if failed it was in write
- except:
- why = sys.exc_info()[1]
- log.msg('Error In %s' % source)
- log.deferr()
-
- if why:
- self._disconnectSelectable(source, why, didRead == source.doRead)
-
- def callback(self, source, condition):
- log.callWithLogger(source, self._doReadOrWrite, source, condition)
- self.simulate() # fire Twisted timers
- return 1 # 1=don't auto-remove the source
-
- def simulate(self):
- """Run simulation loops and reschedule callbacks.
- """
- if self._simtag is not None:
- gobject.source_remove(self._simtag)
- self.runUntilCurrent()
- timeout = min(self.timeout(), 0.1)
- if timeout is None:
- timeout = 0.1
- # grumble
- self._simtag = gobject.timeout_add(int(timeout * 1010), self.simulate)
-
-
-class PortableGtkReactor(selectreactor.SelectReactor):
- """Reactor that works on Windows.
-
- input_add is not supported on GTK+ for Win32, apparently.
- """
-
- def crash(self):
- selectreactor.SelectReactor.crash(self)
- import gtk
- # mainquit is deprecated in newer versions
- if hasattr(gtk, 'main_quit'):
- gtk.main_quit()
- else:
- gtk.mainquit()
-
- def run(self, installSignalHandlers=1):
- import gtk
- self.startRunning(installSignalHandlers=installSignalHandlers)
- self.simulate()
- # mainloop is deprecated in newer versions
- if hasattr(gtk, 'main'):
- gtk.main()
- else:
- gtk.mainloop()
-
- def simulate(self):
- """Run simulation loops and reschedule callbacks.
- """
- if self._simtag is not None:
- gobject.source_remove(self._simtag)
- self.iterate()
- timeout = min(self.timeout(), 0.1)
- if timeout is None:
- timeout = 0.1
- # grumble
- self._simtag = gobject.timeout_add(int(timeout * 1010), self.simulate)
-
-
-def install(useGtk=True):
- """Configure the twisted mainloop to be run inside the gtk mainloop.
-
- @param useGtk: should glib rather than GTK+ event loop be
- used (this will be slightly faster but does not support GUI).
- """
- reactor = Gtk2Reactor(useGtk)
- from twisted.internet.main import installReactor
- installReactor(reactor)
- return reactor
-
-def portableInstall(useGtk=True):
- """Configure the twisted mainloop to be run inside the gtk mainloop.
- """
- reactor = PortableGtkReactor()
- from twisted.internet.main import installReactor
- installReactor(reactor)
- return reactor
-
-if runtime.platform.getType() != 'posix':
- install = portableInstall
-
-
-__all__ = ['install']
diff --git a/tools/buildbot/pylibs/twisted/internet/gtkreactor.py b/tools/buildbot/pylibs/twisted/internet/gtkreactor.py
deleted file mode 100644
index 6c19fe4..0000000
--- a/tools/buildbot/pylibs/twisted/internet/gtkreactor.py
+++ /dev/null
@@ -1,233 +0,0 @@
-# Copyright (c) 2001-2007 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-This module provides support for Twisted to interact with the PyGTK mainloop.
-
-In order to use this support, simply do the following::
-
- | from twisted.internet import gtkreactor
- | gtkreactor.install()
-
-Then use twisted.internet APIs as usual. The other methods here are not
-intended to be called directly.
-
-Maintainer: U{Itamar Shtull-Trauring<mailto:twisted@itamarst.org>}
-"""
-
-import sys
-
-# System Imports
-try:
- import pygtk
- pygtk.require('1.2')
-except ImportError, AttributeError:
- pass # maybe we're using pygtk before this hack existed.
-import gtk
-
-from zope.interface import implements
-
-# Twisted Imports
-from twisted.python import log, runtime
-from twisted.internet.interfaces import IReactorFDSet
-
-# Sibling Imports
-from twisted.internet import posixbase, selectreactor
-
-
-class GtkReactor(posixbase.PosixReactorBase):
- """
- GTK+ event loop reactor.
-
- @ivar _reads: A dictionary mapping L{FileDescriptor} instances to gtk INPUT_READ
- watch handles.
-
- @ivar _writes: A dictionary mapping L{FileDescriptor} instances to gtk
- INTPUT_WRITE watch handles.
-
- @ivar _simtag: A gtk timeout handle for the next L{simulate} call.
- """
- implements(IReactorFDSet)
-
- def __init__(self):
- """
- Initialize the file descriptor tracking dictionaries and the base
- class.
- """
- self._simtag = None
- self._reads = {}
- self._writes = {}
- posixbase.PosixReactorBase.__init__(self)
-
-
- def addReader(self, reader):
- if reader not in self._reads:
- self._reads[reader] = gtk.input_add(reader, gtk.GDK.INPUT_READ, self.callback)
-
- def addWriter(self, writer):
- if writer not in self._writes:
- self._writes[writer] = gtk.input_add(writer, gtk.GDK.INPUT_WRITE, self.callback)
-
-
- def getReaders(self):
- return self._reads.keys()
-
-
- def getWriters(self):
- return self._writes.keys()
-
-
- def removeAll(self):
- return self._removeAll(self._reads, self._writes)
-
- def removeReader(self, reader):
- if reader in self._reads:
- gtk.input_remove(self._reads[reader])
- del self._reads[reader]
-
- def removeWriter(self, writer):
- if writer in self._writes:
- gtk.input_remove(self._writes[writer])
- del self._writes[writer]
-
- doIterationTimer = None
-
- def doIterationTimeout(self, *args):
- self.doIterationTimer = None
- return 0 # auto-remove
- def doIteration(self, delay):
- # flush some pending events, return if there was something to do
- # don't use the usual "while gtk.events_pending(): mainiteration()"
- # idiom because lots of IO (in particular test_tcp's
- # ProperlyCloseFilesTestCase) can keep us from ever exiting.
- log.msg(channel='system', event='iteration', reactor=self)
- if gtk.events_pending():
- gtk.mainiteration(0)
- return
- # nothing to do, must delay
- if delay == 0:
- return # shouldn't delay, so just return
- self.doIterationTimer = gtk.timeout_add(int(delay * 1000),
- self.doIterationTimeout)
- # This will either wake up from IO or from a timeout.
- gtk.mainiteration(1) # block
- # note: with the .simulate timer below, delays > 0.1 will always be
- # woken up by the .simulate timer
- if self.doIterationTimer:
- # if woken by IO, need to cancel the timer
- gtk.timeout_remove(self.doIterationTimer)
- self.doIterationTimer = None
-
- def crash(self):
- posixbase.PosixReactorBase.crash(self)
- gtk.mainquit()
-
- def run(self, installSignalHandlers=1):
- self.startRunning(installSignalHandlers=installSignalHandlers)
- gtk.timeout_add(0, self.simulate)
- gtk.mainloop()
-
- def _readAndWrite(self, source, condition):
- # note: gtk-1.2's gtk_input_add presents an API in terms of gdk
- # constants like INPUT_READ and INPUT_WRITE. Internally, it will add
- # POLL_HUP and POLL_ERR to the poll() events, but if they happen it
- # will turn them back into INPUT_READ and INPUT_WRITE. gdkevents.c
- # maps IN/HUP/ERR to INPUT_READ, and OUT/ERR to INPUT_WRITE. This
- # means there is no immediate way to detect a disconnected socket.
-
- # The g_io_add_watch() API is more suited to this task. I don't think
- # pygtk exposes it, though.
- why = None
- didRead = None
- try:
- if condition & gtk.GDK.INPUT_READ:
- why = source.doRead()
- didRead = source.doRead
- if not why and condition & gtk.GDK.INPUT_WRITE:
- # if doRead caused connectionLost, don't call doWrite
- # if doRead is doWrite, don't call it again.
- if not source.disconnected and source.doWrite != didRead:
- why = source.doWrite()
- didRead = source.doWrite # if failed it was in write
- except:
- why = sys.exc_info()[1]
- log.msg('Error In %s' % source)
- log.deferr()
-
- if why:
- self._disconnectSelectable(source, why, didRead == source.doRead)
-
- def callback(self, source, condition):
- log.callWithLogger(source, self._readAndWrite, source, condition)
- self.simulate() # fire Twisted timers
- return 1 # 1=don't auto-remove the source
-
- def simulate(self):
- """Run simulation loops and reschedule callbacks.
- """
- if self._simtag is not None:
- gtk.timeout_remove(self._simtag)
- self.runUntilCurrent()
- timeout = min(self.timeout(), 0.1)
- if timeout is None:
- timeout = 0.1
- # Quoth someone other than me, "grumble", yet I know not why. Try to be
- # more specific in your complaints, guys. -exarkun
- self._simtag = gtk.timeout_add(int(timeout * 1010), self.simulate)
-
-
-
-class PortableGtkReactor(selectreactor.SelectReactor):
- """Reactor that works on Windows.
-
- input_add is not supported on GTK+ for Win32, apparently.
-
- @ivar _simtag: A gtk timeout handle for the next L{simulate} call.
- """
- _simtag = None
-
-
- def crash(self):
- selectreactor.SelectReactor.crash(self)
- gtk.mainquit()
-
- def run(self, installSignalHandlers=1):
- self.startRunning(installSignalHandlers=installSignalHandlers)
- self.simulate()
- gtk.mainloop()
-
- def simulate(self):
- """Run simulation loops and reschedule callbacks.
- """
- if self._simtag is not None:
- gtk.timeout_remove(self._simtag)
- self.iterate()
- timeout = min(self.timeout(), 0.1)
- if timeout is None:
- timeout = 0.1
-
- # See comment for identical line in GtkReactor.simulate.
- self._simtag = gtk.timeout_add((timeout * 1010), self.simulate)
-
-
-
-def install():
- """Configure the twisted mainloop to be run inside the gtk mainloop.
- """
- reactor = GtkReactor()
- from twisted.internet.main import installReactor
- installReactor(reactor)
- return reactor
-
-def portableInstall():
- """Configure the twisted mainloop to be run inside the gtk mainloop.
- """
- reactor = PortableGtkReactor()
- from twisted.internet.main import installReactor
- installReactor(reactor)
- return reactor
-
-if runtime.platform.getType() != 'posix':
- install = portableInstall
-
-__all__ = ['install']
diff --git a/tools/buildbot/pylibs/twisted/internet/interfaces.py b/tools/buildbot/pylibs/twisted/internet/interfaces.py
deleted file mode 100644
index d7a4521..0000000
--- a/tools/buildbot/pylibs/twisted/internet/interfaces.py
+++ /dev/null
@@ -1,1417 +0,0 @@
-# Copyright (c) 2001-2008 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-Interface documentation.
-
-Maintainer: U{Itamar Shtull-Trauring<mailto:twisted@itamarst.org>}
-"""
-
-from zope.interface import Interface
-
-
-class IAddress(Interface):
- """An address, e.g. a TCP (host, port).
-
- Default implementations are in L{twisted.internet.address}.
- """
-
-
-### Reactor Interfaces
-
-class IConnector(Interface):
- """Object used to interface between connections and protocols.
-
- Each IConnector manages one connection.
- """
-
- def stopConnecting():
- """Stop attempting to connect."""
-
- def disconnect():
- """Disconnect regardless of the connection state.
-
- If we are connected, disconnect, if we are trying to connect,
- stop trying.
- """
-
- def connect():
- """Try to connect to remote address."""
-
- def getDestination():
- """Return destination this will try to connect to.
-
- @return: An object which provides L{IAddress}.
- """
-
-
-class IResolverSimple(Interface):
- def getHostByName(name, timeout = (1, 3, 11, 45)):
- """Resolve the domain name C{name} into an IP address.
-
- @type name: C{str}
- @type timeout: C{tuple}
- @rtype: L{twisted.internet.defer.Deferred}
- @return: The callback of the Deferred that is returned will be
- passed a string that represents the IP address of the specified
- name, or the errback will be called if the lookup times out. If
- multiple types of address records are associated with the name,
- A6 records will be returned in preference to AAAA records, which
- will be returned in preference to A records. If there are multiple
- records of the type to be returned, one will be selected at random.
-
- @raise twisted.internet.defer.TimeoutError: Raised (asynchronously)
- if the name cannot be resolved within the specified timeout period.
- """
-
-class IResolver(IResolverSimple):
- def lookupRecord(name, cls, type, timeout = 10):
- """Lookup the records associated with the given name
- that are of the given type and in the given class.
- """
-
- def query(query, timeout = 10):
- """Interpret and dispatch a query object to the appropriate
- lookup* method.
- """
-
- def lookupAddress(name, timeout = 10):
- """Lookup the A records associated with C{name}."""
-
- def lookupAddress6(name, timeout = 10):
- """Lookup all the A6 records associated with C{name}."""
-
- def lookupIPV6Address(name, timeout = 10):
- """Lookup all the AAAA records associated with C{name}."""
-
- def lookupMailExchange(name, timeout = 10):
- """Lookup the MX records associated with C{name}."""
-
- def lookupNameservers(name, timeout = 10):
- """Lookup the the NS records associated with C{name}."""
-
- def lookupCanonicalName(name, timeout = 10):
- """Lookup the CNAME records associated with C{name}."""
-
- def lookupMailBox(name, timeout = 10):
- """Lookup the MB records associated with C{name}."""
-
- def lookupMailGroup(name, timeout = 10):
- """Lookup the MG records associated with C{name}."""
-
- def lookupMailRename(name, timeout = 10):
- """Lookup the MR records associated with C{name}."""
-
- def lookupPointer(name, timeout = 10):
- """Lookup the PTR records associated with C{name}."""
-
- def lookupAuthority(name, timeout = 10):
- """Lookup the SOA records associated with C{name}."""
-
- def lookupNull(name, timeout = 10):
- """Lookup the NULL records associated with C{name}."""
-
- def lookupWellKnownServices(name, timeout = 10):
- """Lookup the WKS records associated with C{name}."""
-
- def lookupHostInfo(name, timeout = 10):
- """Lookup the HINFO records associated with C{name}."""
-
- def lookupMailboxInfo(name, timeout = 10):
- """Lookup the MINFO records associated with C{name}."""
-
- def lookupText(name, timeout = 10):
- """Lookup the TXT records associated with C{name}."""
-
- def lookupResponsibility(name, timeout = 10):
- """Lookup the RP records associated with C{name}."""
-
- def lookupAFSDatabase(name, timeout = 10):
- """Lookup the AFSDB records associated with C{name}."""
-
- def lookupService(name, timeout = 10):
- """Lookup the SRV records associated with C{name}."""
-
- def lookupAllRecords(name, timeout = 10):
- """Lookup all records associated with C{name}."""
-
- def lookupZone(name, timeout = 10):
- """Perform a zone transfer for the given C{name}."""
-
-
-class IReactorArbitrary(Interface):
- def listenWith(portType, *args, **kw):
- """Start an instance of the given C{portType} listening.
-
- @type portType: type which implements L{IListeningPort}
-
- @param portType: The object given by C{portType(*args, **kw)} will be
- started listening.
-
- @return: an object which provides L{IListeningPort}.
- """
-
- def connectWith(connectorType, *args, **kw):
- """
- Start an instance of the given C{connectorType} connecting.
-
- @type connectorType: type which implements L{IConnector}
-
- @param connectorType: The object given by C{connectorType(*args, **kw)}
- will be started connecting.
-
- @return: An object which provides L{IConnector}.
- """
-
-class IReactorTCP(Interface):
-
- def listenTCP(port, factory, backlog=50, interface=''):
- """Connects a given protocol factory to the given numeric TCP/IP port.
-
- @param port: a port number on which to listen
-
- @param factory: a L{twisted.internet.protocol.ServerFactory} instance
-
- @param backlog: size of the listen queue
-
- @param interface: the hostname to bind to, defaults to '' (all)
-
- @return: an object that provides L{IListeningPort}.
-
- @raise CannotListenError: as defined here
- L{twisted.internet.error.CannotListenError},
- if it cannot listen on this port (e.g., it
- cannot bind to the required port number)
- """
-
- def connectTCP(host, port, factory, timeout=30, bindAddress=None):
- """Connect a TCP client.
-
- @param host: a host name
-
- @param port: a port number
-
- @param factory: a L{twisted.internet.protocol.ClientFactory} instance
-
- @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.
-
- @return: An object which provides L{IConnector}. This connector will
- call various callbacks on the factory when a connection is
- made, failed, or lost - see
- L{ClientFactory<twisted.internet.protocol.ClientFactory>}
- docs for details.
- """
-
-class IReactorSSL(Interface):
-
- def connectSSL(host, port, factory, contextFactory, timeout=30, bindAddress=None):
- """Connect a client Protocol to a remote SSL socket.
-
- @param host: a host name
-
- @param port: a port number
-
- @param factory: a L{twisted.internet.protocol.ClientFactory} instance
-
- @param contextFactory: a L{twisted.internet.ssl.ClientContextFactory} object.
-
- @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 C{None}.
-
- @return: An object which provides L{IConnector}.
- """
-
- def listenSSL(port, factory, contextFactory, backlog=50, interface=''):
- """
- Connects a given protocol factory to the given numeric TCP/IP port.
- The connection is a SSL one, using contexts created by the context
- factory.
-
- @param port: a port number on which to listen
-
- @param factory: a L{twisted.internet.protocol.ServerFactory} instance
-
- @param contextFactory: a L{twisted.internet.ssl.ContextFactory} instance
-
- @param backlog: size of the listen queue
-
- @param interface: the hostname to bind to, defaults to '' (all)
- """
-
-
-class IReactorUNIX(Interface):
- """UNIX socket methods."""
-
- def connectUNIX(address, factory, timeout=30, checkPID=0):
- """Connect a client protocol to a UNIX socket.
-
- @param address: a path to a unix socket on the filesystem.
-
- @param factory: a L{twisted.internet.protocol.ClientFactory} instance
-
- @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.
-
- @return: An object which provides L{IConnector}.
- """
-
- def listenUNIX(address, factory, backlog=50, mode=0666, wantPID=0):
- """Listen on a UNIX socket.
-
- @param address: a path to a unix socket on the filesystem.
-
- @param factory: a L{twisted.internet.protocol.Factory} instance.
-
- @param backlog: number of connections to allow in backlog.
-
- @param mode: mode to set on the unix socket.
-
- @param wantPID: if True, create a pidfile for the socket.
-
- @return: An object which provides L{IListeningPort}.
- """
-
-
-class IReactorUNIXDatagram(Interface):
- """datagram UNIX socket methods."""
-
- def connectUNIXDatagram(address, protocol, maxPacketSize=8192, mode=0666, bindAddress=None):
- """Connect a client protocol to a datagram UNIX socket.
-
- @param address: a path to a unix socket on the filesystem.
-
- @param protocol: a L{twisted.internet.protocol.ConnectedDatagramProtocol} instance
-
- @param maxPacketSize: maximum packet size to accept
-
- @param mode: mode to set on the unix socket.
-
- @param bindAddress: address to bind to
-
- @return: An object which provides L{IConnector}.
- """
-
- def listenUNIXDatagram(address, protocol, maxPacketSize=8192, mode=0666):
- """Listen on a datagram UNIX socket.
-
- @param address: a path to a unix socket on the filesystem.
-
- @param protocol: a L{twisted.internet.protocol.DatagramProtocol} instance.
-
- @param maxPacketSize: maximum packet size to accept
-
- @param mode: mode to set on the unix socket.
-
- @return: An object which provides L{IListeningPort}.
- """
-
-
-class IReactorUDP(Interface):
- """UDP socket methods.
-
- IMPORTANT: This is an experimental new interface. It may change
- without backwards compatability. Suggestions are welcome.
- """
-
- def listenUDP(port, protocol, interface='', maxPacketSize=8192):
- """Connects a given DatagramProtocol to the given numeric UDP port.
-
- @return: object which provides L{IListeningPort}.
- """
-
- def connectUDP(remotehost, remoteport, protocol, localport=0,
- interface='', maxPacketSize=8192):
- """DEPRECATED.
-
- Connects a L{twisted.internet.protocol.ConnectedDatagramProtocol}
- instance to a UDP port.
- """
-
-
-class IReactorMulticast(Interface):
- """UDP socket methods that support multicast.
-
- IMPORTANT: This is an experimental new interface. It may change
- without backwards compatability. Suggestions are welcome.
- """
-
- def listenMulticast(port, protocol, interface='', maxPacketSize=8192,
- listenMultiple=False):
- """
- Connects a given
- L{DatagramProtocol<twisted.internet.protocol.DatagramProtocol>} to the
- given numeric UDP port.
-
- @param listenMultiple: boolean indicating whether multiple sockets can
- bind to same UDP port.
-
- @returns: An object which provides L{IListeningPort}.
- """
-
-
-class IReactorProcess(Interface):
-
- def spawnProcess(processProtocol, executable, args=(), env={}, path=None,
- uid=None, gid=None, usePTY=0, childFDs=None):
- """
- Spawn a process, with a process protocol.
-
- @type processProtocol: L{IProcessProtocol} provider
- @param processProtocol: An object which will be notified of all
- events related to the created process.
-
- @param executable: the file name to spawn - the full path should be
- used.
-
- @param args: the command line arguments to pass to the process; a
- sequence of strings. The first string should be the
- executable's name.
-
- @param env: the environment variables to pass to the processs; a
- dictionary of strings. If 'None', use os.environ.
-
- @param path: the path to run the subprocess in - defaults to the
- current directory.
-
- @param uid: user ID to run the subprocess as. (Only available on
- POSIX systems.)
-
- @param gid: group ID to run the subprocess as. (Only available on
- POSIX systems.)
-
- @param usePTY: if true, run this process in a pseudo-terminal.
- optionally a tuple of (masterfd, slavefd, ttyname),
- in which case use those file descriptors.
- (Not available on all systems.)
-
- @param childFDs: A dictionary mapping file descriptors in the new child
- process to an integer or to the string 'r' or 'w'.
-
- If the value is an integer, it specifies a file
- descriptor in the parent process which will be mapped
- to a file descriptor (specified by the key) in the
- child process. This is useful for things like inetd
- and shell-like file redirection.
-
- If it is the string 'r', a pipe will be created and
- attached to the child at that file descriptor: the
- child will be able to write to that file descriptor
- and the parent will receive read notification via the
- L{IProcessProtocol.childDataReceived} callback. This
- is useful for the child's stdout and stderr.
-
- If it is the string 'w', similar setup to the previous
- case will occur, with the pipe being readable by the
- child instead of writeable. The parent process can
- write to that file descriptor using
- L{IProcessTransport.writeToChild}. This is useful for
- the child's stdin.
-
- If childFDs is not passed, the default behaviour is to
- use a mapping that opens the usual stdin/stdout/stderr
- pipes.
-
- @see: L{twisted.internet.protocol.ProcessProtocol}
-
- @return: An object which provides L{IProcessTransport}.
-
- @raise OSError: Raised with errno EAGAIN or ENOMEM if there are
- insufficient system resources to create a new process.
- """
-
-class IReactorTime(Interface):
- """
- Time methods that a Reactor should implement.
- """
-
- def seconds():
- """
- Get the current time in seconds.
-
- @return: A number-like object of some sort.
- """
-
-
- def callLater(delay, callable, *args, **kw):
- """
- Call a function later.
-
- @type delay: C{float}
- @param delay: the number of seconds to wait.
-
- @param callable: the callable object to call later.
-
- @param args: the arguments to call it with.
-
- @param kw: the keyword arguments to call it with.
-
- @return: An object which provides L{IDelayedCall} and can be used to
- cancel the scheduled call, by calling its C{cancel()} method.
- It also may be rescheduled by calling its C{delay()} or
- C{reset()} methods.
- """
-
- def cancelCallLater(callID):
- """
- This method is deprecated.
-
- Cancel a call that would happen later.
-
- @param callID: this is an opaque identifier returned from C{callLater}
- that will be used to cancel a specific call.
-
- @raise ValueError: if the callID is not recognized.
- """
-
- def getDelayedCalls():
- """
- Retrieve all currently scheduled delayed calls.
-
- @return: A tuple of all L{IDelayedCall} providers representing all
- currently scheduled calls. This is everything that has been
- returned by C{callLater} but not yet called or canceled.
- """
-
-
-class IDelayedCall(Interface):
- """
- A scheduled call.
-
- There are probably other useful methods we can add to this interface;
- suggestions are welcome.
- """
-
- def getTime():
- """
- Get time when delayed call will happen.
-
- @return: time in seconds since epoch (a float).
- """
-
- def cancel():
- """
- Cancel the scheduled call.
-
- @raises twisted.internet.error.AlreadyCalled: if the call has already
- happened.
- @raises twisted.internet.error.AlreadyCancelled: if the call has already
- been cancelled.
- """
-
- def delay(secondsLater):
- """
- Delay the scheduled call.
-
- @param secondsLater: how many seconds from its current firing time to delay
-
- @raises twisted.internet.error.AlreadyCalled: if the call has already
- happened.
- @raises twisted.internet.error.AlreadyCancelled: if the call has already
- been cancelled.
- """
-
- def reset(secondsFromNow):
- """
- Reset the scheduled call's timer.
-
- @param secondsFromNow: how many seconds from now it should fire,
- equivalent to C{.cancel()} and then doing another
- C{reactor.callLater(secondsLater, ...)}
-
- @raises twisted.internet.error.AlreadyCalled: if the call has already
- happened.
- @raises twisted.internet.error.AlreadyCancelled: if the call has already
- been cancelled.
- """
-
- def active():
- """
- @return: True if this call is still active, False if it has been
- called or cancelled.
- """
-
-class IReactorThreads(Interface):
- """Dispatch methods to be run in threads.
-
- Internally, this should use a thread pool and dispatch methods to them.
- """
-
- def callInThread(callable, *args, **kwargs):
- """Run the callable object in a separate thread.
- """
-
- def callFromThread(callable, *args, **kw):
- """Cause a function to be executed by the reactor thread.
-
- Use this method when you want to run a function in the reactor's thread
- from another thread. Calling callFromThread should wake up the main
- thread (where reactor.run() is executing) and run the given callable in
- that thread.
-
- Obviously, the callable must be thread safe. (If you want to call a
- function in the next mainloop iteration, but you're in the same thread,
- use callLater with a delay of 0.)
- """
-
- def suggestThreadPoolSize(size):
- """
- Suggest the size of the internal threadpool used to dispatch functions
- passed to L{callInThread}.
- """
-
-
-class IReactorCore(Interface):
- """Core methods that a Reactor must implement.
- """
-
- def resolve(name, timeout=10):
- """Return a L{twisted.internet.defer.Deferred} that will resolve a hostname.
- """
-
-
- def run():
- """Fire 'startup' System Events, move the reactor to the 'running'
- state, then run the main loop until it is stopped with stop() or
- crash().
- """
-
- def stop():
- """Fire 'shutdown' System Events, which will move the reactor to the
- 'stopped' state and cause reactor.run() to exit. """
-
- def crash():
- """Stop the main loop *immediately*, without firing any system events.
-
- This is named as it is because this is an extremely "rude" thing to do;
- it is possible to lose data and put your system in an inconsistent
- state by calling this. However, it is necessary, as sometimes a system
- can become wedged in a pre-shutdown call.
- """
-
- def iterate(delay=0):
- """Run the main loop's I/O polling function for a period of time.
-
- This is most useful in applications where the UI is being drawn "as
- fast as possible", such as games. All pending L{IDelayedCall}s will
- be called.
-
- The reactor must have been started (via the run() method) prior to
- any invocations of this method. It must also be stopped manually
- after the last call to this method (via the stop() method). This
- method is not re-entrant: you must not call it recursively; in
- particular, you must not call it while the reactor is running.
- """
-
- def fireSystemEvent(eventType):
- """Fire a system-wide event.
-
- System-wide events are things like 'startup', 'shutdown', and
- 'persist'.
- """
-
- def addSystemEventTrigger(phase, eventType, callable, *args, **kw):
- """Add a function to be called when a system event occurs.
-
- Each "system event" in Twisted, such as 'startup', 'shutdown', and
- 'persist', has 3 phases: 'before', 'during', and 'after' (in that
- order, of course). These events will be fired internally by the
- Reactor.
-
- An implementor of this interface must only implement those events
- described here.
-
- Callbacks registered for the "before" phase may return either None or a
- Deferred. The "during" phase will not execute until all of the
- Deferreds from the "before" phase have fired.
-
- Once the "during" phase is running, all of the remaining triggers must
- execute; their return values must be ignored.
-
- @param phase: a time to call the event -- either the string 'before',
- 'after', or 'during', describing when to call it
- relative to the event's execution.
-
- @param eventType: this is a string describing the type of event.
-
- @param callable: the object to call before shutdown.
-
- @param args: the arguments to call it with.
-
- @param kw: the keyword arguments to call it with.
-
- @return: an ID that can be used to remove this call with
- removeSystemEventTrigger.
- """
-
- def removeSystemEventTrigger(triggerID):
- """Removes a trigger added with addSystemEventTrigger.
-
- @param triggerID: a value returned from addSystemEventTrigger.
-
- @raise KeyError: If there is no system event trigger for the given
- C{triggerID}.
-
- @raise ValueError: If there is no system event trigger for the given
- C{triggerID}.
-
- @raise TypeError: If there is no system event trigger for the given
- C{triggerID}.
- """
-
- def callWhenRunning(callable, *args, **kw):
- """Call a function when the reactor is running.
-
- If the reactor has not started, the callable will be scheduled
- to run when it does start. Otherwise, the callable will be invoked
- immediately.
-
- @param callable: the callable object to call later.
-
- @param args: the arguments to call it with.
-
- @param kw: the keyword arguments to call it with.
-
- @return: None if the callable was invoked, otherwise a system
- event id for the scheduled call.
- """
-
-
-class IReactorPluggableResolver(Interface):
- """A reactor with a pluggable name resolver interface.
- """
- def installResolver(resolver):
- """Set the internal resolver to use to for name lookups.
-
- @type resolver: An object implementing the L{IResolverSimple} interface
- @param resolver: The new resolver to use.
-
- @return: The previously installed resolver.
- """
-
-
-class IReactorFDSet(Interface):
- """
- Implement me to be able to use
- L{FileDescriptor<twisted.internet.abstract.FileDescriptor>} type resources.
-
- This assumes that your main-loop uses UNIX-style numeric file descriptors
- (or at least similarly opaque IDs returned from a .fileno() method)
- """
-
- def addReader(reader):
- """I add reader to the set of file descriptors to get read events for.
-
- @param reader: An L{IReadDescriptor} provider that will be checked for
- read events until it is removed from the reactor with
- L{removeReader}.
-
- @return: C{None}.
- """
-
- def addWriter(writer):
- """I add writer to the set of file descriptors to get write events for.
-
- @param writer: An L{IWriteDescriptor} provider that will be checked for
- read events until it is removed from the reactor with
- L{removeWriter}.
-
- @return: C{None}.
- """
-
- def removeReader(reader):
- """Removes an object previously added with L{addReader}.
-
- @return: C{None}.
- """
-
- def removeWriter(writer):
- """Removes an object previously added with L{addWriter}.
-
- @return: C{None}.
- """
-
- def removeAll():
- """Remove all readers and writers.
-
- Should not remove reactor internal reactor connections (like a waker).
-
- @return: A list of L{IReadDescriptor} and L{IWriteDescriptor} providers
- which were removed.
- """
-
-
- def getReaders():
- """
- Return the list of file descriptors currently monitored for input
- events by the reactor.
-
- @return: the list of file descriptors monitored for input events.
- @rtype: C{list} of C{IReadDescriptor}
- """
-
-
- def getWriters():
- """
- Return the list file descriptors currently monitored for output events
- by the reactor.
-
- @return: the list of file descriptors monitored for output events.
- @rtype: C{list} of C{IWriteDescriptor}
- """
-
-
-
-class IListeningPort(Interface):
- """A listening port.
- """
-
- def startListening():
- """Start listening on this port.
-
- @raise CannotListenError: If it cannot listen on this port (e.g., it is
- a TCP port and it cannot bind to the required
- port number).
- """
-
- def stopListening():
- """Stop listening on this port.
-
- If it does not complete immediately, will return Deferred that fires
- upon completion.
- """
-
- def getHost():
- """Get the host that this port is listening for.
-
- @return: An L{IAddress} provider.
- """
-
-
-class ILoggingContext(Interface):
- """
- Give context information that will be used to log events generated by
- this item.
- """
- def logPrefix():
- """
- @return: Prefix used during log formatting to indicate context.
- @rtype: C{str}
- """
-
-
-class IFileDescriptor(ILoggingContext):
- """
- A file descriptor.
- """
-
- def fileno():
- """
- @return: The platform-specified representation of a file-descriptor
- number.
- """
-
- def connectionLost(reason):
- """Called when the connection was lost.
-
- This is called when the connection on a selectable object has been
- lost. It will be called whether the connection was closed explicitly,
- an exception occurred in an event handler, or the other end of the
- connection closed it first.
-
- See also L{IHalfCloseableDescriptor} if your descriptor wants to be
- notified separately of the two halves of the connection being closed.
-
- @param reason: A failure instance indicating the reason why the
- connection was lost. L{error.ConnectionLost} and
- L{error.ConnectionDone} are of special note, but the
- failure may be of other classes as well.
- """
-
-class IReadDescriptor(IFileDescriptor):
-
- def doRead():
- """Some data is available for reading on your descriptor.
- """
-
-
-class IWriteDescriptor(IFileDescriptor):
-
- def doWrite():
- """Some data can be written to your descriptor.
- """
-
-
-class IReadWriteDescriptor(IReadDescriptor, IWriteDescriptor):
- """I am a L{FileDescriptor<twisted.internet.abstract.FileDescriptor>} that can both read and write.
- """
-
-
-class IHalfCloseableDescriptor(Interface):
- """A descriptor that can be half-closed."""
-
- def writeConnectionLost(reason):
- """Indicates write connection was lost."""
-
- def readConnectionLost(reason):
- """Indicates read connection was lost."""
-
-
-class ISystemHandle(Interface):
- """An object that wraps a networking OS-specific handle."""
-
- def getHandle():
- """Return a system- and reactor-specific handle.
-
- This might be a socket.socket() object, or some other type of
- object, depending on which reactor is being used. Use and
- manipulate at your own risk.
-
- This might be used in cases where you want to set specific
- options not exposed by the Twisted APIs.
- """
-
-
-class IConsumer(Interface):
- """A consumer consumes data from a producer."""
-
- def registerProducer(producer, streaming):
- """
- Register to receive data from a producer.
-
- This sets self to be a consumer for a producer. When this object runs
- out of data (as when a send(2) call on a socket succeeds in moving the
- last data from a userspace buffer into a kernelspace buffer), it will
- ask the producer to resumeProducing().
-
- For L{IPullProducer} providers, C{resumeProducing} will be called once
- each time data is required.
-
- For L{IPushProducer} providers, C{pauseProducing} will be called
- whenever the write buffer fills up and C{resumeProducing} will only be
- called when it empties.
-
- @type producer: L{IProducer} provider
-
- @type streaming: C{bool}
- @param streaming: C{True} if C{producer} provides L{IPushProducer},
- C{False} if C{producer} provides L{IPullProducer}.
-
- @return: C{None}
- """
-
- def unregisterProducer():
- """Stop consuming data from a producer, without disconnecting.
- """
-
- def write(data):
- """The producer will write data by calling this method."""
-
-class IFinishableConsumer(IConsumer):
- """A Consumer for producers that finish.
- """
- def finish():
- """The producer has finished producing."""
-
-class IProducer(Interface):
- """A producer produces data for a consumer.
-
- Typically producing is done by calling the write method of an class
- implementing L{IConsumer}.
- """
-
- def stopProducing():
- """Stop producing data.
-
- This tells a producer that its consumer has died, so it must stop
- producing data for good.
- """
-
-
-class IPushProducer(IProducer):
- """
- A push producer, also known as a streaming producer is expected to
- produce (write to this consumer) data on a continous basis, unless
- it has been paused. A paused push producer will resume producing
- after its resumeProducing() method is called. For a push producer
- which is not pauseable, these functions may be noops.
- """
-
- def pauseProducing():
- """Pause producing data.
-
- Tells a producer that it has produced too much data to process for
- the time being, and to stop until resumeProducing() is called.
- """
- def resumeProducing():
- """Resume producing data.
-
- This tells a producer to re-add itself to the main loop and produce
- more data for its consumer.
- """
-
-class IPullProducer(IProducer):
- """
- A pull producer, also known as a non-streaming producer, is
- expected to produce data each time resumeProducing() is called.
- """
-
- def resumeProducing():
- """Produce data for the consumer a single time.
-
- This tells a producer to produce data for the consumer once
- (not repeatedly, once only). Typically this will be done
- by calling the consumer's write() method a single time with
- produced data.
- """
-
-class IProtocol(Interface):
-
- def dataReceived(data):
- """Called whenever data is received.
-
- Use this method to translate to a higher-level message. Usually, some
- callback will be made upon the receipt of each complete protocol
- message.
-
- @param data: a string of indeterminate length. Please keep in mind
- that you will probably need to buffer some data, as partial
- (or multiple) protocol messages may be received! I recommend
- that unit tests for protocols call through to this method with
- differing chunk sizes, down to one byte at a time.
- """
-
- def connectionLost(reason):
- """Called when the connection is shut down.
-
- Clear any circular references here, and any external references
- to this Protocol. The connection has been closed. The C{reason}
- Failure wraps a L{twisted.internet.error.ConnectionDone} or
- L{twisted.internet.error.ConnectionLost} instance (or a subclass
- of one of those).
-
- @type reason: L{twisted.python.failure.Failure}
- """
-
- def makeConnection(transport):
- """Make a connection to a transport and a server.
- """
-
- def connectionMade():
- """Called when a connection is made.
-
- This may be considered the initializer of the protocol, because
- it is called when the connection is completed. For clients,
- this is called once the connection to the server has been
- established; for servers, this is called after an accept() call
- stops blocking and a socket has been received. If you need to
- send any greeting or initial message, do it here.
- """
-
-
-class IProcessProtocol(Interface):
- """
- Interface for process-related event handlers.
- """
-
- def makeConnection(process):
- """
- Called when the process has been created.
-
- @type process: L{IProcessTransport} provider
- @param process: An object representing the process which has been
- created and associated with this protocol.
- """
-
-
- def childDataReceived(childFD, data):
- """
- Called when data arrives from the child process.
-
- @type childFD: C{int}
- @param childFD: The file descriptor from which the data was
- received.
-
- @type data: C{str}
- @param data: The data read from the child's file descriptor.
- """
-
-
- def childConnectionLost(childFD):
- """
- Called when a file descriptor associated with the child process is
- closed.
-
- @type childFD: C{int}
- @param childFD: The file descriptor which was closed.
- """
-
-
- def processEnded(reason):
- """
- Called when the child process exits.
-
- @type reason: L{twisted.python.failure.Failure}
- @param reason: A failure giving the reason the child process
- terminated. The type of exception for this failure is either
- L{twisted.internet.error.ProcessDone} or
- L{twisted.internet.error.ProcessTerminated}.
- """
-
-
-
-class IHalfCloseableProtocol(Interface):
- """Implemented to indicate they want notification of half-closes.
-
- TCP supports the notion of half-closing the connection, e.g.
- closing the write side but still not stopping reading. A protocol
- that implements this interface will be notified of such events,
- instead of having connectionLost called.
- """
-
- def readConnectionLost():
- """Notification of the read connection being closed.
-
- This indicates peer did half-close of write side. It is now
- the responsiblity of the this protocol to call
- loseConnection(). In addition, the protocol MUST make sure a
- reference to it still exists (i.e. by doing a callLater with
- one of its methods, etc.) as the reactor will only have a
- reference to it if it is writing.
-
- If the protocol does not do so, it might get garbage collected
- without the connectionLost method ever being called.
- """
-
- def writeConnectionLost():
- """Notification of the write connection being closed.
-
- This will never be called for TCP connections as TCP does not
- support notification of this type of half-close.
- """
-
-
-class IProtocolFactory(Interface):
- """Interface for protocol factories.
- """
-
- def buildProtocol(addr):
- """Called when a connection has been established to addr.
-
- If None is returned, the connection is assumed to have been refused,
- and the Port will close the connection.
-
- @type addr: (host, port)
- @param addr: The address of the newly-established connection
-
- @return: None if the connection was refused, otherwise an object
- providing L{IProtocol}.
- """
-
- def doStart():
- """Called every time this is connected to a Port or Connector."""
-
- def doStop():
- """Called every time this is unconnected from a Port or Connector."""
-
-
-class ITransport(Interface):
- """I am a transport for bytes.
-
- I represent (and wrap) the physical connection and synchronicity
- of the framework which is talking to the network. I make no
- representations about whether calls to me will happen immediately
- or require returning to a control loop, or whether they will happen
- in the same or another thread. Consider methods of this class
- (aside from getPeer) to be 'thrown over the wall', to happen at some
- indeterminate time.
- """
-
- def write(data):
- """Write some data to the physical connection, in sequence, in a
- non-blocking fashion.
-
- If possible, make sure that it is all written. No data will
- ever be lost, although (obviously) the connection may be closed
- before it all gets through.
- """
-
- def writeSequence(data):
- """Write a list of strings to the physical connection.
-
- If possible, make sure that all of the data is written to
- the socket at once, without first copying it all into a
- single string.
- """
-
- def loseConnection():
- """Close my connection, after writing all pending data.
-
- Note that if there is a registered producer on a transport it
- will not be closed until the producer has been unregistered.
- """
-
- def getPeer():
- """Get the remote address of this connection.
-
- Treat this method with caution. It is the unfortunate result of the
- CGI and Jabber standards, but should not be considered reliable for
- the usual host of reasons; port forwarding, proxying, firewalls, IP
- masquerading, etc.
-
- @return: An L{IAddress} provider.
- """
-
- def getHost():
- """
- Similar to getPeer, but returns an address describing this side of the
- connection.
-
- @return: An L{IAddress} provider.
- """
-
-
-class ITCPTransport(ITransport):
- """A TCP based transport."""
-
- def loseWriteConnection():
- """Half-close the write side of a TCP connection.
-
- If the protocol instance this is attached to provides
- IHalfCloseableProtocol, it will get notified when the operation is
- done. When closing write connection, as with loseConnection this will
- only happen when buffer has emptied and there is no registered
- producer.
- """
-
- def getTcpNoDelay():
- """Return if TCP_NODELAY is enabled."""
-
- def setTcpNoDelay(enabled):
- """Enable/disable TCP_NODELAY.
-
- Enabling TCP_NODELAY turns off Nagle's algorithm. Small packets are
- sent sooner, possibly at the expense of overall throughput."""
-
- def getTcpKeepAlive():
- """Return if SO_KEEPALIVE enabled."""
-
- def setTcpKeepAlive(enabled):
- """Enable/disable SO_KEEPALIVE.
-
- Enabling SO_KEEPALIVE sends packets periodically when the connection
- is otherwise idle, usually once every two hours. They are intended
- to allow detection of lost peers in a non-infinite amount of time."""
-
- def getHost():
- """Returns L{IPv4Address}."""
-
- def getPeer():
- """Returns L{IPv4Address}."""
-
-
-class ITLSTransport(ITCPTransport):
- """A TCP transport that supports switching to TLS midstream.
-
- Once TLS mode is started the transport will implement L{ISSLTransport}.
- """
-
- def startTLS(contextFactory):
- """Initiate TLS negotiation.
-
- @param contextFactory: A context factory (see L{ssl.py<twisted.internet.ssl>})
- """
-
-class ISSLTransport(ITCPTransport):
- """A SSL/TLS based transport."""
-
- def getPeerCertificate():
- """Return an object with the peer's certificate info."""
-
-
-class IProcessTransport(ITransport):
- """A process transport.
-
- @ivar pid: The Process-ID of this process.
- """
-
- def closeStdin():
- """Close stdin after all data has been written out."""
-
- def closeStdout():
- """Close stdout."""
-
- def closeStderr():
- """Close stderr."""
-
- def closeChildFD(descriptor):
- """
- Close a file descriptor which is connected to the child process, identified
- by its FD in the child process.
- """
-
- def writeToChild(childFD, data):
- """
- Similar to L{ITransport.write} but also allows the file descriptor in
- the child process which will receive the bytes to be specified.
-
- This is not available on all platforms.
-
- @type childFD: C{int}
- @param childFD: The file descriptor to which to write.
-
- @type data: C{str}
- @param data: The bytes to write.
-
- @return: C{None}
- """
-
- def loseConnection():
- """Close stdin, stderr and stdout."""
-
- def signalProcess(signalID):
- """Send a signal to the process.
-
- @param signalID: can be
- - one of C{\"HUP\"}, C{\"KILL\"}, C{\"STOP\"}, or C{\"INT\"}.
- These will be implemented in a
- cross-platform manner, and so should be used
- if possible.
- - an integer, where it represents a POSIX
- signal ID.
-
- @raise twisted.internet.error.ProcessExitedAlready: The process has
- already exited.
- """
-
-
-class IServiceCollection(Interface):
- """An object which provides access to a collection of services."""
-
- def getServiceNamed(serviceName):
- """Retrieve the named service from this application.
-
- Raise a KeyError if there is no such service name.
- """
-
- def addService(service):
- """Add a service to this collection.
- """
-
- def removeService(service):
- """Remove a service from this collection."""
-
-
-class IUDPTransport(Interface):
- """Transport for UDP DatagramProtocols."""
-
- def write(packet, addr=None):
- """Write packet to given address.
-
- @param addr: a tuple of (ip, port). For connected transports must
- be the address the transport is connected to, or None.
- In non-connected mode this is mandatory.
-
- @raise twisted.internet.error.MessageLengthError: C{packet} was too
- long.
- """
-
- def connect(host, port):
- """Connect the transport to an address.
-
- This changes it to connected mode. Datagrams can only be sent to
- this address, and will only be received from this address. In addition
- the protocol's connectionRefused method might get called if destination
- is not receiving datagrams.
-
- @param host: an IP address, not a domain name ('127.0.0.1', not 'localhost')
- @param port: port to connect to.
- """
-
- def getHost():
- """Returns IPv4Address."""
-
- def stopListening():
- """Stop listening on this port.
-
- If it does not complete immediately, will return Deferred that fires
- upon completion.
- """
-
-
-class IUDPConnectedTransport(Interface):
- """DEPRECATED. Transport for UDP ConnectedPacketProtocols."""
-
- def write(packet):
- """Write packet to address we are connected to."""
-
- def getHost():
- """Returns UNIXAddress."""
-
-
-class IUNIXDatagramTransport(Interface):
- """Transport for UDP PacketProtocols."""
-
- def write(packet, address):
- """Write packet to given address."""
-
- def getHost():
- """Returns UNIXAddress."""
-
-
-class IUNIXDatagramConnectedTransport(Interface):
- """Transport for UDP ConnectedPacketProtocols."""
-
- def write(packet):
- """Write packet to address we are connected to."""
-
- def getHost():
- """Returns UNIXAddress."""
-
- def getPeer():
- """Returns UNIXAddress."""
-
-
-class IMulticastTransport(Interface):
- """Additional functionality for multicast UDP."""
-
- def getOutgoingInterface():
- """Return interface of outgoing multicast packets."""
-
- def setOutgoingInterface(addr):
- """Set interface for outgoing multicast packets.
-
- Returns Deferred of success.
- """
-
- def getLoopbackMode():
- """Return if loopback mode is enabled."""
-
- def setLoopbackMode(mode):
- """Set if loopback mode is enabled."""
-
- def getTTL():
- """Get time to live for multicast packets."""
-
- def setTTL(ttl):
- """Set time to live on multicast packets."""
-
- def joinGroup(addr, interface=""):
- """Join a multicast group. Returns Deferred of success or failure.
-
- If an error occurs, the returned Deferred will fail with
- L{error.MulticastJoinError}.
- """
-
- def leaveGroup(addr, interface=""):
- """Leave multicast group, return Deferred of success."""
diff --git a/tools/buildbot/pylibs/twisted/internet/iocpreactor/__init__.py b/tools/buildbot/pylibs/twisted/internet/iocpreactor/__init__.py
deleted file mode 100644
index d0c595d..0000000
--- a/tools/buildbot/pylibs/twisted/internet/iocpreactor/__init__.py
+++ /dev/null
@@ -1,2 +0,0 @@
-from twisted.internet.iocpreactor.reactor import install
-
diff --git a/tools/buildbot/pylibs/twisted/internet/iocpreactor/abstract.py b/tools/buildbot/pylibs/twisted/internet/iocpreactor/abstract.py
deleted file mode 100644
index c1838a5..0000000
--- a/tools/buildbot/pylibs/twisted/internet/iocpreactor/abstract.py
+++ /dev/null
@@ -1,456 +0,0 @@
-# Copyright (c) 2008 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-Abstract file handle class
-"""
-
-from twisted.internet import main, error, interfaces
-from twisted.python import log, failure
-from twisted.persisted import styles
-
-from zope.interface import implements
-import errno
-
-from twisted.internet.iocpreactor.const import ERROR_HANDLE_EOF
-from twisted.internet.iocpreactor.const import ERROR_IO_PENDING
-from twisted.internet.iocpreactor import iocpsupport as _iocp
-
-
-
-class FileHandle(log.Logger, styles.Ephemeral, object):
- """
- File handle that can read and write asynchronously
- """
- implements(interfaces.IProducer, interfaces.IConsumer,
- interfaces.ITransport, interfaces.IHalfCloseableDescriptor)
- # read stuff
- maxReadBuffers = 16
- readBufferSize = 4096
- reading = False
- dynamicReadBuffers = True # set this to false if subclass doesn't do iovecs
- _readNextBuffer = 0
- _readSize = 0 # how much data we have in the read buffer
- _readScheduled = None
- _readScheduledInOS = False
-
-
- def startReading(self):
- self.reactor.addActiveHandle(self)
- if not self._readScheduled and not self.reading:
- self.reading = True
- self._readScheduled = self.reactor.callLater(0,
- self._resumeReading)
-
-
- def stopReading(self):
- if self._readScheduled:
- self._readScheduled.cancel()
- self._readScheduled = None
- self.reading = False
-
-
- def _resumeReading(self):
- self._readScheduled = None
- if self._dispatchData() and not self._readScheduledInOS:
- self.doRead()
-
-
- def _dispatchData(self):
- """
- Dispatch previously read data. Return True if self.reading and we don't
- have any more data
- """
- if not self._readSize:
- return self.reading
- size = self._readSize
- full_buffers = size // self.readBufferSize
- while self._readNextBuffer < full_buffers:
- self.dataReceived(self._readBuffers[self._readNextBuffer])
- self._readNextBuffer += 1
- if not self.reading:
- return False
- remainder = size % self.readBufferSize
- if remainder:
- self.dataReceived(buffer(self._readBuffers[full_buffers],
- 0, remainder))
- if self.dynamicReadBuffers:
- total_buffer_size = self.readBufferSize * len(self._readBuffers)
- # we have one buffer too many
- if size < total_buffer_size - self.readBufferSize:
- del self._readBuffers[-1]
- # we filled all buffers, so allocate one more
- elif (size == total_buffer_size and
- len(self._readBuffers) < self.maxReadBuffers):
- self._readBuffers.append(_iocp.AllocateReadBuffer(
- self.readBufferSize))
- self._readNextBuffer = 0
- self._readSize = 0
- return self.reading
-
-
- def _cbRead(self, rc, bytes, evt):
- self._readScheduledInOS = False
- if self._handleRead(rc, bytes, evt):
- self.doRead()
-
-
- def _handleRead(self, rc, bytes, evt):
- """
- Returns False if we should stop reading for now
- """
- if self.disconnected:
- return False
- # graceful disconnection
- if (not (rc or bytes)) or rc in (errno.WSAEDISCON, ERROR_HANDLE_EOF):
- self.reactor.removeActiveHandle(self)
- self.readConnectionLost(failure.Failure(main.CONNECTION_DONE))
- return False
- # XXX: not handling WSAEWOULDBLOCK
- # ("too many outstanding overlapped I/O requests")
- elif rc:
- self.connectionLost(failure.Failure(
- error.ConnectionLost("read error -- %s (%s)" %
- (errno.errorcode.get(rc, 'unknown'), rc))))
- return False
- else:
- assert self._readSize == 0
- assert self._readNextBuffer == 0
- self._readSize = bytes
- return self._dispatchData()
-
-
- def doRead(self):
- numReads = 0
- while 1:
- evt = _iocp.Event(self._cbRead, self)
-
- evt.buff = buff = self._readBuffers
- rc, bytes = self.readFromHandle(buff, evt)
-
- if (rc == ERROR_IO_PENDING
- or (not rc and numReads >= self.maxReads)):
- self._readScheduledInOS = True
- break
- else:
- evt.ignore = True
- if not self._handleRead(rc, bytes, evt):
- break
- numReads += 1
-
-
- def readFromHandle(self, bufflist, evt):
- raise NotImplementedError() # TODO: this should default to ReadFile
-
-
- def dataReceived(self, data):
- raise NotImplementedError
-
-
- def readConnectionLost(self, reason):
- self.connectionLost(reason)
-
-
- # write stuff
- dataBuffer = ''
- offset = 0
- writing = False
- _writeScheduled = None
- _writeDisconnecting = False
- _writeDisconnected = False
- writeBufferSize = 2**2**2**2
- maxWrites = 5
-
-
- def loseWriteConnection(self):
- self._writeDisconnecting = True
- self.startWriting()
-
-
- def _closeWriteConnection(self):
- # override in subclasses
- pass
-
-
- def writeConnectionLost(self, reason):
- # in current code should never be called
- self.connectionLost(reason)
-
-
- def startWriting(self):
- self.reactor.addActiveHandle(self)
- self.writing = True
- if not self._writeScheduled:
- self._writeScheduled = self.reactor.callLater(0,
- self._resumeWriting)
-
-
- def stopWriting(self):
- if self._writeScheduled:
- self._writeScheduled.cancel()
- self._writeScheduled = None
- self.writing = False
-
-
- def _resumeWriting(self):
- self._writeScheduled = None
- self.doWrite()
-
-
- def _cbWrite(self, rc, bytes, evt):
- if self._handleWrite(rc, bytes, evt):
- self.doWrite()
-
-
- def _handleWrite(self, rc, bytes, evt):
- """
- Returns false if we should stop writing for now
- """
- if self.disconnected or self._writeDisconnected:
- return False
- # XXX: not handling WSAEWOULDBLOCK
- # ("too many outstanding overlapped I/O requests")
- if rc:
- self.connectionLost(failure.Failure(
- error.ConnectionLost("write error -- %s (%s)" %
- (errno.errorcode.get(rc, 'unknown'), rc))))
- return False
- else:
- self.offset += bytes
- # If there is nothing left to send,
- if self.offset == len(self.dataBuffer) and not self._tempDataLen:
- self.dataBuffer = ""
- self.offset = 0
- # stop writing
- self.stopWriting()
- # If I've got a producer who is supposed to supply me with data
- if self.producer is not None and ((not self.streamingProducer)
- or self.producerPaused):
- # tell them to supply some more.
- self.producerPaused = True
- self.producer.resumeProducing()
- elif self.disconnecting:
- # But if I was previously asked to let the connection die,
- # do so.
- self.connectionLost(failure.Failure(main.CONNECTION_DONE))
- elif self._writeDisconnecting:
- # I was previously asked to to half-close the connection.
- self._closeWriteConnection()
- self._writeDisconnected = True
- return False
- else:
- return True
-
-
- def doWrite(self):
- numWrites = 0
- while 1:
- if len(self.dataBuffer) - self.offset < self.SEND_LIMIT:
- # If there is currently less than SEND_LIMIT bytes left to send
- # in the string, extend it with the array data.
- self.dataBuffer = (buffer(self.dataBuffer, self.offset) +
- "".join(self._tempDataBuffer))
- self.offset = 0
- self._tempDataBuffer = []
- self._tempDataLen = 0
-
- evt = _iocp.Event(self._cbWrite, self)
-
- # Send as much data as you can.
- if self.offset:
- evt.buff = buff = buffer(self.dataBuffer, self.offset)
- else:
- evt.buff = buff = self.dataBuffer
- rc, bytes = self.writeToHandle(buff, evt)
- if (rc == ERROR_IO_PENDING
- or (not rc and numWrites >= self.maxWrites)):
- break
- else:
- evt.ignore = True
- if not self._handleWrite(rc, bytes, evt):
- break
- numWrites += 1
-
-
- def writeToHandle(self, buff, evt):
- raise NotImplementedError() # TODO: this should default to WriteFile
-
-
- def write(self, data):
- """Reliably write some data.
-
- The data is buffered until his file descriptor is ready for writing.
- """
- if isinstance(data, unicode): # no, really, I mean it
- raise TypeError("Data must not be unicode")
- if not self.connected or self._writeDisconnected:
- return
- if data:
- self._tempDataBuffer.append(data)
- self._tempDataLen += len(data)
- if self.producer is not None:
- if (len(self.dataBuffer) + self._tempDataLen
- > self.writeBufferSize):
- self.producerPaused = True
- self.producer.pauseProducing()
- self.startWriting()
-
-
- def writeSequence(self, iovec):
- if not self.connected or not iovec or self._writeDisconnected:
- return
- self._tempDataBuffer.extend(iovec)
- for i in iovec:
- self._tempDataLen += len(i)
- if self.producer is not None:
- if len(self.dataBuffer) + self._tempDataLen > self.writeBufferSize:
- self.producerPaused = True
- self.producer.pauseProducing()
- self.startWriting()
-
-
- # general stuff
- connected = False
- disconnected = False
- disconnecting = False
- logstr = "Uninitialized"
-
- SEND_LIMIT = 128*1024
-
- maxReads = 5
-
-
- def __init__(self, reactor = None):
- if not reactor:
- from twisted.internet import reactor
- self.reactor = reactor
- self._tempDataBuffer = [] # will be added to dataBuffer in doWrite
- self._tempDataLen = 0
- self._readBuffers = [_iocp.AllocateReadBuffer(self.readBufferSize)]
-
-
- def connectionLost(self, reason):
- """
- The connection was lost.
-
- This is called when the connection on a selectable object has been
- lost. It will be called whether the connection was closed explicitly,
- an exception occurred in an event handler, or the other end of the
- connection closed it first.
-
- Clean up state here, but make sure to call back up to FileDescriptor.
- """
-
- self.disconnected = True
- self.connected = False
- if self.producer is not None:
- self.producer.stopProducing()
- self.producer = None
- self.stopReading()
- self.stopWriting()
- self.reactor.removeActiveHandle(self)
-
-
- def getFileHandle(self):
- return -1
-
-
- def loseConnection(self, _connDone=failure.Failure(main.CONNECTION_DONE)):
- """
- Close the connection at the next available opportunity.
-
- Call this to cause this FileDescriptor to lose its connection. It will
- first write any data that it has buffered.
-
- If there is data buffered yet to be written, this method will cause the
- transport to lose its connection as soon as it's done flushing its
- write buffer. If you have a producer registered, the connection won't
- be closed until the producer is finished. Therefore, make sure you
- unregister your producer when it's finished, or the connection will
- never close.
- """
-
- if self.connected and not self.disconnecting:
- if self._writeDisconnected:
- # doWrite won't trigger the connection close anymore
- self.stopReading()
- self.stopWriting
- self.connectionLost(_connDone)
- else:
- self.stopReading()
- self.startWriting()
- self.disconnecting = 1
-
-
- # Producer/consumer implementation
-
- producerPaused = False
- streamingProducer = False
-
- # first, the consumer stuff. This requires no additional work, as
- # any object you can write to can be a consumer, really.
-
- producer = None
-
-
- def registerProducer(self, producer, streaming):
- """
- Register to receive data from a producer.
-
- This sets this selectable to be a consumer for a producer. When this
- selectable runs out of data on a write() call, it will ask the producer
- to resumeProducing(). A producer should implement the IProducer
- interface.
-
- FileDescriptor provides some infrastructure for producer methods.
- """
- if self.producer is not None:
- raise RuntimeError(
- "Cannot register producer %s, because producer "
- "%s was never unregistered." % (producer, self.producer))
- if self.disconnected:
- producer.stopProducing()
- else:
- self.producer = producer
- self.streamingProducer = streaming
- if not streaming:
- producer.resumeProducing()
-
-
- def unregisterProducer(self):
- """
- Stop consuming data from a producer, without disconnecting.
- """
- self.producer = None
-
-
- def stopConsuming(self):
- """
- Stop consuming data.
-
- This is called when a producer has lost its connection, to tell the
- consumer to go lose its connection (and break potential circular
- references).
- """
- self.unregisterProducer()
- self.loseConnection()
-
-
- # producer interface implementation
-
- def resumeProducing(self):
- assert self.connected and not self.disconnecting
- self.startReading()
-
-
- def pauseProducing(self):
- self.stopReading()
-
-
- def stopProducing(self):
- self.loseConnection()
-
-
-__all__ = ['FileHandle']
-
diff --git a/tools/buildbot/pylibs/twisted/internet/iocpreactor/build.bat b/tools/buildbot/pylibs/twisted/internet/iocpreactor/build.bat
deleted file mode 100644
index 25f361b..0000000
--- a/tools/buildbot/pylibs/twisted/internet/iocpreactor/build.bat
+++ /dev/null
@@ -1,4 +0,0 @@
-del iocpsupport\iocpsupport.c iocpsupport.pyd
-del /f /s /q build
-python setup.py build_ext -i -c mingw32
-
diff --git a/tools/buildbot/pylibs/twisted/internet/iocpreactor/const.py b/tools/buildbot/pylibs/twisted/internet/iocpreactor/const.py
deleted file mode 100644
index edc09f2..0000000
--- a/tools/buildbot/pylibs/twisted/internet/iocpreactor/const.py
+++ /dev/null
@@ -1,26 +0,0 @@
-# Copyright (c) 2008 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-Windows constants for IOCP
-"""
-
-
-# this stuff should really be gotten from Windows headers via pyrex, but it
-# probably is not going to change
-
-ERROR_PORT_UNREACHABLE = 1234
-ERROR_NETWORK_UNREACHABLE = 1231
-ERROR_CONNECTION_REFUSED = 1225
-ERROR_IO_PENDING = 997
-ERROR_OPERATION_ABORTED = 995
-WAIT_TIMEOUT = 258
-ERROR_NETNAME_DELETED = 64
-ERROR_HANDLE_EOF = 38
-
-INFINITE = -1
-
-SO_UPDATE_CONNECT_CONTEXT = 0x7010
-SO_UPDATE_ACCEPT_CONTEXT = 0x700B
-
diff --git a/tools/buildbot/pylibs/twisted/internet/iocpreactor/interfaces.py b/tools/buildbot/pylibs/twisted/internet/iocpreactor/interfaces.py
deleted file mode 100644
index 180f3cc..0000000
--- a/tools/buildbot/pylibs/twisted/internet/iocpreactor/interfaces.py
+++ /dev/null
@@ -1,33 +0,0 @@
-# Copyright (c) 2008 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-Interfaces for iocpreactor
-"""
-
-
-from zope.interface import Interface
-
-
-
-class IReadHandle(Interface):
- def readFromHandle(bufflist, evt):
- """
- Read from this handle into the buffer list
- """
-
-
-
-class IWriteHandle(Interface):
- def writeToHandle(buff, evt):
- """
- Write the buffer to this handle
- """
-
-
-
-class IReadWriteHandle(IReadHandle, IWriteHandle):
- pass
-
-
diff --git a/tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/acceptex.pxi b/tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/acceptex.pxi
deleted file mode 100644
index 8fd76ef..0000000
--- a/tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/acceptex.pxi
+++ /dev/null
@@ -1,38 +0,0 @@
-# Copyright (c) 2008 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-def accept(long listening, long accepting, object buff, object obj):
- cdef unsigned long bytes
- cdef int size, rc
- cdef void *mem_buffer
- cdef myOVERLAPPED *ov
-
- PyObject_AsWriteBuffer(buff, &mem_buffer, &size)
-
- ov = makeOV()
- if obj is not None:
- ov.obj = <PyObject *>obj
-
- rc = lpAcceptEx(listening, accepting, mem_buffer, 0, size / 2, size / 2,
- &bytes, <OVERLAPPED *>ov)
- if not rc:
- rc = WSAGetLastError()
- if rc != ERROR_IO_PENDING:
- return rc
-
- # operation is in progress
- Py_XINCREF(obj)
- return rc
-
-def get_accept_addrs(long s, object buff):
- cdef WSAPROTOCOL_INFO wsa_pi
- cdef int size, locallen, remotelen
- cdef void *mem_buffer
- cdef sockaddr *localaddr, *remoteaddr
-
- PyObject_AsReadBuffer(buff, &mem_buffer, &size)
-
- lpGetAcceptExSockaddrs(mem_buffer, 0, size / 2, size / 2, &localaddr, &locallen, &remoteaddr, &remotelen)
- return remoteaddr.sa_family, _makesockaddr(localaddr, locallen), _makesockaddr(remoteaddr, remotelen)
-
diff --git a/tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/connectex.pxi b/tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/connectex.pxi
deleted file mode 100644
index 65f07434..0000000
--- a/tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/connectex.pxi
+++ /dev/null
@@ -1,34 +0,0 @@
-# Copyright (c) 2008 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-def connect(long s, object addr, object obj):
- cdef int family, rc
- cdef myOVERLAPPED *ov
- cdef sockaddr name
-
- if not have_connectex:
- raise ValueError, 'ConnectEx is not available on this system'
-
- family = getAddrFamily(s)
- if family == AF_INET:
- fillinetaddr(<sockaddr_in *>&name, addr)
- else:
- raise ValueError, 'unsupported address family'
- name.sa_family = family
-
- ov = makeOV()
- if obj is not None:
- ov.obj = <PyObject *>obj
-
- rc = lpConnectEx(s, &name, sizeof(name), NULL, 0, NULL, <OVERLAPPED *>ov)
-
- if not rc:
- rc = WSAGetLastError()
- if rc != ERROR_IO_PENDING:
- return rc
-
- # operation is in progress
- Py_XINCREF(obj)
- return rc
-
diff --git a/tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/iocpsupport.c b/tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/iocpsupport.c
deleted file mode 100644
index f67e35c..0000000
--- a/tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/iocpsupport.c
+++ /dev/null
@@ -1,2003 +0,0 @@
-/* Generated by Pyrex 0.9.6.4 on Tue Mar 18 10:18:51 2008 */
-
-#define PY_SSIZE_T_CLEAN
-#include "Python.h"
-#include "structmember.h"
-#ifndef PY_LONG_LONG
- #define PY_LONG_LONG LONG_LONG
-#endif
-#if PY_VERSION_HEX < 0x02050000
- typedef int Py_ssize_t;
- #define PY_SSIZE_T_MAX INT_MAX
- #define PY_SSIZE_T_MIN INT_MIN
- #define PyInt_FromSsize_t(z) PyInt_FromLong(z)
- #define PyInt_AsSsize_t(o) PyInt_AsLong(o)
-#endif
-#ifndef WIN32
- #ifndef __stdcall
- #define __stdcall
- #endif
- #ifndef __cdecl
- #define __cdecl
- #endif
-#endif
-#ifdef __cplusplus
-#define __PYX_EXTERN_C extern "C"
-#else
-#define __PYX_EXTERN_C extern
-#endif
-#include <math.h>
-#include "io.h"
-#include "errno.h"
-#include "winsock2.h"
-#include "windows.h"
-#include "python.h"
-#include "string.h"
-#include "winsock_pointers.h"
-
-
-typedef struct {PyObject **p; char *s;} __Pyx_InternTabEntry; /*proto*/
-typedef struct {PyObject **p; char *s; long n;} __Pyx_StringTabEntry; /*proto*/
-
-static PyObject *__pyx_m;
-static PyObject *__pyx_b;
-static int __pyx_lineno;
-static char *__pyx_filename;
-static char **__pyx_f;
-
-static PyObject *__Pyx_CreateClass(PyObject *bases, PyObject *dict, PyObject *name, char *modname); /*proto*/
-
-static int __Pyx_GetStarArgs(PyObject **args, PyObject **kwds, char *kwd_list[], Py_ssize_t nargs, PyObject **args2, PyObject **kwds2, char rqd_kwds[]); /*proto*/
-
-static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list); /*proto*/
-
-static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/
-
-static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb); /*proto*/
-
-static PyObject *__Pyx_UnpackItem(PyObject *); /*proto*/
-static int __Pyx_EndUnpack(PyObject *); /*proto*/
-
-static int __Pyx_InternStrings(__Pyx_InternTabEntry *t); /*proto*/
-
-static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/
-
-static void __Pyx_AddTraceback(char *funcname); /*proto*/
-
-/* Declarations from iocpsupport */
-
-typedef int __pyx_t_11iocpsupport_size_t;
-
-typedef unsigned long __pyx_t_11iocpsupport_HANDLE;
-
-typedef unsigned long __pyx_t_11iocpsupport_SOCKET;
-
-typedef unsigned long __pyx_t_11iocpsupport_DWORD;
-
-typedef unsigned long __pyx_t_11iocpsupport_ULONG_PTR;
-
-typedef int __pyx_t_11iocpsupport_BOOL;
-
-struct __pyx_t_11iocpsupport_myOVERLAPPED {
- OVERLAPPED ov;
- struct PyObject *obj;
-};
-
-struct __pyx_obj_11iocpsupport_CompletionPort {
- PyObject_HEAD
- __pyx_t_11iocpsupport_HANDLE port;
-};
-
-
-static PyTypeObject *__pyx_ptype_11iocpsupport_CompletionPort = 0;
-static long __pyx_k2;
-static unsigned long __pyx_k5;
-static unsigned long __pyx_k6;
-static unsigned long __pyx_k7;
-static struct __pyx_t_11iocpsupport_myOVERLAPPED *__pyx_f_11iocpsupport_makeOV(void); /*proto*/
-static void __pyx_f_11iocpsupport_raise_error(int,PyObject *); /*proto*/
-static PyObject *__pyx_f_11iocpsupport__makesockaddr(struct sockaddr *,int); /*proto*/
-static PyObject *__pyx_f_11iocpsupport_fillinetaddr(struct sockaddr_in *,PyObject *); /*proto*/
-static int __pyx_f_11iocpsupport_getAddrFamily(__pyx_t_11iocpsupport_SOCKET); /*proto*/
-
-
-/* Implementation of iocpsupport */
-
-static char __pyx_k4[] = "Failed to initialize Winsock function vectors";
-
-static PyObject *__pyx_n_Event;
-static PyObject *__pyx_n___init__;
-static PyObject *__pyx_n_socket;
-static PyObject *__pyx_n_ValueError;
-static PyObject *__pyx_n_have_connectex;
-
-static PyObject *__pyx_k4p;
-
-static PyObject *__pyx_n_MemoryError;
-
-static struct __pyx_t_11iocpsupport_myOVERLAPPED *__pyx_f_11iocpsupport_makeOV(void) {
- struct __pyx_t_11iocpsupport_myOVERLAPPED *__pyx_v_res;
- struct __pyx_t_11iocpsupport_myOVERLAPPED *__pyx_r;
- void *__pyx_1;
- int __pyx_2;
- PyObject *__pyx_3 = 0;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":110 */
- __pyx_1 = PyMem_Malloc((sizeof(struct __pyx_t_11iocpsupport_myOVERLAPPED))); if (__pyx_1 == NULL) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; goto __pyx_L1;}
- __pyx_v_res = ((struct __pyx_t_11iocpsupport_myOVERLAPPED *)__pyx_1);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":111 */
- __pyx_2 = (!(__pyx_v_res != 0));
- if (__pyx_2) {
- __pyx_3 = __Pyx_GetName(__pyx_b, __pyx_n_MemoryError); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 112; goto __pyx_L1;}
- __Pyx_Raise(__pyx_3, 0, 0);
- Py_DECREF(__pyx_3); __pyx_3 = 0;
- {__pyx_filename = __pyx_f[0]; __pyx_lineno = 112; goto __pyx_L1;}
- goto __pyx_L2;
- }
- __pyx_L2:;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":113 */
- memset(__pyx_v_res,0,(sizeof(struct __pyx_t_11iocpsupport_myOVERLAPPED)));
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":114 */
- __pyx_r = __pyx_v_res;
- goto __pyx_L0;
-
- __pyx_r = 0;
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_3);
- __Pyx_AddTraceback("iocpsupport.makeOV");
- __pyx_r = NULL;
- __pyx_L0:;
- return __pyx_r;
-}
-
-static PyObject *__pyx_n_WindowsError;
-
-static void __pyx_f_11iocpsupport_raise_error(int __pyx_v_err,PyObject *__pyx_v_message) {
- int __pyx_1;
- PyObject *__pyx_2 = 0;
- PyObject *__pyx_3 = 0;
- PyObject *__pyx_4 = 0;
- Py_INCREF(__pyx_v_message);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":117 */
- __pyx_1 = (!__pyx_v_err);
- if (__pyx_1) {
- __pyx_v_err = GetLastError();
- goto __pyx_L2;
- }
- __pyx_L2:;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":119 */
- __pyx_2 = __Pyx_GetName(__pyx_b, __pyx_n_WindowsError); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; goto __pyx_L1;}
- __pyx_3 = PyInt_FromLong(__pyx_v_err); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; goto __pyx_L1;}
- __pyx_4 = PyTuple_New(2); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; goto __pyx_L1;}
- Py_INCREF(__pyx_v_message);
- PyTuple_SET_ITEM(__pyx_4, 0, __pyx_v_message);
- PyTuple_SET_ITEM(__pyx_4, 1, __pyx_3);
- __pyx_3 = 0;
- __pyx_3 = PyObject_CallObject(__pyx_2, __pyx_4); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; goto __pyx_L1;}
- Py_DECREF(__pyx_2); __pyx_2 = 0;
- Py_DECREF(__pyx_4); __pyx_4 = 0;
- __Pyx_Raise(__pyx_3, 0, 0);
- Py_DECREF(__pyx_3); __pyx_3 = 0;
- {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; goto __pyx_L1;}
-
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_2);
- Py_XDECREF(__pyx_3);
- Py_XDECREF(__pyx_4);
- __Pyx_AddTraceback("iocpsupport.raise_error");
- __pyx_L0:;
- Py_DECREF(__pyx_v_message);
-}
-
-static PyObject *__pyx_n_callback;
-static PyObject *__pyx_n_owner;
-static PyObject *__pyx_n_False;
-static PyObject *__pyx_n_ignore;
-static PyObject *__pyx_n_items;
-
-static PyObject *__pyx_f_11iocpsupport_5Event___init__(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static PyMethodDef __pyx_mdef_11iocpsupport_5Event___init__ = {"__init__", (PyCFunction)__pyx_f_11iocpsupport_5Event___init__, METH_VARARGS|METH_KEYWORDS, 0};
-static PyObject *__pyx_f_11iocpsupport_5Event___init__(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- PyObject *__pyx_v_self = 0;
- PyObject *__pyx_v_callback = 0;
- PyObject *__pyx_v_owner = 0;
- PyObject *__pyx_v_kw = 0;
- PyObject *__pyx_v_k;
- PyObject *__pyx_v_v;
- PyObject *__pyx_r;
- PyObject *__pyx_1 = 0;
- PyObject *__pyx_2 = 0;
- PyObject *__pyx_3 = 0;
- int __pyx_4;
- static char *__pyx_argnames[] = {"self","callback","owner",0};
- if (__Pyx_GetStarArgs(&__pyx_args, &__pyx_kwds, __pyx_argnames, 3, 0, &__pyx_v_kw, 0) < 0) return 0;
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "OOO", __pyx_argnames, &__pyx_v_self, &__pyx_v_callback, &__pyx_v_owner)) {
- Py_XDECREF(__pyx_args);
- Py_XDECREF(__pyx_kwds);
- Py_XDECREF(__pyx_v_kw);
- return 0;
- }
- Py_INCREF(__pyx_v_self);
- Py_INCREF(__pyx_v_callback);
- Py_INCREF(__pyx_v_owner);
- __pyx_v_k = Py_None; Py_INCREF(Py_None);
- __pyx_v_v = Py_None; Py_INCREF(Py_None);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":123 */
- if (PyObject_SetAttr(__pyx_v_self, __pyx_n_callback, __pyx_v_callback) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 123; goto __pyx_L1;}
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":124 */
- if (PyObject_SetAttr(__pyx_v_self, __pyx_n_owner, __pyx_v_owner) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; goto __pyx_L1;}
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":125 */
- __pyx_1 = __Pyx_GetName(__pyx_b, __pyx_n_False); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; goto __pyx_L1;}
- if (PyObject_SetAttr(__pyx_v_self, __pyx_n_ignore, __pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; goto __pyx_L1;}
- Py_DECREF(__pyx_1); __pyx_1 = 0;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":126 */
- __pyx_1 = PyObject_GetAttr(__pyx_v_kw, __pyx_n_items); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; goto __pyx_L1;}
- __pyx_2 = PyObject_CallObject(__pyx_1, 0); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; goto __pyx_L1;}
- Py_DECREF(__pyx_1); __pyx_1 = 0;
- __pyx_1 = PyObject_GetIter(__pyx_2); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; goto __pyx_L1;}
- Py_DECREF(__pyx_2); __pyx_2 = 0;
- for (;;) {
- __pyx_2 = PyIter_Next(__pyx_1);
- if (!__pyx_2) {
- if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; goto __pyx_L1;}
- break;
- }
- __pyx_3 = PyObject_GetIter(__pyx_2); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; goto __pyx_L1;}
- Py_DECREF(__pyx_2); __pyx_2 = 0;
- __pyx_2 = __Pyx_UnpackItem(__pyx_3); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; goto __pyx_L1;}
- Py_DECREF(__pyx_v_k);
- __pyx_v_k = __pyx_2;
- __pyx_2 = 0;
- __pyx_2 = __Pyx_UnpackItem(__pyx_3); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; goto __pyx_L1;}
- Py_DECREF(__pyx_v_v);
- __pyx_v_v = __pyx_2;
- __pyx_2 = 0;
- if (__Pyx_EndUnpack(__pyx_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; goto __pyx_L1;}
- Py_DECREF(__pyx_3); __pyx_3 = 0;
- __pyx_4 = PyObject_SetAttr(__pyx_v_self,__pyx_v_k,__pyx_v_v); if (__pyx_4 == -1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; goto __pyx_L1;}
- }
- Py_DECREF(__pyx_1); __pyx_1 = 0;
-
- __pyx_r = Py_None; Py_INCREF(Py_None);
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_1);
- Py_XDECREF(__pyx_2);
- Py_XDECREF(__pyx_3);
- __Pyx_AddTraceback("iocpsupport.Event.__init__");
- __pyx_r = 0;
- __pyx_L0:;
- Py_XDECREF(__pyx_v_kw);
- Py_DECREF(__pyx_v_k);
- Py_DECREF(__pyx_v_v);
- Py_DECREF(__pyx_v_self);
- Py_DECREF(__pyx_v_callback);
- Py_DECREF(__pyx_v_owner);
- Py_XDECREF(__pyx_args);
- Py_XDECREF(__pyx_kwds);
- return __pyx_r;
-}
-
-static PyObject *__pyx_n_CreateIoCompletionPort;
-
-
-static int __pyx_f_11iocpsupport_14CompletionPort___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static int __pyx_f_11iocpsupport_14CompletionPort___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- __pyx_t_11iocpsupport_HANDLE __pyx_v_res;
- int __pyx_r;
- int __pyx_1;
- static char *__pyx_argnames[] = {0};
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "", __pyx_argnames)) return -1;
- Py_INCREF(__pyx_v_self);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":133 */
- __pyx_v_res = CreateIoCompletionPort(INVALID_HANDLE_VALUE,0,0,0);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":134 */
- __pyx_1 = (!__pyx_v_res);
- if (__pyx_1) {
- __pyx_f_11iocpsupport_raise_error(0,__pyx_n_CreateIoCompletionPort); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 135; goto __pyx_L1;}
- goto __pyx_L2;
- }
- __pyx_L2:;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":136 */
- ((struct __pyx_obj_11iocpsupport_CompletionPort *)__pyx_v_self)->port = __pyx_v_res;
-
- __pyx_r = 0;
- goto __pyx_L0;
- __pyx_L1:;
- __Pyx_AddTraceback("iocpsupport.CompletionPort.__init__");
- __pyx_r = -1;
- __pyx_L0:;
- Py_DECREF(__pyx_v_self);
- return __pyx_r;
-}
-
-
-static PyObject *__pyx_f_11iocpsupport_14CompletionPort_addHandle(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static PyObject *__pyx_f_11iocpsupport_14CompletionPort_addHandle(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- long __pyx_v_handle;
- long __pyx_v_key;
- __pyx_t_11iocpsupport_HANDLE __pyx_v_res;
- PyObject *__pyx_r;
- int __pyx_1;
- static char *__pyx_argnames[] = {"handle","key",0};
- __pyx_v_key = __pyx_k2;
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "l|l", __pyx_argnames, &__pyx_v_handle, &__pyx_v_key)) return 0;
- Py_INCREF(__pyx_v_self);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":140 */
- __pyx_v_res = CreateIoCompletionPort(__pyx_v_handle,((struct __pyx_obj_11iocpsupport_CompletionPort *)__pyx_v_self)->port,__pyx_v_key,0);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":141 */
- __pyx_1 = (!__pyx_v_res);
- if (__pyx_1) {
- __pyx_f_11iocpsupport_raise_error(0,__pyx_n_CreateIoCompletionPort); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 142; goto __pyx_L1;}
- goto __pyx_L2;
- }
- __pyx_L2:;
-
- __pyx_r = Py_None; Py_INCREF(Py_None);
- goto __pyx_L0;
- __pyx_L1:;
- __Pyx_AddTraceback("iocpsupport.CompletionPort.addHandle");
- __pyx_r = 0;
- __pyx_L0:;
- Py_DECREF(__pyx_v_self);
- return __pyx_r;
-}
-
-static PyObject *__pyx_f_11iocpsupport_14CompletionPort_getEvent(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static PyObject *__pyx_f_11iocpsupport_14CompletionPort_getEvent(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- long __pyx_v_timeout;
- struct PyThreadState *__pyx_v__save;
- unsigned long __pyx_v_bytes;
- unsigned long __pyx_v_key;
- unsigned long __pyx_v_rc;
- struct __pyx_t_11iocpsupport_myOVERLAPPED *__pyx_v_ov;
- PyObject *__pyx_v_obj;
- PyObject *__pyx_r;
- int __pyx_1;
- PyObject *__pyx_2 = 0;
- PyObject *__pyx_3 = 0;
- PyObject *__pyx_4 = 0;
- PyObject *__pyx_5 = 0;
- static char *__pyx_argnames[] = {"timeout",0};
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "l", __pyx_argnames, &__pyx_v_timeout)) return 0;
- Py_INCREF(__pyx_v_self);
- __pyx_v_obj = Py_None; Py_INCREF(Py_None);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":149 */
- __pyx_v__save = PyEval_SaveThread();
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":150 */
- __pyx_v_rc = GetQueuedCompletionStatus(((struct __pyx_obj_11iocpsupport_CompletionPort *)__pyx_v_self)->port,(&__pyx_v_bytes),(&__pyx_v_key),((OVERLAPPED **)(&__pyx_v_ov)),__pyx_v_timeout);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":151 */
- PyEval_RestoreThread(__pyx_v__save);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":153 */
- __pyx_1 = (!__pyx_v_rc);
- if (__pyx_1) {
- __pyx_v_rc = GetLastError();
- goto __pyx_L2;
- }
- /*else*/ {
- __pyx_v_rc = 0;
- }
- __pyx_L2:;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":158 */
- Py_INCREF(Py_None);
- Py_DECREF(__pyx_v_obj);
- __pyx_v_obj = Py_None;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":159 */
- __pyx_1 = (__pyx_v_ov != 0);
- if (__pyx_1) {
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":160 */
- __pyx_1 = (__pyx_v_ov->obj != 0);
- if (__pyx_1) {
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":161 */
- __pyx_2 = (PyObject *)__pyx_v_ov->obj;
- Py_INCREF(__pyx_2);
- Py_DECREF(__pyx_v_obj);
- __pyx_v_obj = __pyx_2;
- __pyx_2 = 0;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":162 */
- Py_DECREF(__pyx_v_obj);
- goto __pyx_L4;
- }
- __pyx_L4:;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":163 */
- PyMem_Free(__pyx_v_ov);
- goto __pyx_L3;
- }
- __pyx_L3:;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":165 */
- __pyx_2 = PyLong_FromUnsignedLong(__pyx_v_rc); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 165; goto __pyx_L1;}
- __pyx_3 = PyLong_FromUnsignedLong(__pyx_v_bytes); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 165; goto __pyx_L1;}
- __pyx_4 = PyLong_FromUnsignedLong(__pyx_v_key); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 165; goto __pyx_L1;}
- __pyx_5 = PyTuple_New(4); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 165; goto __pyx_L1;}
- PyTuple_SET_ITEM(__pyx_5, 0, __pyx_2);
- PyTuple_SET_ITEM(__pyx_5, 1, __pyx_3);
- PyTuple_SET_ITEM(__pyx_5, 2, __pyx_4);
- Py_INCREF(__pyx_v_obj);
- PyTuple_SET_ITEM(__pyx_5, 3, __pyx_v_obj);
- __pyx_2 = 0;
- __pyx_3 = 0;
- __pyx_4 = 0;
- __pyx_r = __pyx_5;
- __pyx_5 = 0;
- goto __pyx_L0;
-
- __pyx_r = Py_None; Py_INCREF(Py_None);
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_2);
- Py_XDECREF(__pyx_3);
- Py_XDECREF(__pyx_4);
- Py_XDECREF(__pyx_5);
- __Pyx_AddTraceback("iocpsupport.CompletionPort.getEvent");
- __pyx_r = 0;
- __pyx_L0:;
- Py_DECREF(__pyx_v_obj);
- Py_DECREF(__pyx_v_self);
- return __pyx_r;
-}
-
-static PyObject *__pyx_n_PostQueuedCompletionStatus;
-
-
-static PyObject *__pyx_f_11iocpsupport_14CompletionPort_postEvent(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static PyObject *__pyx_f_11iocpsupport_14CompletionPort_postEvent(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- unsigned long __pyx_v_bytes;
- unsigned long __pyx_v_key;
- PyObject *__pyx_v_obj = 0;
- struct __pyx_t_11iocpsupport_myOVERLAPPED *__pyx_v_ov;
- unsigned long __pyx_v_rc;
- PyObject *__pyx_r;
- int __pyx_1;
- struct __pyx_t_11iocpsupport_myOVERLAPPED *__pyx_2;
- static char *__pyx_argnames[] = {"bytes","key","obj",0};
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "kkO", __pyx_argnames, &__pyx_v_bytes, &__pyx_v_key, &__pyx_v_obj)) return 0;
- Py_INCREF(__pyx_v_self);
- Py_INCREF(__pyx_v_obj);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":171 */
- __pyx_1 = __pyx_v_obj != Py_None;
- if (__pyx_1) {
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":172 */
- __pyx_2 = __pyx_f_11iocpsupport_makeOV(); if (__pyx_2 == NULL) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 172; goto __pyx_L1;}
- __pyx_v_ov = __pyx_2;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":173 */
- Py_INCREF(__pyx_v_obj);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":174 */
- __pyx_v_ov->obj = ((struct PyObject *)__pyx_v_obj);
- goto __pyx_L2;
- }
- /*else*/ {
- __pyx_v_ov = NULL;
- }
- __pyx_L2:;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":178 */
- __pyx_v_rc = PostQueuedCompletionStatus(((struct __pyx_obj_11iocpsupport_CompletionPort *)__pyx_v_self)->port,__pyx_v_bytes,__pyx_v_key,((OVERLAPPED *)__pyx_v_ov));
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":179 */
- __pyx_1 = (!__pyx_v_rc);
- if (__pyx_1) {
- __pyx_f_11iocpsupport_raise_error(0,__pyx_n_PostQueuedCompletionStatus); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; goto __pyx_L1;}
- goto __pyx_L3;
- }
- __pyx_L3:;
-
- __pyx_r = Py_None; Py_INCREF(Py_None);
- goto __pyx_L0;
- __pyx_L1:;
- __Pyx_AddTraceback("iocpsupport.CompletionPort.postEvent");
- __pyx_r = 0;
- __pyx_L0:;
- Py_DECREF(__pyx_v_self);
- Py_DECREF(__pyx_v_obj);
- return __pyx_r;
-}
-
-static PyObject *__pyx_f_11iocpsupport_14CompletionPort___del__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static PyObject *__pyx_f_11iocpsupport_14CompletionPort___del__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- PyObject *__pyx_r;
- static char *__pyx_argnames[] = {0};
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "", __pyx_argnames)) return 0;
- Py_INCREF(__pyx_v_self);
- CloseHandle(((struct __pyx_obj_11iocpsupport_CompletionPort *)__pyx_v_self)->port);
-
- __pyx_r = Py_None; Py_INCREF(Py_None);
- Py_DECREF(__pyx_v_self);
- return __pyx_r;
-}
-
-static PyObject *__pyx_f_11iocpsupport_makesockaddr(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static PyObject *__pyx_f_11iocpsupport_makesockaddr(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- PyObject *__pyx_v_buff = 0;
- void *__pyx_v_mem_buffer;
- int __pyx_v_size;
- PyObject *__pyx_r;
- int __pyx_1;
- PyObject *__pyx_2 = 0;
- static char *__pyx_argnames[] = {"buff",0};
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "O", __pyx_argnames, &__pyx_v_buff)) return 0;
- Py_INCREF(__pyx_v_buff);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":189 */
- __pyx_1 = PyObject_AsReadBuffer(__pyx_v_buff,(&__pyx_v_mem_buffer),(&__pyx_v_size)); if (__pyx_1 == (-1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 189; goto __pyx_L1;}
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":191 */
- __pyx_2 = __pyx_f_11iocpsupport__makesockaddr(((struct sockaddr *)__pyx_v_mem_buffer),__pyx_v_size); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 191; goto __pyx_L1;}
- __pyx_r = __pyx_2;
- __pyx_2 = 0;
- goto __pyx_L0;
-
- __pyx_r = Py_None; Py_INCREF(Py_None);
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_2);
- __Pyx_AddTraceback("iocpsupport.makesockaddr");
- __pyx_r = 0;
- __pyx_L0:;
- Py_DECREF(__pyx_v_buff);
- return __pyx_r;
-}
-
-static PyObject *__pyx_f_11iocpsupport__makesockaddr(struct sockaddr *__pyx_v_addr,int __pyx_v_len) {
- struct sockaddr_in *__pyx_v_sin;
- PyObject *__pyx_r;
- int __pyx_1;
- PyObject *__pyx_2 = 0;
- PyObject *__pyx_3 = 0;
- PyObject *__pyx_4 = 0;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":195 */
- __pyx_1 = (!__pyx_v_len);
- if (__pyx_1) {
- Py_INCREF(Py_None);
- __pyx_r = Py_None;
- goto __pyx_L0;
- goto __pyx_L2;
- }
- __pyx_L2:;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":197 */
- __pyx_1 = (__pyx_v_addr->sa_family == AF_INET);
- if (__pyx_1) {
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":198 */
- __pyx_v_sin = ((struct sockaddr_in *)__pyx_v_addr);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":199 */
- __pyx_2 = PyString_FromString(inet_ntoa(__pyx_v_sin->sin_addr)); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; goto __pyx_L1;}
- __pyx_3 = PyInt_FromLong(ntohs(__pyx_v_sin->sin_port)); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; goto __pyx_L1;}
- __pyx_4 = PyTuple_New(2); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; goto __pyx_L1;}
- PyTuple_SET_ITEM(__pyx_4, 0, __pyx_2);
- PyTuple_SET_ITEM(__pyx_4, 1, __pyx_3);
- __pyx_2 = 0;
- __pyx_3 = 0;
- __pyx_r = __pyx_4;
- __pyx_4 = 0;
- goto __pyx_L0;
- goto __pyx_L3;
- }
- /*else*/ {
- __pyx_2 = PyString_FromStringAndSize(__pyx_v_addr->sa_data,(sizeof(__pyx_v_addr->sa_data))); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; goto __pyx_L1;}
- __pyx_r = __pyx_2;
- __pyx_2 = 0;
- goto __pyx_L0;
- }
- __pyx_L3:;
-
- __pyx_r = Py_None; Py_INCREF(Py_None);
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_2);
- Py_XDECREF(__pyx_3);
- Py_XDECREF(__pyx_4);
- __Pyx_AddTraceback("iocpsupport._makesockaddr");
- __pyx_r = 0;
- __pyx_L0:;
- return __pyx_r;
-}
-
-static PyObject *__pyx_k11p;
-
-static char __pyx_k11[] = "invalid IP address";
-
-static PyObject *__pyx_f_11iocpsupport_fillinetaddr(struct sockaddr_in *__pyx_v_dest,PyObject *__pyx_v_addr) {
- short __pyx_v_port;
- unsigned long __pyx_v_res;
- char *__pyx_v_hoststr;
- PyObject *__pyx_v_host;
- PyObject *__pyx_r;
- PyObject *__pyx_1 = 0;
- PyObject *__pyx_2 = 0;
- short __pyx_3;
- char *__pyx_4;
- int __pyx_5;
- Py_INCREF(__pyx_v_addr);
- __pyx_v_host = Py_None; Py_INCREF(Py_None);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":207 */
- __pyx_1 = PyObject_GetIter(__pyx_v_addr); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; goto __pyx_L1;}
- __pyx_2 = __Pyx_UnpackItem(__pyx_1); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; goto __pyx_L1;}
- Py_DECREF(__pyx_v_host);
- __pyx_v_host = __pyx_2;
- __pyx_2 = 0;
- __pyx_2 = __Pyx_UnpackItem(__pyx_1); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; goto __pyx_L1;}
- __pyx_3 = PyInt_AsLong(__pyx_2); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; goto __pyx_L1;}
- Py_DECREF(__pyx_2); __pyx_2 = 0;
- __pyx_v_port = __pyx_3;
- if (__Pyx_EndUnpack(__pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 207; goto __pyx_L1;}
- Py_DECREF(__pyx_1); __pyx_1 = 0;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":209 */
- __pyx_4 = PyString_AsString(__pyx_v_host); if (__pyx_4 == NULL) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 209; goto __pyx_L1;}
- __pyx_v_hoststr = __pyx_4;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":210 */
- __pyx_v_res = inet_addr(__pyx_v_hoststr);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":211 */
- __pyx_5 = (__pyx_v_res == INADDR_ANY);
- if (__pyx_5) {
- __pyx_2 = __Pyx_GetName(__pyx_b, __pyx_n_ValueError); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; goto __pyx_L1;}
- __Pyx_Raise(__pyx_2, __pyx_k11p, 0);
- Py_DECREF(__pyx_2); __pyx_2 = 0;
- {__pyx_filename = __pyx_f[0]; __pyx_lineno = 212; goto __pyx_L1;}
- goto __pyx_L2;
- }
- __pyx_L2:;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":213 */
- __pyx_v_dest->sin_addr.s_addr = __pyx_v_res;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":215 */
- __pyx_v_dest->sin_port = htons(__pyx_v_port);
-
- __pyx_r = Py_None; Py_INCREF(Py_None);
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_1);
- Py_XDECREF(__pyx_2);
- __Pyx_AddTraceback("iocpsupport.fillinetaddr");
- __pyx_r = 0;
- __pyx_L0:;
- Py_DECREF(__pyx_v_host);
- Py_DECREF(__pyx_v_addr);
- return __pyx_r;
-}
-
-static PyObject *__pyx_f_11iocpsupport_AllocateReadBuffer(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static PyObject *__pyx_f_11iocpsupport_AllocateReadBuffer(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- int __pyx_v_size;
- PyObject *__pyx_r;
- PyObject *__pyx_1 = 0;
- static char *__pyx_argnames[] = {"size",0};
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "i", __pyx_argnames, &__pyx_v_size)) return 0;
- __pyx_1 = PyBuffer_New(__pyx_v_size); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; goto __pyx_L1;}
- __pyx_r = __pyx_1;
- __pyx_1 = 0;
- goto __pyx_L0;
-
- __pyx_r = Py_None; Py_INCREF(Py_None);
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_1);
- __Pyx_AddTraceback("iocpsupport.AllocateReadBuffer");
- __pyx_r = 0;
- __pyx_L0:;
- return __pyx_r;
-}
-
-static PyObject *__pyx_n_getsockopt;
-
-
-static PyObject *__pyx_f_11iocpsupport_maxAddrLen(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static PyObject *__pyx_f_11iocpsupport_maxAddrLen(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- long __pyx_v_s;
- WSAPROTOCOL_INFO __pyx_v_wsa_pi;
- int __pyx_v_size;
- int __pyx_v_rc;
- PyObject *__pyx_r;
- int __pyx_1;
- PyObject *__pyx_2 = 0;
- static char *__pyx_argnames[] = {"s",0};
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "l", __pyx_argnames, &__pyx_v_s)) return 0;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":224 */
- __pyx_v_size = (sizeof(__pyx_v_wsa_pi));
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":225 */
- __pyx_v_rc = getsockopt(__pyx_v_s,SOL_SOCKET,SO_PROTOCOL_INFO,((char *)(&__pyx_v_wsa_pi)),(&__pyx_v_size));
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":226 */
- __pyx_1 = (__pyx_v_rc == SOCKET_ERROR);
- if (__pyx_1) {
- __pyx_f_11iocpsupport_raise_error(WSAGetLastError(),__pyx_n_getsockopt); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 227; goto __pyx_L1;}
- goto __pyx_L2;
- }
- __pyx_L2:;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":228 */
- __pyx_2 = PyInt_FromLong(__pyx_v_wsa_pi.iMaxSockAddr); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 228; goto __pyx_L1;}
- __pyx_r = __pyx_2;
- __pyx_2 = 0;
- goto __pyx_L0;
-
- __pyx_r = Py_None; Py_INCREF(Py_None);
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_2);
- __Pyx_AddTraceback("iocpsupport.maxAddrLen");
- __pyx_r = 0;
- __pyx_L0:;
- return __pyx_r;
-}
-
-
-static int __pyx_f_11iocpsupport_getAddrFamily(__pyx_t_11iocpsupport_SOCKET __pyx_v_s) {
- WSAPROTOCOL_INFO __pyx_v_wsa_pi;
- int __pyx_v_size;
- int __pyx_v_rc;
- int __pyx_r;
- int __pyx_1;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":234 */
- __pyx_v_size = (sizeof(__pyx_v_wsa_pi));
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":235 */
- __pyx_v_rc = getsockopt(__pyx_v_s,SOL_SOCKET,SO_PROTOCOL_INFO,((char *)(&__pyx_v_wsa_pi)),(&__pyx_v_size));
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":236 */
- __pyx_1 = (__pyx_v_rc == SOCKET_ERROR);
- if (__pyx_1) {
- __pyx_f_11iocpsupport_raise_error(WSAGetLastError(),__pyx_n_getsockopt); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 237; goto __pyx_L1;}
- goto __pyx_L2;
- }
- __pyx_L2:;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":238 */
- __pyx_r = __pyx_v_wsa_pi.iAddressFamily;
- goto __pyx_L0;
-
- __pyx_r = 0;
- goto __pyx_L0;
- __pyx_L1:;
- __Pyx_AddTraceback("iocpsupport.getAddrFamily");
- __pyx_L0:;
- return __pyx_r;
-}
-
-static PyObject *__pyx_f_11iocpsupport_accept(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static PyObject *__pyx_f_11iocpsupport_accept(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- long __pyx_v_listening;
- long __pyx_v_accepting;
- PyObject *__pyx_v_buff = 0;
- PyObject *__pyx_v_obj = 0;
- unsigned long __pyx_v_bytes;
- int __pyx_v_size;
- int __pyx_v_rc;
- void *__pyx_v_mem_buffer;
- struct __pyx_t_11iocpsupport_myOVERLAPPED *__pyx_v_ov;
- PyObject *__pyx_r;
- int __pyx_1;
- struct __pyx_t_11iocpsupport_myOVERLAPPED *__pyx_2;
- PyObject *__pyx_3 = 0;
- static char *__pyx_argnames[] = {"listening","accepting","buff","obj",0};
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "llOO", __pyx_argnames, &__pyx_v_listening, &__pyx_v_accepting, &__pyx_v_buff, &__pyx_v_obj)) return 0;
- Py_INCREF(__pyx_v_buff);
- Py_INCREF(__pyx_v_obj);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\acceptex.pxi":11 */
- __pyx_1 = PyObject_AsWriteBuffer(__pyx_v_buff,(&__pyx_v_mem_buffer),(&__pyx_v_size)); if (__pyx_1 == (-1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 11; goto __pyx_L1;}
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\acceptex.pxi":13 */
- __pyx_2 = __pyx_f_11iocpsupport_makeOV(); if (__pyx_2 == NULL) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 13; goto __pyx_L1;}
- __pyx_v_ov = __pyx_2;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\acceptex.pxi":14 */
- __pyx_1 = __pyx_v_obj != Py_None;
- if (__pyx_1) {
- __pyx_v_ov->obj = ((struct PyObject *)__pyx_v_obj);
- goto __pyx_L2;
- }
- __pyx_L2:;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\acceptex.pxi":17 */
- __pyx_v_rc = lpAcceptEx(__pyx_v_listening,__pyx_v_accepting,__pyx_v_mem_buffer,0,(__pyx_v_size / 2),(__pyx_v_size / 2),(&__pyx_v_bytes),((OVERLAPPED *)__pyx_v_ov));
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\acceptex.pxi":19 */
- __pyx_1 = (!__pyx_v_rc);
- if (__pyx_1) {
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\acceptex.pxi":20 */
- __pyx_v_rc = WSAGetLastError();
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\acceptex.pxi":21 */
- __pyx_1 = (__pyx_v_rc != ERROR_IO_PENDING);
- if (__pyx_1) {
- __pyx_3 = PyInt_FromLong(__pyx_v_rc); if (!__pyx_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 22; goto __pyx_L1;}
- __pyx_r = __pyx_3;
- __pyx_3 = 0;
- goto __pyx_L0;
- goto __pyx_L4;
- }
- __pyx_L4:;
- goto __pyx_L3;
- }
- __pyx_L3:;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\acceptex.pxi":25 */
- Py_XINCREF(__pyx_v_obj);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\acceptex.pxi":26 */
- __pyx_3 = PyInt_FromLong(__pyx_v_rc); if (!__pyx_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 26; goto __pyx_L1;}
- __pyx_r = __pyx_3;
- __pyx_3 = 0;
- goto __pyx_L0;
-
- __pyx_r = Py_None; Py_INCREF(Py_None);
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_3);
- __Pyx_AddTraceback("iocpsupport.accept");
- __pyx_r = 0;
- __pyx_L0:;
- Py_DECREF(__pyx_v_buff);
- Py_DECREF(__pyx_v_obj);
- return __pyx_r;
-}
-
-static PyObject *__pyx_f_11iocpsupport_get_accept_addrs(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static PyObject *__pyx_f_11iocpsupport_get_accept_addrs(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- long __pyx_v_s;
- PyObject *__pyx_v_buff = 0;
- int __pyx_v_size;
- int __pyx_v_locallen;
- int __pyx_v_remotelen;
- void *__pyx_v_mem_buffer;
- struct sockaddr *__pyx_v_localaddr;
- struct sockaddr *__pyx_v_remoteaddr;
- PyObject *__pyx_r;
- int __pyx_1;
- PyObject *__pyx_2 = 0;
- PyObject *__pyx_3 = 0;
- PyObject *__pyx_4 = 0;
- PyObject *__pyx_5 = 0;
- static char *__pyx_argnames[] = {"s","buff",0};
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "lO", __pyx_argnames, &__pyx_v_s, &__pyx_v_buff)) return 0;
- Py_INCREF(__pyx_v_buff);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\acceptex.pxi":34 */
- __pyx_1 = PyObject_AsReadBuffer(__pyx_v_buff,(&__pyx_v_mem_buffer),(&__pyx_v_size)); if (__pyx_1 == (-1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 34; goto __pyx_L1;}
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\acceptex.pxi":36 */
- lpGetAcceptExSockaddrs(__pyx_v_mem_buffer,0,(__pyx_v_size / 2),(__pyx_v_size / 2),(&__pyx_v_localaddr),(&__pyx_v_locallen),(&__pyx_v_remoteaddr),(&__pyx_v_remotelen));
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\acceptex.pxi":37 */
- __pyx_2 = PyInt_FromLong(__pyx_v_remoteaddr->sa_family); if (!__pyx_2) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 37; goto __pyx_L1;}
- __pyx_3 = __pyx_f_11iocpsupport__makesockaddr(__pyx_v_localaddr,__pyx_v_locallen); if (!__pyx_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 37; goto __pyx_L1;}
- __pyx_4 = __pyx_f_11iocpsupport__makesockaddr(__pyx_v_remoteaddr,__pyx_v_remotelen); if (!__pyx_4) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 37; goto __pyx_L1;}
- __pyx_5 = PyTuple_New(3); if (!__pyx_5) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 37; goto __pyx_L1;}
- PyTuple_SET_ITEM(__pyx_5, 0, __pyx_2);
- PyTuple_SET_ITEM(__pyx_5, 1, __pyx_3);
- PyTuple_SET_ITEM(__pyx_5, 2, __pyx_4);
- __pyx_2 = 0;
- __pyx_3 = 0;
- __pyx_4 = 0;
- __pyx_r = __pyx_5;
- __pyx_5 = 0;
- goto __pyx_L0;
-
- __pyx_r = Py_None; Py_INCREF(Py_None);
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_2);
- Py_XDECREF(__pyx_3);
- Py_XDECREF(__pyx_4);
- Py_XDECREF(__pyx_5);
- __Pyx_AddTraceback("iocpsupport.get_accept_addrs");
- __pyx_r = 0;
- __pyx_L0:;
- Py_DECREF(__pyx_v_buff);
- return __pyx_r;
-}
-
-static PyObject *__pyx_k14p;
-static PyObject *__pyx_k15p;
-
-static char __pyx_k14[] = "ConnectEx is not available on this system";
-static char __pyx_k15[] = "unsupported address family";
-
-static PyObject *__pyx_f_11iocpsupport_connect(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static PyObject *__pyx_f_11iocpsupport_connect(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- long __pyx_v_s;
- PyObject *__pyx_v_addr = 0;
- PyObject *__pyx_v_obj = 0;
- int __pyx_v_family;
- int __pyx_v_rc;
- struct __pyx_t_11iocpsupport_myOVERLAPPED *__pyx_v_ov;
- struct sockaddr __pyx_v_name;
- PyObject *__pyx_r;
- PyObject *__pyx_1 = 0;
- int __pyx_2;
- int __pyx_3;
- struct __pyx_t_11iocpsupport_myOVERLAPPED *__pyx_4;
- static char *__pyx_argnames[] = {"s","addr","obj",0};
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "lOO", __pyx_argnames, &__pyx_v_s, &__pyx_v_addr, &__pyx_v_obj)) return 0;
- Py_INCREF(__pyx_v_addr);
- Py_INCREF(__pyx_v_obj);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\connectex.pxi":10 */
- __pyx_1 = __Pyx_GetName(__pyx_m, __pyx_n_have_connectex); if (!__pyx_1) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 10; goto __pyx_L1;}
- __pyx_2 = PyObject_IsTrue(__pyx_1); if (__pyx_2 < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 10; goto __pyx_L1;}
- Py_DECREF(__pyx_1); __pyx_1 = 0;
- __pyx_3 = (!__pyx_2);
- if (__pyx_3) {
- __pyx_1 = __Pyx_GetName(__pyx_b, __pyx_n_ValueError); if (!__pyx_1) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 11; goto __pyx_L1;}
- __Pyx_Raise(__pyx_1, __pyx_k14p, 0);
- Py_DECREF(__pyx_1); __pyx_1 = 0;
- {__pyx_filename = __pyx_f[2]; __pyx_lineno = 11; goto __pyx_L1;}
- goto __pyx_L2;
- }
- __pyx_L2:;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\connectex.pxi":13 */
- __pyx_2 = __pyx_f_11iocpsupport_getAddrFamily(__pyx_v_s); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 13; goto __pyx_L1;}
- __pyx_v_family = __pyx_2;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\connectex.pxi":14 */
- __pyx_3 = (__pyx_v_family == AF_INET);
- if (__pyx_3) {
- __pyx_1 = __pyx_f_11iocpsupport_fillinetaddr(((struct sockaddr_in *)(&__pyx_v_name)),__pyx_v_addr); if (!__pyx_1) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 15; goto __pyx_L1;}
- Py_DECREF(__pyx_1); __pyx_1 = 0;
- goto __pyx_L3;
- }
- /*else*/ {
- __pyx_1 = __Pyx_GetName(__pyx_b, __pyx_n_ValueError); if (!__pyx_1) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 17; goto __pyx_L1;}
- __Pyx_Raise(__pyx_1, __pyx_k15p, 0);
- Py_DECREF(__pyx_1); __pyx_1 = 0;
- {__pyx_filename = __pyx_f[2]; __pyx_lineno = 17; goto __pyx_L1;}
- }
- __pyx_L3:;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\connectex.pxi":18 */
- __pyx_v_name.sa_family = __pyx_v_family;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\connectex.pxi":20 */
- __pyx_4 = __pyx_f_11iocpsupport_makeOV(); if (__pyx_4 == NULL) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 20; goto __pyx_L1;}
- __pyx_v_ov = __pyx_4;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\connectex.pxi":21 */
- __pyx_2 = __pyx_v_obj != Py_None;
- if (__pyx_2) {
- __pyx_v_ov->obj = ((struct PyObject *)__pyx_v_obj);
- goto __pyx_L4;
- }
- __pyx_L4:;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\connectex.pxi":24 */
- __pyx_v_rc = lpConnectEx(__pyx_v_s,(&__pyx_v_name),(sizeof(__pyx_v_name)),NULL,0,NULL,((OVERLAPPED *)__pyx_v_ov));
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\connectex.pxi":26 */
- __pyx_3 = (!__pyx_v_rc);
- if (__pyx_3) {
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\connectex.pxi":27 */
- __pyx_v_rc = WSAGetLastError();
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\connectex.pxi":28 */
- __pyx_2 = (__pyx_v_rc != ERROR_IO_PENDING);
- if (__pyx_2) {
- __pyx_1 = PyInt_FromLong(__pyx_v_rc); if (!__pyx_1) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 29; goto __pyx_L1;}
- __pyx_r = __pyx_1;
- __pyx_1 = 0;
- goto __pyx_L0;
- goto __pyx_L6;
- }
- __pyx_L6:;
- goto __pyx_L5;
- }
- __pyx_L5:;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\connectex.pxi":32 */
- Py_XINCREF(__pyx_v_obj);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\connectex.pxi":33 */
- __pyx_1 = PyInt_FromLong(__pyx_v_rc); if (!__pyx_1) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 33; goto __pyx_L1;}
- __pyx_r = __pyx_1;
- __pyx_1 = 0;
- goto __pyx_L0;
-
- __pyx_r = Py_None; Py_INCREF(Py_None);
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_1);
- __Pyx_AddTraceback("iocpsupport.connect");
- __pyx_r = 0;
- __pyx_L0:;
- Py_DECREF(__pyx_v_addr);
- Py_DECREF(__pyx_v_obj);
- return __pyx_r;
-}
-
-static char __pyx_k16[] = "second argument needs to be a list";
-
-static PyObject *__pyx_f_11iocpsupport_recv(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static PyObject *__pyx_f_11iocpsupport_recv(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- long __pyx_v_s;
- PyObject *__pyx_v_bufflist = 0;
- PyObject *__pyx_v_obj = 0;
- unsigned long __pyx_v_flags;
- int __pyx_v_rc;
- int __pyx_v_buffcount;
- int __pyx_v_i;
- struct __pyx_t_11iocpsupport_myOVERLAPPED *__pyx_v_ov;
- WSABUF *__pyx_v_ws_buf;
- unsigned long __pyx_v_bytes;
- struct PyObject **__pyx_v_buffers;
- PyObject *__pyx_r;
- PyObject *__pyx_1 = 0;
- void *__pyx_2;
- int __pyx_3;
- struct __pyx_t_11iocpsupport_myOVERLAPPED *__pyx_4;
- PyObject *__pyx_5 = 0;
- PyObject *__pyx_6 = 0;
- static char *__pyx_argnames[] = {"s","bufflist","obj","flags",0};
- __pyx_v_flags = __pyx_k5;
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "lOO|k", __pyx_argnames, &__pyx_v_s, &__pyx_v_bufflist, &__pyx_v_obj, &__pyx_v_flags)) return 0;
- Py_INCREF(__pyx_v_bufflist);
- Py_INCREF(__pyx_v_obj);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsarecv.pxi":12 */
- __pyx_1 = PySequence_Fast(__pyx_v_bufflist,__pyx_k16); if (!__pyx_1) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 12; goto __pyx_L1;}
- Py_DECREF(__pyx_v_bufflist);
- __pyx_v_bufflist = __pyx_1;
- __pyx_1 = 0;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsarecv.pxi":13 */
- __pyx_v_buffcount = PySequence_Fast_GET_SIZE(__pyx_v_bufflist);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsarecv.pxi":14 */
- __pyx_v_buffers = PySequence_Fast_ITEMS(__pyx_v_bufflist);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsarecv.pxi":16 */
- __pyx_2 = PyMem_Malloc((__pyx_v_buffcount * (sizeof(WSABUF)))); if (__pyx_2 == NULL) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 16; goto __pyx_L1;}
- __pyx_v_ws_buf = ((WSABUF *)__pyx_2);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsarecv.pxi":18 */
- /*try:*/ {
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsarecv.pxi":19 */
- for (__pyx_v_i = 0; __pyx_v_i < __pyx_v_buffcount; ++__pyx_v_i) {
- __pyx_1 = (PyObject *)(__pyx_v_buffers[__pyx_v_i]);
- Py_INCREF(__pyx_1);
- __pyx_3 = PyObject_AsWriteBuffer(__pyx_1,((void **)(&(__pyx_v_ws_buf[__pyx_v_i]).buf)),((int *)(&(__pyx_v_ws_buf[__pyx_v_i]).len))); if (__pyx_3 == (-1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 20; goto __pyx_L3;}
- Py_DECREF(__pyx_1); __pyx_1 = 0;
- }
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsarecv.pxi":22 */
- __pyx_4 = __pyx_f_11iocpsupport_makeOV(); if (__pyx_4 == NULL) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 22; goto __pyx_L3;}
- __pyx_v_ov = __pyx_4;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsarecv.pxi":23 */
- __pyx_3 = __pyx_v_obj != Py_None;
- if (__pyx_3) {
- __pyx_v_ov->obj = ((struct PyObject *)__pyx_v_obj);
- goto __pyx_L7;
- }
- __pyx_L7:;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsarecv.pxi":26 */
- __pyx_v_rc = WSARecv(__pyx_v_s,__pyx_v_ws_buf,__pyx_v_buffcount,(&__pyx_v_bytes),(&__pyx_v_flags),((OVERLAPPED *)__pyx_v_ov),NULL);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsarecv.pxi":28 */
- __pyx_3 = (__pyx_v_rc == SOCKET_ERROR);
- if (__pyx_3) {
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsarecv.pxi":29 */
- __pyx_v_rc = WSAGetLastError();
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsarecv.pxi":30 */
- __pyx_3 = (__pyx_v_rc != ERROR_IO_PENDING);
- if (__pyx_3) {
- __pyx_1 = PyInt_FromLong(__pyx_v_rc); if (!__pyx_1) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 31; goto __pyx_L3;}
- __pyx_5 = PyInt_FromLong(0); if (!__pyx_5) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 31; goto __pyx_L3;}
- __pyx_6 = PyTuple_New(2); if (!__pyx_6) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 31; goto __pyx_L3;}
- PyTuple_SET_ITEM(__pyx_6, 0, __pyx_1);
- PyTuple_SET_ITEM(__pyx_6, 1, __pyx_5);
- __pyx_1 = 0;
- __pyx_5 = 0;
- __pyx_r = __pyx_6;
- __pyx_6 = 0;
- goto __pyx_L2;
- goto __pyx_L9;
- }
- __pyx_L9:;
- goto __pyx_L8;
- }
- __pyx_L8:;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsarecv.pxi":33 */
- Py_XINCREF(__pyx_v_obj);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsarecv.pxi":34 */
- __pyx_1 = PyInt_FromLong(__pyx_v_rc); if (!__pyx_1) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 34; goto __pyx_L3;}
- __pyx_5 = PyLong_FromUnsignedLong(__pyx_v_bytes); if (!__pyx_5) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 34; goto __pyx_L3;}
- __pyx_6 = PyTuple_New(2); if (!__pyx_6) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 34; goto __pyx_L3;}
- PyTuple_SET_ITEM(__pyx_6, 0, __pyx_1);
- PyTuple_SET_ITEM(__pyx_6, 1, __pyx_5);
- __pyx_1 = 0;
- __pyx_5 = 0;
- __pyx_r = __pyx_6;
- __pyx_6 = 0;
- goto __pyx_L2;
- }
- /*finally:*/ {
- int __pyx_why;
- PyObject *__pyx_exc_type, *__pyx_exc_value, *__pyx_exc_tb;
- int __pyx_exc_lineno;
- __pyx_why = 0; goto __pyx_L4;
- __pyx_L2: __pyx_why = 3; goto __pyx_L4;
- __pyx_L3: {
- __pyx_why = 4;
- Py_XDECREF(__pyx_1); __pyx_1 = 0;
- Py_XDECREF(__pyx_5); __pyx_5 = 0;
- Py_XDECREF(__pyx_6); __pyx_6 = 0;
- PyErr_Fetch(&__pyx_exc_type, &__pyx_exc_value, &__pyx_exc_tb);
- __pyx_exc_lineno = __pyx_lineno;
- goto __pyx_L4;
- }
- __pyx_L4:;
- PyMem_Free(__pyx_v_ws_buf);
- switch (__pyx_why) {
- case 3: goto __pyx_L0;
- case 4: {
- PyErr_Restore(__pyx_exc_type, __pyx_exc_value, __pyx_exc_tb);
- __pyx_lineno = __pyx_exc_lineno;
- __pyx_exc_type = 0;
- __pyx_exc_value = 0;
- __pyx_exc_tb = 0;
- goto __pyx_L1;
- }
- }
- }
-
- __pyx_r = Py_None; Py_INCREF(Py_None);
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_1);
- Py_XDECREF(__pyx_5);
- Py_XDECREF(__pyx_6);
- __Pyx_AddTraceback("iocpsupport.recv");
- __pyx_r = 0;
- __pyx_L0:;
- Py_DECREF(__pyx_v_bufflist);
- Py_DECREF(__pyx_v_obj);
- return __pyx_r;
-}
-
-static PyObject *__pyx_f_11iocpsupport_recvfrom(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static PyObject *__pyx_f_11iocpsupport_recvfrom(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- long __pyx_v_s;
- PyObject *__pyx_v_buff = 0;
- PyObject *__pyx_v_addr_buff = 0;
- PyObject *__pyx_v_obj = 0;
- unsigned long __pyx_v_flags;
- int __pyx_v_rc;
- int __pyx_v_fromlen;
- struct __pyx_t_11iocpsupport_myOVERLAPPED *__pyx_v_ov;
- WSABUF __pyx_v_ws_buf;
- unsigned long __pyx_v_bytes;
- struct sockaddr *__pyx_v_fromaddr;
- PyObject *__pyx_r;
- int __pyx_1;
- struct __pyx_t_11iocpsupport_myOVERLAPPED *__pyx_2;
- PyObject *__pyx_3 = 0;
- PyObject *__pyx_4 = 0;
- PyObject *__pyx_5 = 0;
- static char *__pyx_argnames[] = {"s","buff","addr_buff","obj","flags",0};
- __pyx_v_flags = __pyx_k6;
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "lOOO|k", __pyx_argnames, &__pyx_v_s, &__pyx_v_buff, &__pyx_v_addr_buff, &__pyx_v_obj, &__pyx_v_flags)) return 0;
- Py_INCREF(__pyx_v_buff);
- Py_INCREF(__pyx_v_addr_buff);
- Py_INCREF(__pyx_v_obj);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsarecv.pxi":45 */
- __pyx_1 = PyObject_AsWriteBuffer(__pyx_v_buff,((void **)(&__pyx_v_ws_buf.buf)),((int *)(&__pyx_v_ws_buf.len))); if (__pyx_1 == (-1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 45; goto __pyx_L1;}
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsarecv.pxi":46 */
- __pyx_1 = PyObject_AsWriteBuffer(__pyx_v_addr_buff,((void **)(&__pyx_v_fromaddr)),(&__pyx_v_fromlen)); if (__pyx_1 == (-1)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 46; goto __pyx_L1;}
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsarecv.pxi":48 */
- __pyx_2 = __pyx_f_11iocpsupport_makeOV(); if (__pyx_2 == NULL) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 48; goto __pyx_L1;}
- __pyx_v_ov = __pyx_2;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsarecv.pxi":49 */
- __pyx_1 = __pyx_v_obj != Py_None;
- if (__pyx_1) {
- __pyx_v_ov->obj = ((struct PyObject *)__pyx_v_obj);
- goto __pyx_L2;
- }
- __pyx_L2:;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsarecv.pxi":52 */
- __pyx_v_rc = WSARecvFrom(__pyx_v_s,(&__pyx_v_ws_buf),1,(&__pyx_v_bytes),(&__pyx_v_flags),__pyx_v_fromaddr,(&__pyx_v_fromlen),((OVERLAPPED *)__pyx_v_ov),NULL);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsarecv.pxi":54 */
- __pyx_1 = (__pyx_v_rc == SOCKET_ERROR);
- if (__pyx_1) {
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsarecv.pxi":55 */
- __pyx_v_rc = WSAGetLastError();
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsarecv.pxi":56 */
- __pyx_1 = (__pyx_v_rc != ERROR_IO_PENDING);
- if (__pyx_1) {
- __pyx_3 = PyInt_FromLong(__pyx_v_rc); if (!__pyx_3) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 57; goto __pyx_L1;}
- __pyx_4 = PyInt_FromLong(0); if (!__pyx_4) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 57; goto __pyx_L1;}
- __pyx_5 = PyTuple_New(2); if (!__pyx_5) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 57; goto __pyx_L1;}
- PyTuple_SET_ITEM(__pyx_5, 0, __pyx_3);
- PyTuple_SET_ITEM(__pyx_5, 1, __pyx_4);
- __pyx_3 = 0;
- __pyx_4 = 0;
- __pyx_r = __pyx_5;
- __pyx_5 = 0;
- goto __pyx_L0;
- goto __pyx_L4;
- }
- __pyx_L4:;
- goto __pyx_L3;
- }
- __pyx_L3:;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsarecv.pxi":59 */
- Py_XINCREF(__pyx_v_obj);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsarecv.pxi":60 */
- __pyx_3 = PyInt_FromLong(__pyx_v_rc); if (!__pyx_3) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 60; goto __pyx_L1;}
- __pyx_4 = PyLong_FromUnsignedLong(__pyx_v_bytes); if (!__pyx_4) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 60; goto __pyx_L1;}
- __pyx_5 = PyTuple_New(2); if (!__pyx_5) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 60; goto __pyx_L1;}
- PyTuple_SET_ITEM(__pyx_5, 0, __pyx_3);
- PyTuple_SET_ITEM(__pyx_5, 1, __pyx_4);
- __pyx_3 = 0;
- __pyx_4 = 0;
- __pyx_r = __pyx_5;
- __pyx_5 = 0;
- goto __pyx_L0;
-
- __pyx_r = Py_None; Py_INCREF(Py_None);
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_3);
- Py_XDECREF(__pyx_4);
- Py_XDECREF(__pyx_5);
- __Pyx_AddTraceback("iocpsupport.recvfrom");
- __pyx_r = 0;
- __pyx_L0:;
- Py_DECREF(__pyx_v_buff);
- Py_DECREF(__pyx_v_addr_buff);
- Py_DECREF(__pyx_v_obj);
- return __pyx_r;
-}
-
-static PyObject *__pyx_f_11iocpsupport_send(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
-static PyObject *__pyx_f_11iocpsupport_send(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
- long __pyx_v_s;
- PyObject *__pyx_v_buff = 0;
- PyObject *__pyx_v_obj = 0;
- unsigned long __pyx_v_flags;
- int __pyx_v_rc;
- struct __pyx_t_11iocpsupport_myOVERLAPPED *__pyx_v_ov;
- WSABUF __pyx_v_ws_buf;
- unsigned long __pyx_v_bytes;
- PyObject *__pyx_r;
- int __pyx_1;
- struct __pyx_t_11iocpsupport_myOVERLAPPED *__pyx_2;
- PyObject *__pyx_3 = 0;
- PyObject *__pyx_4 = 0;
- PyObject *__pyx_5 = 0;
- static char *__pyx_argnames[] = {"s","buff","obj","flags",0};
- __pyx_v_flags = __pyx_k7;
- if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "lOO|k", __pyx_argnames, &__pyx_v_s, &__pyx_v_buff, &__pyx_v_obj, &__pyx_v_flags)) return 0;
- Py_INCREF(__pyx_v_buff);
- Py_INCREF(__pyx_v_obj);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsasend.pxi":11 */
- __pyx_1 = PyObject_AsReadBuffer(__pyx_v_buff,((void **)(&__pyx_v_ws_buf.buf)),((int *)(&__pyx_v_ws_buf.len))); if (__pyx_1 == (-1)) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 11; goto __pyx_L1;}
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsasend.pxi":13 */
- __pyx_2 = __pyx_f_11iocpsupport_makeOV(); if (__pyx_2 == NULL) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 13; goto __pyx_L1;}
- __pyx_v_ov = __pyx_2;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsasend.pxi":14 */
- __pyx_1 = __pyx_v_obj != Py_None;
- if (__pyx_1) {
- __pyx_v_ov->obj = ((struct PyObject *)__pyx_v_obj);
- goto __pyx_L2;
- }
- __pyx_L2:;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsasend.pxi":17 */
- __pyx_v_rc = WSASend(__pyx_v_s,(&__pyx_v_ws_buf),1,(&__pyx_v_bytes),__pyx_v_flags,((OVERLAPPED *)__pyx_v_ov),NULL);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsasend.pxi":19 */
- __pyx_1 = (__pyx_v_rc == SOCKET_ERROR);
- if (__pyx_1) {
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsasend.pxi":20 */
- __pyx_v_rc = WSAGetLastError();
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsasend.pxi":21 */
- __pyx_1 = (__pyx_v_rc != ERROR_IO_PENDING);
- if (__pyx_1) {
- __pyx_3 = PyInt_FromLong(__pyx_v_rc); if (!__pyx_3) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 22; goto __pyx_L1;}
- __pyx_4 = PyLong_FromUnsignedLong(__pyx_v_bytes); if (!__pyx_4) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 22; goto __pyx_L1;}
- __pyx_5 = PyTuple_New(2); if (!__pyx_5) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 22; goto __pyx_L1;}
- PyTuple_SET_ITEM(__pyx_5, 0, __pyx_3);
- PyTuple_SET_ITEM(__pyx_5, 1, __pyx_4);
- __pyx_3 = 0;
- __pyx_4 = 0;
- __pyx_r = __pyx_5;
- __pyx_5 = 0;
- goto __pyx_L0;
- goto __pyx_L4;
- }
- __pyx_L4:;
- goto __pyx_L3;
- }
- __pyx_L3:;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsasend.pxi":24 */
- Py_XINCREF(__pyx_v_obj);
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsasend.pxi":25 */
- __pyx_3 = PyInt_FromLong(__pyx_v_rc); if (!__pyx_3) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 25; goto __pyx_L1;}
- __pyx_4 = PyLong_FromUnsignedLong(__pyx_v_bytes); if (!__pyx_4) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 25; goto __pyx_L1;}
- __pyx_5 = PyTuple_New(2); if (!__pyx_5) {__pyx_filename = __pyx_f[4]; __pyx_lineno = 25; goto __pyx_L1;}
- PyTuple_SET_ITEM(__pyx_5, 0, __pyx_3);
- PyTuple_SET_ITEM(__pyx_5, 1, __pyx_4);
- __pyx_3 = 0;
- __pyx_4 = 0;
- __pyx_r = __pyx_5;
- __pyx_5 = 0;
- goto __pyx_L0;
-
- __pyx_r = Py_None; Py_INCREF(Py_None);
- goto __pyx_L0;
- __pyx_L1:;
- Py_XDECREF(__pyx_3);
- Py_XDECREF(__pyx_4);
- Py_XDECREF(__pyx_5);
- __Pyx_AddTraceback("iocpsupport.send");
- __pyx_r = 0;
- __pyx_L0:;
- Py_DECREF(__pyx_v_buff);
- Py_DECREF(__pyx_v_obj);
- return __pyx_r;
-}
-
-static __Pyx_InternTabEntry __pyx_intern_tab[] = {
- {&__pyx_n_CreateIoCompletionPort, "CreateIoCompletionPort"},
- {&__pyx_n_Event, "Event"},
- {&__pyx_n_False, "False"},
- {&__pyx_n_MemoryError, "MemoryError"},
- {&__pyx_n_PostQueuedCompletionStatus, "PostQueuedCompletionStatus"},
- {&__pyx_n_ValueError, "ValueError"},
- {&__pyx_n_WindowsError, "WindowsError"},
- {&__pyx_n___init__, "__init__"},
- {&__pyx_n_callback, "callback"},
- {&__pyx_n_getsockopt, "getsockopt"},
- {&__pyx_n_have_connectex, "have_connectex"},
- {&__pyx_n_ignore, "ignore"},
- {&__pyx_n_items, "items"},
- {&__pyx_n_owner, "owner"},
- {&__pyx_n_socket, "socket"},
- {0, 0}
-};
-
-static __Pyx_StringTabEntry __pyx_string_tab[] = {
- {&__pyx_k4p, __pyx_k4, sizeof(__pyx_k4)},
- {&__pyx_k11p, __pyx_k11, sizeof(__pyx_k11)},
- {&__pyx_k14p, __pyx_k14, sizeof(__pyx_k14)},
- {&__pyx_k15p, __pyx_k15, sizeof(__pyx_k15)},
- {0, 0, 0}
-};
-
-static PyObject *__pyx_tp_new_11iocpsupport_CompletionPort(PyTypeObject *t, PyObject *a, PyObject *k) {
- PyObject *o = (*t->tp_alloc)(t, 0);
- if (!o) return 0;
- return o;
-}
-
-static void __pyx_tp_dealloc_11iocpsupport_CompletionPort(PyObject *o) {
- (*o->ob_type->tp_free)(o);
-}
-
-static int __pyx_tp_traverse_11iocpsupport_CompletionPort(PyObject *o, visitproc v, void *a) {
- return 0;
-}
-
-static int __pyx_tp_clear_11iocpsupport_CompletionPort(PyObject *o) {
- return 0;
-}
-
-static struct PyMethodDef __pyx_methods_11iocpsupport_CompletionPort[] = {
- {"addHandle", (PyCFunction)__pyx_f_11iocpsupport_14CompletionPort_addHandle, METH_VARARGS|METH_KEYWORDS, 0},
- {"getEvent", (PyCFunction)__pyx_f_11iocpsupport_14CompletionPort_getEvent, METH_VARARGS|METH_KEYWORDS, 0},
- {"postEvent", (PyCFunction)__pyx_f_11iocpsupport_14CompletionPort_postEvent, METH_VARARGS|METH_KEYWORDS, 0},
- {"__del__", (PyCFunction)__pyx_f_11iocpsupport_14CompletionPort___del__, METH_VARARGS|METH_KEYWORDS, 0},
- {0, 0, 0, 0}
-};
-
-static PyNumberMethods __pyx_tp_as_number_CompletionPort = {
- 0, /*nb_add*/
- 0, /*nb_subtract*/
- 0, /*nb_multiply*/
- 0, /*nb_divide*/
- 0, /*nb_remainder*/
- 0, /*nb_divmod*/
- 0, /*nb_power*/
- 0, /*nb_negative*/
- 0, /*nb_positive*/
- 0, /*nb_absolute*/
- 0, /*nb_nonzero*/
- 0, /*nb_invert*/
- 0, /*nb_lshift*/
- 0, /*nb_rshift*/
- 0, /*nb_and*/
- 0, /*nb_xor*/
- 0, /*nb_or*/
- 0, /*nb_coerce*/
- 0, /*nb_int*/
- 0, /*nb_long*/
- 0, /*nb_float*/
- 0, /*nb_oct*/
- 0, /*nb_hex*/
- 0, /*nb_inplace_add*/
- 0, /*nb_inplace_subtract*/
- 0, /*nb_inplace_multiply*/
- 0, /*nb_inplace_divide*/
- 0, /*nb_inplace_remainder*/
- 0, /*nb_inplace_power*/
- 0, /*nb_inplace_lshift*/
- 0, /*nb_inplace_rshift*/
- 0, /*nb_inplace_and*/
- 0, /*nb_inplace_xor*/
- 0, /*nb_inplace_or*/
- 0, /*nb_floor_divide*/
- 0, /*nb_true_divide*/
- 0, /*nb_inplace_floor_divide*/
- 0, /*nb_inplace_true_divide*/
- #if Py_TPFLAGS_DEFAULT & Py_TPFLAGS_HAVE_INDEX
- 0, /*nb_index*/
- #endif
-};
-
-static PySequenceMethods __pyx_tp_as_sequence_CompletionPort = {
- 0, /*sq_length*/
- 0, /*sq_concat*/
- 0, /*sq_repeat*/
- 0, /*sq_item*/
- 0, /*sq_slice*/
- 0, /*sq_ass_item*/
- 0, /*sq_ass_slice*/
- 0, /*sq_contains*/
- 0, /*sq_inplace_concat*/
- 0, /*sq_inplace_repeat*/
-};
-
-static PyMappingMethods __pyx_tp_as_mapping_CompletionPort = {
- 0, /*mp_length*/
- 0, /*mp_subscript*/
- 0, /*mp_ass_subscript*/
-};
-
-static PyBufferProcs __pyx_tp_as_buffer_CompletionPort = {
- 0, /*bf_getreadbuffer*/
- 0, /*bf_getwritebuffer*/
- 0, /*bf_getsegcount*/
- 0, /*bf_getcharbuffer*/
-};
-
-PyTypeObject __pyx_type_11iocpsupport_CompletionPort = {
- PyObject_HEAD_INIT(0)
- 0, /*ob_size*/
- "iocpsupport.CompletionPort", /*tp_name*/
- sizeof(struct __pyx_obj_11iocpsupport_CompletionPort), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- __pyx_tp_dealloc_11iocpsupport_CompletionPort, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- &__pyx_tp_as_number_CompletionPort, /*tp_as_number*/
- &__pyx_tp_as_sequence_CompletionPort, /*tp_as_sequence*/
- &__pyx_tp_as_mapping_CompletionPort, /*tp_as_mapping*/
- 0, /*tp_hash*/
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- &__pyx_tp_as_buffer_CompletionPort, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/
- 0, /*tp_doc*/
- __pyx_tp_traverse_11iocpsupport_CompletionPort, /*tp_traverse*/
- __pyx_tp_clear_11iocpsupport_CompletionPort, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- __pyx_methods_11iocpsupport_CompletionPort, /*tp_methods*/
- 0, /*tp_members*/
- 0, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- __pyx_f_11iocpsupport_14CompletionPort___init__, /*tp_init*/
- 0, /*tp_alloc*/
- __pyx_tp_new_11iocpsupport_CompletionPort, /*tp_new*/
- 0, /*tp_free*/
- 0, /*tp_is_gc*/
- 0, /*tp_bases*/
- 0, /*tp_mro*/
- 0, /*tp_cache*/
- 0, /*tp_subclasses*/
- 0, /*tp_weaklist*/
-};
-
-static struct PyMethodDef __pyx_methods[] = {
- {"makesockaddr", (PyCFunction)__pyx_f_11iocpsupport_makesockaddr, METH_VARARGS|METH_KEYWORDS, 0},
- {"AllocateReadBuffer", (PyCFunction)__pyx_f_11iocpsupport_AllocateReadBuffer, METH_VARARGS|METH_KEYWORDS, 0},
- {"maxAddrLen", (PyCFunction)__pyx_f_11iocpsupport_maxAddrLen, METH_VARARGS|METH_KEYWORDS, 0},
- {"accept", (PyCFunction)__pyx_f_11iocpsupport_accept, METH_VARARGS|METH_KEYWORDS, 0},
- {"get_accept_addrs", (PyCFunction)__pyx_f_11iocpsupport_get_accept_addrs, METH_VARARGS|METH_KEYWORDS, 0},
- {"connect", (PyCFunction)__pyx_f_11iocpsupport_connect, METH_VARARGS|METH_KEYWORDS, 0},
- {"recv", (PyCFunction)__pyx_f_11iocpsupport_recv, METH_VARARGS|METH_KEYWORDS, 0},
- {"recvfrom", (PyCFunction)__pyx_f_11iocpsupport_recvfrom, METH_VARARGS|METH_KEYWORDS, 0},
- {"send", (PyCFunction)__pyx_f_11iocpsupport_send, METH_VARARGS|METH_KEYWORDS, 0},
- {0, 0, 0, 0}
-};
-
-static void __pyx_init_filenames(void); /*proto*/
-
-PyMODINIT_FUNC initiocpsupport(void); /*proto*/
-PyMODINIT_FUNC initiocpsupport(void) {
- PyObject *__pyx_1 = 0;
- PyObject *__pyx_2 = 0;
- PyObject *__pyx_3 = 0;
- PyObject *__pyx_4 = 0;
- int __pyx_5;
- __pyx_init_filenames();
- __pyx_m = Py_InitModule4("iocpsupport", __pyx_methods, 0, 0, PYTHON_API_VERSION);
- if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 5; goto __pyx_L1;};
- Py_INCREF(__pyx_m);
- __pyx_b = PyImport_AddModule("__builtin__");
- if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 5; goto __pyx_L1;};
- if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 5; goto __pyx_L1;};
- if (__Pyx_InternStrings(__pyx_intern_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 5; goto __pyx_L1;};
- if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 5; goto __pyx_L1;};
- if (PyType_Ready(&__pyx_type_11iocpsupport_CompletionPort) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; goto __pyx_L1;}
- if (PyObject_SetAttrString(__pyx_m, "CompletionPort", (PyObject *)&__pyx_type_11iocpsupport_CompletionPort) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; goto __pyx_L1;}
- __pyx_ptype_11iocpsupport_CompletionPort = &__pyx_type_11iocpsupport_CompletionPort;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":121 */
- __pyx_1 = PyDict_New(); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 121; goto __pyx_L1;}
- __pyx_2 = PyTuple_New(0); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 121; goto __pyx_L1;}
- __pyx_3 = __Pyx_CreateClass(__pyx_2, __pyx_1, __pyx_n_Event, "iocpsupport"); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 121; goto __pyx_L1;}
- Py_DECREF(__pyx_2); __pyx_2 = 0;
- __pyx_2 = PyCFunction_New(&__pyx_mdef_11iocpsupport_5Event___init__, 0); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; goto __pyx_L1;}
- __pyx_4 = PyMethod_New(__pyx_2, 0, __pyx_3); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; goto __pyx_L1;}
- Py_DECREF(__pyx_2); __pyx_2 = 0;
- if (PyObject_SetAttr(__pyx_3, __pyx_n___init__, __pyx_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; goto __pyx_L1;}
- Py_DECREF(__pyx_4); __pyx_4 = 0;
- if (PyObject_SetAttr(__pyx_m, __pyx_n_Event, __pyx_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 121; goto __pyx_L1;}
- Py_DECREF(__pyx_3); __pyx_3 = 0;
- Py_DECREF(__pyx_1); __pyx_1 = 0;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":138 */
- __pyx_k2 = 0;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":240 */
- __pyx_2 = __Pyx_Import(__pyx_n_socket, 0); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 240; goto __pyx_L1;}
- if (PyObject_SetAttr(__pyx_m, __pyx_n_socket, __pyx_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 240; goto __pyx_L1;}
- Py_DECREF(__pyx_2); __pyx_2 = 0;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":241 */
- __pyx_5 = (!initWinsockPointers());
- if (__pyx_5) {
- __pyx_4 = __Pyx_GetName(__pyx_b, __pyx_n_ValueError); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 242; goto __pyx_L1;}
- __Pyx_Raise(__pyx_4, __pyx_k4p, 0);
- Py_DECREF(__pyx_4); __pyx_4 = 0;
- {__pyx_filename = __pyx_f[0]; __pyx_lineno = 242; goto __pyx_L1;}
- goto __pyx_L5;
- }
- __pyx_L5:;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport/iocpsupport.pyx":244 */
- __pyx_3 = PyInt_FromLong((lpConnectEx != NULL)); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 244; goto __pyx_L1;}
- if (PyObject_SetAttr(__pyx_m, __pyx_n_have_connectex, __pyx_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 244; goto __pyx_L1;}
- Py_DECREF(__pyx_3); __pyx_3 = 0;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsarecv.pxi":5 */
- __pyx_k5 = 0;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsarecv.pxi":38 */
- __pyx_k6 = 0;
-
- /* "X:\projects\Twisted\trunk\twisted\internet\iocpreactor\iocpsupport\wsasend.pxi":5 */
- __pyx_k7 = 0;
- return;
- __pyx_L1:;
- Py_XDECREF(__pyx_1);
- Py_XDECREF(__pyx_2);
- Py_XDECREF(__pyx_3);
- Py_XDECREF(__pyx_4);
- __Pyx_AddTraceback("iocpsupport");
-}
-
-static char *__pyx_filenames[] = {
- "iocpsupport.pyx",
- "acceptex.pxi",
- "connectex.pxi",
- "wsarecv.pxi",
- "wsasend.pxi",
-};
-
-/* Runtime support code */
-
-static void __pyx_init_filenames(void) {
- __pyx_f = __pyx_filenames;
-}
-
-static PyObject *__Pyx_CreateClass(
- PyObject *bases, PyObject *dict, PyObject *name, char *modname)
-{
- PyObject *py_modname;
- PyObject *result = 0;
-
- py_modname = PyString_FromString(modname);
- if (!py_modname)
- goto bad;
- if (PyDict_SetItemString(dict, "__module__", py_modname) < 0)
- goto bad;
- result = PyClass_New(bases, dict, name);
-bad:
- Py_XDECREF(py_modname);
- return result;
-}
-
-static int __Pyx_GetStarArgs(
- PyObject **args,
- PyObject **kwds,
- char *kwd_list[],
- Py_ssize_t nargs,
- PyObject **args2,
- PyObject **kwds2,
- char rqd_kwds[])
-{
- PyObject *x = 0, *args1 = 0, *kwds1 = 0;
- int i;
- char **p;
-
- if (args2)
- *args2 = 0;
- if (kwds2)
- *kwds2 = 0;
-
- if (args2) {
- args1 = PyTuple_GetSlice(*args, 0, nargs);
- if (!args1)
- goto bad;
- *args2 = PyTuple_GetSlice(*args, nargs, PyTuple_GET_SIZE(*args));
- if (!*args2)
- goto bad;
- }
- else if (PyTuple_GET_SIZE(*args) > nargs) {
- int m = nargs;
- int n = PyTuple_GET_SIZE(*args);
- PyErr_Format(PyExc_TypeError,
- "function takes at most %d positional arguments (%d given)",
- m, n);
- goto bad;
- }
- else {
- args1 = *args;
- Py_INCREF(args1);
- }
-
- if (rqd_kwds && !*kwds)
- for (i = 0, p = kwd_list; *p; i++, p++)
- if (rqd_kwds[i])
- goto missing_kwarg;
-
- if (kwds2) {
- if (*kwds) {
- kwds1 = PyDict_New();
- if (!kwds1)
- goto bad;
- *kwds2 = PyDict_Copy(*kwds);
- if (!*kwds2)
- goto bad;
- for (i = 0, p = kwd_list; *p; i++, p++) {
- x = PyDict_GetItemString(*kwds, *p);
- if (x) {
- if (PyDict_SetItemString(kwds1, *p, x) < 0)
- goto bad;
- if (PyDict_DelItemString(*kwds2, *p) < 0)
- goto bad;
- }
- else if (rqd_kwds && rqd_kwds[i])
- goto missing_kwarg;
- }
- }
- else {
- *kwds2 = PyDict_New();
- if (!*kwds2)
- goto bad;
- }
- }
- else {
- kwds1 = *kwds;
- Py_XINCREF(kwds1);
- if (rqd_kwds && *kwds)
- for (i = 0, p = kwd_list; *p; i++, p++)
- if (rqd_kwds[i] && !PyDict_GetItemString(*kwds, *p))
- goto missing_kwarg;
- }
-
- *args = args1;
- *kwds = kwds1;
- return 0;
-missing_kwarg:
- PyErr_Format(PyExc_TypeError,
- "required keyword argument '%s' is missing", *p);
-bad:
- Py_XDECREF(args1);
- Py_XDECREF(kwds1);
- if (args2) {
- Py_XDECREF(*args2);
- }
- if (kwds2) {
- Py_XDECREF(*kwds2);
- }
- return -1;
-}
-
-static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list) {
- PyObject *__import__ = 0;
- PyObject *empty_list = 0;
- PyObject *module = 0;
- PyObject *global_dict = 0;
- PyObject *empty_dict = 0;
- PyObject *list;
- __import__ = PyObject_GetAttrString(__pyx_b, "__import__");
- if (!__import__)
- goto bad;
- if (from_list)
- list = from_list;
- else {
- empty_list = PyList_New(0);
- if (!empty_list)
- goto bad;
- list = empty_list;
- }
- global_dict = PyModule_GetDict(__pyx_m);
- if (!global_dict)
- goto bad;
- empty_dict = PyDict_New();
- if (!empty_dict)
- goto bad;
- module = PyObject_CallFunction(__import__, "OOOO",
- name, global_dict, empty_dict, list);
-bad:
- Py_XDECREF(empty_list);
- Py_XDECREF(__import__);
- Py_XDECREF(empty_dict);
- return module;
-}
-
-static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) {
- PyObject *result;
- result = PyObject_GetAttr(dict, name);
- if (!result)
- PyErr_SetObject(PyExc_NameError, name);
- return result;
-}
-
-static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb) {
- Py_XINCREF(type);
- Py_XINCREF(value);
- Py_XINCREF(tb);
- /* First, check the traceback argument, replacing None with NULL. */
- if (tb == Py_None) {
- Py_DECREF(tb);
- tb = 0;
- }
- else if (tb != NULL && !PyTraceBack_Check(tb)) {
- PyErr_SetString(PyExc_TypeError,
- "raise: arg 3 must be a traceback or None");
- goto raise_error;
- }
- /* Next, replace a missing value with None */
- if (value == NULL) {
- value = Py_None;
- Py_INCREF(value);
- }
- #if PY_VERSION_HEX < 0x02050000
- if (!PyClass_Check(type))
- #else
- if (!PyType_Check(type))
- #endif
- {
- /* Raising an instance. The value should be a dummy. */
- if (value != Py_None) {
- PyErr_SetString(PyExc_TypeError,
- "instance exception may not have a separate value");
- goto raise_error;
- }
- /* Normalize to raise <class>, <instance> */
- Py_DECREF(value);
- value = type;
- #if PY_VERSION_HEX < 0x02050000
- if (PyInstance_Check(type)) {
- type = (PyObject*) ((PyInstanceObject*)type)->in_class;
- Py_INCREF(type);
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "raise: exception must be an old-style class or instance");
- goto raise_error;
- }
- #else
- type = (PyObject*) type->ob_type;
- Py_INCREF(type);
- if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) {
- PyErr_SetString(PyExc_TypeError,
- "raise: exception class must be a subclass of BaseException");
- goto raise_error;
- }
- #endif
- }
- PyErr_Restore(type, value, tb);
- return;
-raise_error:
- Py_XDECREF(value);
- Py_XDECREF(type);
- Py_XDECREF(tb);
- return;
-}
-
-static void __Pyx_UnpackError(void) {
- PyErr_SetString(PyExc_ValueError, "unpack sequence of wrong size");
-}
-
-static PyObject *__Pyx_UnpackItem(PyObject *iter) {
- PyObject *item;
- if (!(item = PyIter_Next(iter))) {
- if (!PyErr_Occurred())
- __Pyx_UnpackError();
- }
- return item;
-}
-
-static int __Pyx_EndUnpack(PyObject *iter) {
- PyObject *item;
- if ((item = PyIter_Next(iter))) {
- Py_DECREF(item);
- __Pyx_UnpackError();
- return -1;
- }
- else if (!PyErr_Occurred())
- return 0;
- else
- return -1;
-}
-
-static int __Pyx_InternStrings(__Pyx_InternTabEntry *t) {
- while (t->p) {
- *t->p = PyString_InternFromString(t->s);
- if (!*t->p)
- return -1;
- ++t;
- }
- return 0;
-}
-
-static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) {
- while (t->p) {
- *t->p = PyString_FromStringAndSize(t->s, t->n - 1);
- if (!*t->p)
- return -1;
- ++t;
- }
- return 0;
-}
-
-#include "compile.h"
-#include "frameobject.h"
-#include "traceback.h"
-
-static void __Pyx_AddTraceback(char *funcname) {
- PyObject *py_srcfile = 0;
- PyObject *py_funcname = 0;
- PyObject *py_globals = 0;
- PyObject *empty_tuple = 0;
- PyObject *empty_string = 0;
- PyCodeObject *py_code = 0;
- PyFrameObject *py_frame = 0;
-
- py_srcfile = PyString_FromString(__pyx_filename);
- if (!py_srcfile) goto bad;
- py_funcname = PyString_FromString(funcname);
- if (!py_funcname) goto bad;
- py_globals = PyModule_GetDict(__pyx_m);
- if (!py_globals) goto bad;
- empty_tuple = PyTuple_New(0);
- if (!empty_tuple) goto bad;
- empty_string = PyString_FromString("");
- if (!empty_string) goto bad;
- py_code = PyCode_New(
- 0, /*int argcount,*/
- 0, /*int nlocals,*/
- 0, /*int stacksize,*/
- 0, /*int flags,*/
- empty_string, /*PyObject *code,*/
- empty_tuple, /*PyObject *consts,*/
- empty_tuple, /*PyObject *names,*/
- empty_tuple, /*PyObject *varnames,*/
- empty_tuple, /*PyObject *freevars,*/
- empty_tuple, /*PyObject *cellvars,*/
- py_srcfile, /*PyObject *filename,*/
- py_funcname, /*PyObject *name,*/
- __pyx_lineno, /*int firstlineno,*/
- empty_string /*PyObject *lnotab*/
- );
- if (!py_code) goto bad;
- py_frame = PyFrame_New(
- PyThreadState_Get(), /*PyThreadState *tstate,*/
- py_code, /*PyCodeObject *code,*/
- py_globals, /*PyObject *globals,*/
- 0 /*PyObject *locals*/
- );
- if (!py_frame) goto bad;
- py_frame->f_lineno = __pyx_lineno;
- PyTraceBack_Here(py_frame);
-bad:
- Py_XDECREF(py_srcfile);
- Py_XDECREF(py_funcname);
- Py_XDECREF(empty_tuple);
- Py_XDECREF(empty_string);
- Py_XDECREF(py_code);
- Py_XDECREF(py_frame);
-}
diff --git a/tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/iocpsupport.pyx b/tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/iocpsupport.pyx
deleted file mode 100644
index 85f8c47..0000000
--- a/tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/iocpsupport.pyx
+++ /dev/null
@@ -1,250 +0,0 @@
-# Copyright (c) 2008 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-ctypedef int size_t
-ctypedef unsigned long HANDLE
-ctypedef unsigned long SOCKET
-ctypedef unsigned long DWORD
-ctypedef unsigned long ULONG_PTR
-ctypedef int BOOL
-
-cdef extern from 'io.h':
- long _get_osfhandle(int filehandle)
-
-cdef extern from 'errno.h':
- int errno
- enum:
- EBADF
-
-cdef extern from 'winsock2.h':
- pass
-
-cdef extern from 'windows.h':
- ctypedef struct OVERLAPPED:
- pass
- HANDLE CreateIoCompletionPort(HANDLE fileHandle, HANDLE existing, ULONG_PTR key, DWORD numThreads)
- BOOL GetQueuedCompletionStatus(HANDLE port, DWORD *bytes, ULONG_PTR *key, OVERLAPPED **ov, DWORD timeout)
- BOOL PostQueuedCompletionStatus(HANDLE port, DWORD bytes, ULONG_PTR key, OVERLAPPED *ov)
- DWORD GetLastError()
- BOOL CloseHandle(HANDLE h)
- enum:
- INVALID_HANDLE_VALUE
- void DebugBreak()
-
-cdef extern from 'python.h':
- struct PyObject:
- pass
- void *PyMem_Malloc(size_t n) except NULL
- void PyMem_Free(void *p)
- struct PyThreadState:
- pass
- PyThreadState *PyEval_SaveThread()
- void PyEval_RestoreThread(PyThreadState *tstate)
- void Py_INCREF(object o)
- void Py_XINCREF(object o)
- void Py_DECREF(object o)
- void Py_XDECREF(object o)
- int PyObject_AsWriteBuffer(object obj, void **buffer, int *buffer_len) except -1
- int PyObject_AsReadBuffer(object obj, void **buffer, int *buffer_len) except -1
- object PyString_FromString(char *v)
- object PyString_FromStringAndSize(char *v, int len)
- object PyBuffer_New(int size)
- char *PyString_AsString(object obj) except NULL
- object PySequence_Fast(object o, char *m)
-# object PySequence_Fast_GET_ITEM(object o, int i)
- PyObject** PySequence_Fast_ITEMS(object o)
- PyObject* PySequence_ITEM( PyObject *o, int i)
- int PySequence_Fast_GET_SIZE(object o)
-
-cdef extern from '':
- struct sockaddr:
- int sa_family
- char sa_data[0]
- cdef struct in_addr:
- unsigned long s_addr
- struct sockaddr_in:
- int sin_port
- in_addr sin_addr
- int getsockopt(SOCKET s, int level, int optname, char *optval, int *optlen)
- enum:
- SOL_SOCKET
- SO_PROTOCOL_INFO
- SOCKET_ERROR
- ERROR_IO_PENDING
- AF_INET
- INADDR_ANY
- ctypedef struct WSAPROTOCOL_INFO:
- int iMaxSockAddr
- int iAddressFamily
- int WSAGetLastError()
- char *inet_ntoa(in_addr ina)
- unsigned long inet_addr(char *cp)
- short ntohs(short netshort)
- short htons(short hostshort)
- ctypedef struct WSABUF:
- long len
- char *buf
-# cdef struct TRANSMIT_FILE_BUFFERS:
-# pass
- int WSARecv(SOCKET s, WSABUF *buffs, DWORD buffcount, DWORD *bytes, DWORD *flags, OVERLAPPED *ov, void *crud)
- int WSARecvFrom(SOCKET s, WSABUF *buffs, DWORD buffcount, DWORD *bytes, DWORD *flags, sockaddr *fromaddr, int *fromlen, OVERLAPPED *ov, void *crud)
- int WSASend(SOCKET s, WSABUF *buffs, DWORD buffcount, DWORD *bytes, DWORD flags, OVERLAPPED *ov, void *crud)
-
-cdef extern from 'string.h':
- void *memset(void *s, int c, size_t n)
-
-cdef extern from 'winsock_pointers.h':
- int initWinsockPointers()
- BOOL (*lpAcceptEx)(SOCKET listening, SOCKET accepting, void *buffer, DWORD recvlen, DWORD locallen, DWORD remotelen, DWORD *bytes, OVERLAPPED *ov)
- void (*lpGetAcceptExSockaddrs)(void *buffer, DWORD recvlen, DWORD locallen, DWORD remotelen, sockaddr **localaddr, int *locallen, sockaddr **remoteaddr, int *remotelen)
- BOOL (*lpConnectEx)(SOCKET s, sockaddr *name, int namelen, void *buff, DWORD sendlen, DWORD *sentlen, OVERLAPPED *ov)
-# BOOL (*lpTransmitFile)(SOCKET s, HANDLE hFile, DWORD size, DWORD buffer_size, OVERLAPPED *ov, TRANSMIT_FILE_BUFFERS *buff, DWORD flags)
-
-cdef struct myOVERLAPPED:
- OVERLAPPED ov
- PyObject *obj
-
-cdef myOVERLAPPED *makeOV() except NULL:
- cdef myOVERLAPPED *res
- res = <myOVERLAPPED *>PyMem_Malloc(sizeof(myOVERLAPPED))
- if not res:
- raise MemoryError
- memset(res, 0, sizeof(myOVERLAPPED))
- return res
-
-cdef void raise_error(int err, object message) except *:
- if not err:
- err = GetLastError()
- raise WindowsError(message, err)
-
-class Event:
- def __init__(self, callback, owner, **kw):
- self.callback = callback
- self.owner = owner
- self.ignore = False
- for k, v in kw.items():
- setattr(self, k, v)
-
-cdef class CompletionPort:
- cdef HANDLE port
- def __init__(self):
- cdef HANDLE res
- res = CreateIoCompletionPort(INVALID_HANDLE_VALUE, 0, 0, 0)
- if not res:
- raise_error(0, 'CreateIoCompletionPort')
- self.port = res
-
- def addHandle(self, long handle, long key=0):
- cdef HANDLE res
- res = CreateIoCompletionPort(handle, self.port, key, 0)
- if not res:
- raise_error(0, 'CreateIoCompletionPort')
-
- def getEvent(self, long timeout):
- cdef PyThreadState *_save
- cdef unsigned long bytes, key, rc
- cdef myOVERLAPPED *ov
-
- _save = PyEval_SaveThread()
- rc = GetQueuedCompletionStatus(self.port, &bytes, &key, <OVERLAPPED **>&ov, timeout)
- PyEval_RestoreThread(_save)
-
- if not rc:
- rc = GetLastError()
- else:
- rc = 0
-
- obj = None
- if ov:
- if ov.obj:
- obj = <object>ov.obj
- Py_DECREF(obj) # we are stealing a reference here
- PyMem_Free(ov)
-
- return (rc, bytes, key, obj)
-
- def postEvent(self, unsigned long bytes, unsigned long key, obj):
- cdef myOVERLAPPED *ov
- cdef unsigned long rc
-
- if obj is not None:
- ov = makeOV()
- Py_INCREF(obj) # give ov its own reference to obj
- ov.obj = <PyObject *>obj
- else:
- ov = NULL
-
- rc = PostQueuedCompletionStatus(self.port, bytes, key, <OVERLAPPED *>ov)
- if not rc:
- raise_error(0, 'PostQueuedCompletionStatus')
-
- def __del__(self):
- CloseHandle(self.port)
-
-def makesockaddr(object buff):
- cdef void *mem_buffer
- cdef int size
-
- PyObject_AsReadBuffer(buff, &mem_buffer, &size)
- # XXX: this should really return the address family as well
- return _makesockaddr(<sockaddr *>mem_buffer, size)
-
-cdef object _makesockaddr(sockaddr *addr, int len):
- cdef sockaddr_in *sin
- if not len:
- return None
- if addr.sa_family == AF_INET:
- sin = <sockaddr_in *>addr
- return PyString_FromString(inet_ntoa(sin.sin_addr)), ntohs(sin.sin_port)
- else:
- return PyString_FromStringAndSize(addr.sa_data, sizeof(addr.sa_data))
-
-cdef object fillinetaddr(sockaddr_in *dest, object addr):
- cdef short port
- cdef unsigned long res
- cdef char *hoststr
- host, port = addr
-
- hoststr = PyString_AsString(host)
- res = inet_addr(hoststr)
- if res == INADDR_ANY:
- raise ValueError, 'invalid IP address'
- dest.sin_addr.s_addr = res
-
- dest.sin_port = htons(port)
-
-def AllocateReadBuffer(int size):
- return PyBuffer_New(size)
-
-def maxAddrLen(long s):
- cdef WSAPROTOCOL_INFO wsa_pi
- cdef int size, rc
-
- size = sizeof(wsa_pi)
- rc = getsockopt(s, SOL_SOCKET, SO_PROTOCOL_INFO, <char *>&wsa_pi, &size)
- if rc == SOCKET_ERROR:
- raise_error(WSAGetLastError(), 'getsockopt')
- return wsa_pi.iMaxSockAddr
-
-cdef int getAddrFamily(SOCKET s) except *:
- cdef WSAPROTOCOL_INFO wsa_pi
- cdef int size, rc
-
- size = sizeof(wsa_pi)
- rc = getsockopt(s, SOL_SOCKET, SO_PROTOCOL_INFO, <char *>&wsa_pi, &size)
- if rc == SOCKET_ERROR:
- raise_error(WSAGetLastError(), 'getsockopt')
- return wsa_pi.iAddressFamily
-
-import socket # for WSAStartup
-if not initWinsockPointers():
- raise ValueError, 'Failed to initialize Winsock function vectors'
-
-have_connectex = (lpConnectEx != NULL)
-
-include 'acceptex.pxi'
-include 'connectex.pxi'
-include 'wsarecv.pxi'
-include 'wsasend.pxi'
-
diff --git a/tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/winsock_pointers.c b/tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/winsock_pointers.c
deleted file mode 100644
index 9bd115a..0000000
--- a/tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/winsock_pointers.c
+++ /dev/null
@@ -1,62 +0,0 @@
-/* Copyright (c) 2008 Twisted Matrix Laboratories.
- * See LICENSE for details.
- */
-
-
-#include<winsock2.h>
-#include<assert.h>
-#include<stdio.h>
-#include<stdlib.h>
-
-#ifndef WSAID_CONNECTEX
-#define WSAID_CONNECTEX {0x25a207b9,0xddf3,0x4660,{0x8e,0xe9,0x76,0xe5,0x8c,0x74,0x06,0x3e}}
-#endif
-#ifndef WSAID_GETACCEPTEXSOCKADDRS
-#define WSAID_GETACCEPTEXSOCKADDRS {0xb5367df2,0xcbac,0x11cf,{0x95,0xca,0x00,0x80,0x5f,0x48,0xa1,0x92}}
-#endif
-#ifndef WSAID_ACCEPTEX
-#define WSAID_ACCEPTEX {0xb5367df1,0xcbac,0x11cf,{0x95,0xca,0x00,0x80,0x5f,0x48,0xa1,0x92}}
-#endif
-/*#ifndef WSAID_TRANSMITFILE
-#define WSAID_TRANSMITFILE {0xb5367df0,0xcbac,0x11cf,{0x95,0xca,0x00,0x80,0x5f,0x48,0xa1,0x92}}
-#endif*/
-
-
-void *lpAcceptEx, *lpGetAcceptExSockaddrs, *lpConnectEx, *lpTransmitFile;
-
-int initPointer(SOCKET s, void **fun, GUID guid) {
- int res;
- DWORD bytes;
-
- *fun = NULL;
- res = WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER,
- &guid, sizeof(guid),
- fun, sizeof(fun),
- &bytes, NULL, NULL);
- return !res;
-}
-
-int initWinsockPointers() {
- SOCKET s = socket(AF_INET, SOCK_STREAM, 0);
- /* I hate C */
- GUID guid1 = WSAID_ACCEPTEX;
- GUID guid2 = WSAID_GETACCEPTEXSOCKADDRS;
- GUID guid3 = WSAID_CONNECTEX;
- /*GUID guid4 = WSAID_TRANSMITFILE;*/
- if (!s) {
- return 0;
- }
- if (!initPointer(s, &lpAcceptEx, guid1))
- {
- return 0;
- }
- if (!initPointer(s, &lpGetAcceptExSockaddrs, guid2)) {
- return 0;
- }
- if (!initPointer(s, &lpConnectEx, guid3)) {
- return 0;
- };
- /*initPointer(s, &lpTransmitFile, guid4);*/
- return 1;
-}
-
diff --git a/tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/winsock_pointers.h b/tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/winsock_pointers.h
deleted file mode 100644
index 83e9ba8..0000000
--- a/tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/winsock_pointers.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/* Copyright (c) 2008 Twisted Matrix Laboratories.
- * See LICENSE for details.
- */
-
-
-#include<windows.h>
-
-int initWinsockPointers();
-BOOL
-(PASCAL FAR * lpAcceptEx)(
- IN SOCKET sListenSocket,
- IN SOCKET sAcceptSocket,
- IN PVOID lpOutputBuffer,
- IN DWORD dwReceiveDataLength,
- IN DWORD dwLocalAddressLength,
- IN DWORD dwRemoteAddressLength,
- OUT LPDWORD lpdwBytesReceived,
- IN LPOVERLAPPED lpOverlapped
- );
-VOID
-(PASCAL FAR * lpGetAcceptExSockaddrs)(
- IN PVOID lpOutputBuffer,
- IN DWORD dwReceiveDataLength,
- IN DWORD dwLocalAddressLength,
- IN DWORD dwRemoteAddressLength,
- OUT struct sockaddr **LocalSockaddr,
- OUT LPINT LocalSockaddrLength,
- OUT struct sockaddr **RemoteSockaddr,
- OUT LPINT RemoteSockaddrLength
- );
-BOOL
-(PASCAL FAR * lpConnectEx) (
- IN SOCKET s,
- IN const struct sockaddr FAR *name,
- IN int namelen,
- IN PVOID lpSendBuffer OPTIONAL,
- IN DWORD dwSendDataLength,
- OUT LPDWORD lpdwBytesSent,
- IN LPOVERLAPPED lpOverlapped
- );
-/*BOOL
-(PASCAL FAR * lpTransmitFile)(
- IN SOCKET hSocket,
- IN HANDLE hFile,
- IN DWORD nNumberOfBytesToWrite,
- IN DWORD nNumberOfBytesPerSend,
- IN LPOVERLAPPED lpOverlapped,
- IN LPTRANSMIT_FILE_BUFFERS lpTransmitBuffers,
- IN DWORD dwReserved
- );*/
-
diff --git a/tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/wsarecv.pxi b/tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/wsarecv.pxi
deleted file mode 100644
index afb1906..0000000
--- a/tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/wsarecv.pxi
+++ /dev/null
@@ -1,61 +0,0 @@
-# Copyright (c) 2008 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-def recv(long s, object bufflist, object obj, unsigned long flags = 0):
- cdef int rc, buffcount, i, res
- cdef myOVERLAPPED *ov
- cdef WSABUF *ws_buf
- cdef unsigned long bytes
- cdef PyObject **buffers
-
- bufflist = PySequence_Fast(bufflist, 'second argument needs to be a list')
- buffcount = PySequence_Fast_GET_SIZE(bufflist)
- buffers = PySequence_Fast_ITEMS(bufflist)
-
- ws_buf = <WSABUF *>PyMem_Malloc(buffcount*sizeof(WSABUF))
-
- try:
- for i from 0 <= i < buffcount:
- PyObject_AsWriteBuffer(<object>buffers[i], <void **>&ws_buf[i].buf, <int *>&ws_buf[i].len)
-
- ov = makeOV()
- if obj is not None:
- ov.obj = <PyObject *>obj
-
- rc = WSARecv(s, ws_buf, buffcount, &bytes, &flags, <OVERLAPPED *>ov, NULL)
-
- if rc == SOCKET_ERROR:
- rc = WSAGetLastError()
- if rc != ERROR_IO_PENDING:
- return rc, 0
-
- Py_XINCREF(obj)
- return rc, bytes
- finally:
- PyMem_Free(ws_buf)
-
-def recvfrom(long s, object buff, object addr_buff, object obj, unsigned long flags = 0):
- cdef int rc, fromlen
- cdef myOVERLAPPED *ov
- cdef WSABUF ws_buf
- cdef unsigned long bytes
- cdef sockaddr *fromaddr
-
- PyObject_AsWriteBuffer(buff, <void **>&ws_buf.buf, <int *>&ws_buf.len)
- PyObject_AsWriteBuffer(addr_buff, <void **>&fromaddr, &fromlen)
-
- ov = makeOV()
- if obj is not None:
- ov.obj = <PyObject *>obj
-
- rc = WSARecvFrom(s, &ws_buf, 1, &bytes, &flags, fromaddr, &fromlen, <OVERLAPPED *>ov, NULL)
-
- if rc == SOCKET_ERROR:
- rc = WSAGetLastError()
- if rc != ERROR_IO_PENDING:
- return rc, 0
-
- Py_XINCREF(obj)
- return rc, bytes
-
diff --git a/tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/wsasend.pxi b/tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/wsasend.pxi
deleted file mode 100644
index 03c44ad..0000000
--- a/tools/buildbot/pylibs/twisted/internet/iocpreactor/iocpsupport/wsasend.pxi
+++ /dev/null
@@ -1,27 +0,0 @@
-# Copyright (c) 2008 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-def send(long s, object buff, object obj, unsigned long flags = 0):
- cdef int rc
- cdef myOVERLAPPED *ov
- cdef WSABUF ws_buf
- cdef unsigned long bytes
-
- PyObject_AsReadBuffer(buff, <void **>&ws_buf.buf, <int *>&ws_buf.len)
-
- ov = makeOV()
- if obj is not None:
- ov.obj = <PyObject *>obj
-
- rc = WSASend(s, &ws_buf, 1, &bytes, flags, <OVERLAPPED *>ov, NULL)
-
- if rc == SOCKET_ERROR:
- rc = WSAGetLastError()
- if rc != ERROR_IO_PENDING:
- return rc, bytes
-
- Py_XINCREF(obj)
- return rc, bytes
-
-
diff --git a/tools/buildbot/pylibs/twisted/internet/iocpreactor/notes.txt b/tools/buildbot/pylibs/twisted/internet/iocpreactor/notes.txt
deleted file mode 100644
index 4caffb8..0000000
--- a/tools/buildbot/pylibs/twisted/internet/iocpreactor/notes.txt
+++ /dev/null
@@ -1,24 +0,0 @@
-test specifically:
-failed accept error message -- similar to test_tcp_internals
-immediate success on accept/connect/recv, including Event.ignore
-parametrize iocpsupport somehow -- via reactor?
-
-do:
-break handling -- WaitForSingleObject on the IOCP handle?
-iovecs for write buffer
-do not wait for a mainloop iteration if resumeProducing (in _handleWrite) does startWriting
-don't addActiveHandle in every call to startWriting/startReading
-iocpified process support
- win32er-in-a-thread (or run GQCS in a thread -- it can't receive SIGBREAK)
-blocking in sendto() -- I think Windows can do that, especially with local UDP
-
-buildbot:
-run in vmware
-start from a persistent snapshot
-
-use a stub inside the vm to svnup/run tests/collect stdio
-lift logs through SMB? or ship them via tcp beams to the VM host
-
-have a timeout on the test run
-if we time out, take a screenshot, save it, kill the VM
-
diff --git a/tools/buildbot/pylibs/twisted/internet/iocpreactor/reactor.py b/tools/buildbot/pylibs/twisted/internet/iocpreactor/reactor.py
deleted file mode 100644
index 08c4a36..0000000
--- a/tools/buildbot/pylibs/twisted/internet/iocpreactor/reactor.py
+++ /dev/null
@@ -1,211 +0,0 @@
-# -*- test-case-name: twisted.internet.test.test_iocp -*-
-
-# Copyright (c) 2008 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-Reactor that uses IO completion ports
-"""
-
-
-from twisted.internet import base, interfaces, main, error
-from twisted.python import log, failure
-from twisted.internet._dumbwin32proc import Process
-
-from zope.interface import implements
-import socket, sys
-
-from twisted.internet.iocpreactor import iocpsupport as _iocp
-from twisted.internet.iocpreactor.const import WAIT_TIMEOUT
-from twisted.internet.iocpreactor import tcp, udp
-
-from twisted.python.compat import set
-
-MAX_TIMEOUT = 2000 # 2 seconds, see doIteration for explanation
-
-EVENTS_PER_LOOP = 1000 # XXX: what's a good value here?
-
-# keys to associate with normal and waker events
-KEY_NORMAL, KEY_WAKEUP = range(2)
-
-_NO_GETHANDLE = error.ConnectionFdescWentAway(
- 'Handler has no getFileHandle method')
-_NO_FILEDESC = error.ConnectionFdescWentAway('Filedescriptor went away')
-
-
-
-class IOCPReactor(base._SignalReactorMixin, base.ReactorBase):
- implements(interfaces.IReactorTCP, interfaces.IReactorUDP,
- interfaces.IReactorMulticast, interfaces.IReactorProcess)
-
- port = None
-
- def __init__(self):
- base.ReactorBase.__init__(self)
- self.port = _iocp.CompletionPort()
- self.handles = set()
-
-
- def addActiveHandle(self, handle):
- self.handles.add(handle)
-
-
- def removeActiveHandle(self, handle):
- self.handles.discard(handle)
-
-
- def doIteration(self, timeout):
- # This function sits and waits for an IO completion event.
- #
- # There are two requirements: process IO events as soon as they arrive
- # and process ctrl-break from the user in a reasonable amount of time.
- #
- # There are three kinds of waiting.
- # 1) GetQueuedCompletionStatus (self.port.getEvent) to wait for IO
- # events only.
- # 2) Msg* family of wait functions that can stop waiting when
- # ctrl-break is detected (then, I think, Python converts it into a
- # KeyboardInterrupt)
- # 3) *Ex family of wait functions that put the thread into an
- # "alertable" wait state which is supposedly triggered by IO completion
- #
- # 2) and 3) can be combined. Trouble is, my IO completion is not
- # causing 3) to trigger, possibly because I do not use an IO completion
- # callback. Windows is weird.
- # There are two ways to handle this. I could use MsgWaitForSingleObject
- # here and GetQueuedCompletionStatus in a thread. Or I could poll with
- # a reasonable interval. Guess what! Threads are hard.
-
- processed_events = 0
- if timeout is None:
- timeout = MAX_TIMEOUT
- else:
- timeout = min(MAX_TIMEOUT, int(1000*timeout))
- rc, bytes, key, evt = self.port.getEvent(timeout)
- while processed_events < EVENTS_PER_LOOP:
- if rc == WAIT_TIMEOUT:
- break
- if key != KEY_WAKEUP:
- assert key == KEY_NORMAL
- if not evt.ignore:
- log.callWithLogger(evt.owner, self._callEventCallback,
- rc, bytes, evt)
- processed_events += 1
- rc, bytes, key, evt = self.port.getEvent(0)
-
-
- def _callEventCallback(self, rc, bytes, evt):
- owner = evt.owner
- why = None
- try:
- evt.callback(rc, bytes, evt)
- handfn = getattr(owner, 'getFileHandle', None)
- if not handfn:
- why = _NO_GETHANDLE
- elif handfn() == -1:
- why = _NO_FILEDESC
- if why:
- return # ignore handles that were closed
- except:
- why = sys.exc_info()[1]
- log.err()
- if why:
- owner.loseConnection(failure.Failure(why))
-
-
- def installWaker(self):
- pass
-
-
- def wakeUp(self):
- self.port.postEvent(0, KEY_WAKEUP, None)
-
-
- def registerHandle(self, handle):
- self.port.addHandle(handle, KEY_NORMAL)
-
-
- def createSocket(self, af, stype):
- skt = socket.socket(af, stype)
- self.registerHandle(skt.fileno())
- return skt
-
-
- def listenTCP(self, port, factory, backlog=50, interface=''):
- """
- @see: twisted.internet.interfaces.IReactorTCP.listenTCP
- """
- p = tcp.Port(port, factory, backlog, interface, self)
- p.startListening()
- return p
-
-
- def connectTCP(self, host, port, factory, timeout=30, bindAddress=None):
- """
- @see: twisted.internet.interfaces.IReactorTCP.connectTCP
- """
- c = tcp.Connector(host, port, factory, timeout, bindAddress, self)
- c.connect()
- return c
-
-
- def listenUDP(self, port, protocol, interface='', maxPacketSize=8192):
- """
- Connects a given L{DatagramProtocol} to the given numeric UDP port.
-
- @returns: object conforming to L{IListeningPort}.
- """
- p = udp.Port(port, protocol, interface, maxPacketSize, self)
- p.startListening()
- return p
-
-
- def listenMulticast(self, port, protocol, interface='', maxPacketSize=8192,
- listenMultiple=False):
- """
- Connects a given DatagramProtocol to the given numeric UDP port.
-
- EXPERIMENTAL.
-
- @returns: object conforming to IListeningPort.
- """
- p = udp.MulticastPort(port, protocol, interface, maxPacketSize, self,
- listenMultiple)
- p.startListening()
- return p
-
-
- def spawnProcess(self, processProtocol, executable, args=(), env={},
- path=None, uid=None, gid=None, usePTY=0, childFDs=None):
- """
- 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.")
- if childFDs is not None:
- raise ValueError(
- "Custom child file descriptor mappings are unsupported on "
- "this platform.")
- args, env = self._checkProcessArgs(args, env)
- return Process(self, processProtocol, executable, args, env, path)
-
-
- def removeAll(self):
- res = list(self.handles)
- self.handles.clear()
- return res
-
-
-
-def install():
- r = IOCPReactor()
- main.installReactor(r)
-
-
-__all__ = ['IOCPReactor', 'install']
-
diff --git a/tools/buildbot/pylibs/twisted/internet/iocpreactor/setup.py b/tools/buildbot/pylibs/twisted/internet/iocpreactor/setup.py
deleted file mode 100644
index 6a70d55..0000000
--- a/tools/buildbot/pylibs/twisted/internet/iocpreactor/setup.py
+++ /dev/null
@@ -1,23 +0,0 @@
-# Copyright (c) 2008 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-Distutils file for building low-level IOCP bindings from their Pyrex source
-"""
-
-
-from distutils.core import setup
-from distutils.extension import Extension
-from Pyrex.Distutils import build_ext
-
-setup(name='iocpsupport',
- ext_modules=[Extension('iocpsupport',
- ['iocpsupport/iocpsupport.pyx',
- 'iocpsupport/winsock_pointers.c'],
- libraries = ['ws2_32'],
- )
- ],
- cmdclass = {'build_ext': build_ext},
- )
-
diff --git a/tools/buildbot/pylibs/twisted/internet/iocpreactor/tcp.py b/tools/buildbot/pylibs/twisted/internet/iocpreactor/tcp.py
deleted file mode 100644
index 2300bef..0000000
--- a/tools/buildbot/pylibs/twisted/internet/iocpreactor/tcp.py
+++ /dev/null
@@ -1,497 +0,0 @@
-# Copyright (c) 2008 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-TCP support for IOCP reactor
-"""
-
-from twisted.internet import interfaces, error, address, main, defer
-from twisted.internet.abstract import isIPAddress
-from twisted.internet.tcp import _SocketCloser, Connector as TCPConnector
-from twisted.persisted import styles
-from twisted.python import log, failure, reflect, util
-
-from zope.interface import implements
-import socket, operator, errno, struct
-
-from twisted.internet.iocpreactor import iocpsupport as _iocp, abstract
-from twisted.internet.iocpreactor.interfaces import IReadWriteHandle
-from twisted.internet.iocpreactor.const import ERROR_IO_PENDING
-from twisted.internet.iocpreactor.const import SO_UPDATE_CONNECT_CONTEXT
-from twisted.internet.iocpreactor.const import SO_UPDATE_ACCEPT_CONTEXT
-from twisted.internet.iocpreactor.const import ERROR_CONNECTION_REFUSED
-from twisted.internet.iocpreactor.const import ERROR_NETWORK_UNREACHABLE
-
-# ConnectEx returns these. XXX: find out what it does for timeout
-connectExErrors = {
- ERROR_CONNECTION_REFUSED: errno.WSAECONNREFUSED,
- ERROR_NETWORK_UNREACHABLE: errno.WSAENETUNREACH,
- }
-
-
-
-class Connection(abstract.FileHandle, _SocketCloser):
- implements(IReadWriteHandle, interfaces.ITCPTransport,
- interfaces.ISystemHandle)
-
-
- def __init__(self, sock, proto, reactor=None):
- abstract.FileHandle.__init__(self, reactor)
- self.socket = sock
- self.getFileHandle = sock.fileno
- self.protocol = proto
-
-
- def getHandle(self):
- return self.socket
-
-
- def dataReceived(self, rbuffer):
- # XXX: some day, we'll have protocols that can handle raw buffers
- self.protocol.dataReceived(str(rbuffer))
-
-
- def readFromHandle(self, bufflist, evt):
- return _iocp.recv(self.getFileHandle(), bufflist, evt)
-
-
- def writeToHandle(self, buff, evt):
- return _iocp.send(self.getFileHandle(), buff, evt)
-
-
- def _closeWriteConnection(self):
- try:
- getattr(self.socket, self._socketShutdownMethod)(1)
- except socket.error:
- pass
- p = interfaces.IHalfCloseableProtocol(self.protocol, None)
- if p:
- try:
- p.writeConnectionLost()
- except:
- f = failure.Failure()
- log.err()
- self.connectionLost(f)
-
-
- def readConnectionLost(self, reason):
- p = interfaces.IHalfCloseableProtocol(self.protocol, None)
- if p:
- try:
- p.readConnectionLost()
- except:
- log.err()
- self.connectionLost(failure.Failure())
- else:
- self.connectionLost(reason)
-
-
- def connectionLost(self, reason):
- abstract.FileHandle.connectionLost(self, reason)
- self._closeSocket()
- protocol = self.protocol
- del self.protocol
- del self.socket
- del self.getFileHandle
- protocol.connectionLost(reason)
-
-
- def logPrefix(self):
- """
- Return the prefix to log with when I own the logging thread.
- """
- return self.logstr
-
-
- 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)
-
-
-
-class Client(Connection):
- addressFamily = socket.AF_INET
- socketType = socket.SOCK_STREAM
-
-
- def __init__(self, host, port, bindAddress, connector, reactor):
- self.connector = connector
- self.addr = (host, port)
- self.reactor = reactor
- # ConnectEx documentation says socket _has_ to be bound
- if bindAddress is None:
- bindAddress = ('', 0)
-
- try:
- try:
- skt = reactor.createSocket(self.addressFamily, self.socketType)
- except socket.error, se:
- raise error.ConnectBindError(se[0], se[1])
- else:
- try:
- skt.bind(bindAddress)
- except socket.error, se:
- raise error.ConnectBindError(se[0], se[1])
- self.socket = skt
- Connection.__init__(self, skt, None)
- reactor.callLater(0, self.resolveAddress)
- except error.ConnectBindError, err:
- reactor.callLater(0, self.failIfNotConnected, err)
-
-
- def resolveAddress(self):
- if isIPAddress(self.addr[0]):
- self._setRealAddress(self.addr[0])
- else:
- d = self.reactor.resolve(self.addr[0])
- d.addCallbacks(self._setRealAddress, self.failIfNotConnected)
-
-
- def _setRealAddress(self, address):
- self.realAddress = (address, self.addr[1])
- self.doConnect()
-
-
- def failIfNotConnected(self, err):
- if (self.connected or self.disconnected or
- not hasattr(self, "connector")):
- return
-
- try:
- self._closeSocket()
- except AttributeError:
- pass
- else:
- del self.socket, self.getFileHandle
- self.reactor.removeActiveHandle(self)
-
- self.connector.connectionFailed(failure.Failure(err))
- del self.connector
-
-
- def stopConnecting(self):
- """
- Stop attempt to connect.
- """
- self.failIfNotConnected(error.UserError())
-
-
- def cbConnect(self, rc, bytes, evt):
- if rc:
- rc = connectExErrors.get(rc, rc)
- self.failIfNotConnected(error.getConnectError((rc,
- errno.errorcode.get(rc, 'Unknown error'))))
- else:
- self.socket.setsockopt(socket.SOL_SOCKET,
- SO_UPDATE_CONNECT_CONTEXT,
- struct.pack('I', self.socket.fileno()))
- self.protocol = self.connector.buildProtocol(self.getPeer())
- self.connected = True
- self.logstr = self.protocol.__class__.__name__+",client"
- self.protocol.makeConnection(self)
- self.startReading()
-
-
- def doConnect(self):
- if not hasattr(self, "connector"):
- # this happens if we connector.stopConnecting in
- # factory.startedConnecting
- return
- assert _iocp.have_connectex
- self.reactor.addActiveHandle(self)
- evt = _iocp.Event(self.cbConnect, self)
-
- rc = _iocp.connect(self.socket.fileno(), self.realAddress, evt)
- if rc == ERROR_IO_PENDING:
- return
- else:
- evt.ignore = True
- self.cbConnect(rc, 0, 0, evt)
-
-
- def getHost(self):
- """
- Returns an IPv4Address.
-
- This indicates the address from which I am connecting.
- """
- return address.IPv4Address('TCP', *(self.socket.getsockname() +
- ('INET',)))
-
-
- def getPeer(self):
- """
- Returns an IPv4Address.
-
- This indicates the address that I am connected to.
- """
- return address.IPv4Address('TCP', *(self.addr + ('INET',)))
-
-
- def __repr__(self):
- s = ('<%s to %s at %x>' %
- (self.__class__, self.addr, util.unsignedID(self)))
- return s
-
-
- def connectionLost(self, reason):
- if not self.connected:
- self.failIfNotConnected(error.ConnectError(string=reason))
- else:
- Connection.connectionLost(self, reason)
- self.connector.connectionLost(reason)
-
-
-
-class Server(Connection):
- """
- Serverside socket-stream connection class.
-
- I am a serverside network connection transport; a socket which came from an
- accept() on a server.
- """
-
-
- def __init__(self, sock, protocol, clientAddr, serverAddr, sessionno):
- """
- Server(sock, protocol, client, server, sessionno)
-
- Initialize me with a socket, a protocol, a descriptor for my peer (a
- tuple of host, port describing the other end of the connection), an
- instance of Port, and a session number.
- """
- Connection.__init__(self, sock, protocol)
- self.serverAddr = serverAddr
- self.clientAddr = clientAddr
- self.sessionno = sessionno
- self.logstr = "%s,%s,%s" % (self.protocol.__class__.__name__,
- sessionno, self.clientAddr.host)
- self.repstr = "<%s #%s on %s>" % (self.protocol.__class__.__name__,
- self.sessionno, self.serverAddr.port)
- self.connected = True
- self.startReading()
-
-
- def __repr__(self):
- """
- A string representation of this connection.
- """
- return self.repstr
-
-
- def getHost(self):
- """
- Returns an IPv4Address.
-
- This indicates the server's address.
- """
- return self.serverAddr
-
-
- def getPeer(self):
- """
- Returns an IPv4Address.
-
- This indicates the client's address.
- """
- return self.clientAddr
-
-
-
-class Connector(TCPConnector):
- def _makeTransport(self):
- return Client(self.host, self.port, self.bindAddress, self,
- self.reactor)
-
-
-
-class Port(styles.Ephemeral, _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
-
- skt = socket.socket(self.addressFamily, self.socketType)
- self.addrLen = _iocp.maxAddrLen(skt.fileno())
-
-
- 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)
-
- # 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.reactor.addActiveHandle(self)
- self.socket = skt
- self.getFileHandle = self.socket.fileno
- self.doAccept()
-
-
- def loseConnection(self, connDone=failure.Failure(main.CONNECTION_DONE)):
- """
- Stop accepting connections on this port.
-
- This will shut down my socket and call self.connectionLost().
- It returns a deferred which will fire successfully when the
- port is actually closed.
- """
- self.disconnecting = True
- if self.connected:
- self.deferred = defer.Deferred()
- self.reactor.callLater(0, self.connectionLost, connDone)
- return self.deferred
-
- stopListening = loseConnection
-
-
- def connectionLost(self, reason):
- """
- Cleans up my socket.
- """
- log.msg('(Port %s Closed)' % self._realPortNumber)
- self._realPortNumber = None
- self.disconnected = True
- self.reactor.removeActiveHandle(self)
- self.connected = False
- self._closeSocket()
- del self.socket
- del self.getFileHandle
- self.factory.doStop()
- if hasattr(self, "deferred"):
- self.deferred.callback(None)
- del self.deferred
-
-
- def logPrefix(self):
- """
- Returns the name of my class, to prefix log entries with.
- """
- return reflect.qual(self.factory.__class__)
-
-
- def getHost(self):
- """
- Returns an IPv4Address.
-
- This indicates the server's address.
- """
- return address.IPv4Address('TCP', *(self.socket.getsockname() +
- ('INET',)))
-
-
- def cbAccept(self, rc, bytes, evt):
- self.handleAccept(rc, evt)
- if not (self.disconnecting or self.disconnected):
- self.doAccept()
-
-
- def handleAccept(self, rc, evt):
- if self.disconnecting or self.disconnected:
- return False
-
- # possible errors:
- # (WSAEMFILE, WSAENOBUFS, WSAENFILE, WSAENOMEM, WSAECONNABORTED)
- if rc:
- log.msg("Could not accept new connection -- %s (%s)" %
- (errno.errorcode.get(rc, 'unknown error'), rc))
- return False
- else:
- evt.newskt.setsockopt(socket.SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT,
- struct.pack('I', self.socket.fileno()))
- family, lAddr, rAddr = _iocp.get_accept_addrs(evt.newskt.fileno(),
- evt.buff)
- assert family == self.addressFamily
-
- protocol = self.factory.buildProtocol(
- address._ServerFactoryIPv4Address('TCP', rAddr[0], rAddr[1]))
- if protocol is None:
- evt.newskt.close()
- else:
- s = self.sessionno
- self.sessionno = s+1
- transport = Server(evt.newskt, protocol,
- address.IPv4Address('TCP', rAddr[0], rAddr[1], 'INET'),
- address.IPv4Address('TCP', lAddr[0], lAddr[1], 'INET'),
- s)
- protocol.makeConnection(transport)
- return True
-
-
- def doAccept(self):
- numAccepts = 0
- while 1:
- evt = _iocp.Event(self.cbAccept, self)
-
- # see AcceptEx documentation
- evt.buff = buff = _iocp.AllocateReadBuffer(2 * (self.addrLen + 16))
-
- evt.newskt = newskt = self.reactor.createSocket(self.addressFamily,
- self.socketType)
- rc = _iocp.accept(self.socket.fileno(), newskt.fileno(), buff, evt)
-
- if (rc == ERROR_IO_PENDING
- or (not rc and numAccepts >= self.maxAccepts)):
- break
- else:
- evt.ignore = True
- if not self.handleAccept(rc, evt):
- break
- numAccepts += 1
-
-
diff --git a/tools/buildbot/pylibs/twisted/internet/iocpreactor/udp.py b/tools/buildbot/pylibs/twisted/internet/iocpreactor/udp.py
deleted file mode 100644
index c0e1a8e..0000000
--- a/tools/buildbot/pylibs/twisted/internet/iocpreactor/udp.py
+++ /dev/null
@@ -1,389 +0,0 @@
-# Copyright (c) 2008 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-UDP support for IOCP reactor
-"""
-
-from twisted.internet import defer, address, error, interfaces
-from twisted.internet.abstract import isIPAddress
-from twisted.python import log, reflect, failure
-
-from zope.interface import implements
-import socket, operator, struct, warnings, errno
-
-from twisted.internet.iocpreactor.const import ERROR_IO_PENDING
-from twisted.internet.iocpreactor.const import ERROR_CONNECTION_REFUSED
-from twisted.internet.iocpreactor.const import ERROR_PORT_UNREACHABLE
-from twisted.internet.iocpreactor.interfaces import IReadWriteHandle
-from twisted.internet.iocpreactor import iocpsupport as _iocp, abstract
-
-
-
-class Port(abstract.FileHandle):
- """
- UDP port, listening for packets.
- """
-
- implements(IReadWriteHandle, interfaces.IUDPTransport,
- interfaces.ISystemHandle)
-
- addressFamily = socket.AF_INET
- socketType = socket.SOCK_DGRAM
- maxThroughput = 256 * 1024 # max bytes we read in one eventloop iteration
- dynamicReadBuffers = False
-
- # Actual port number being listened on, only set to a non-None
- # value when we are actually listening.
- _realPortNumber = None
-
-
- def __init__(self, port, proto, interface='', maxPacketSize=8192,
- reactor=None):
- """
- Initialize with a numeric port to listen on.
- """
- self.port = port
- self.protocol = proto
- self.readBufferSize = maxPacketSize
- self.interface = interface
- self.setLogStr()
- self._connectedAddr = None
-
- abstract.FileHandle.__init__(self, reactor)
-
- skt = socket.socket(self.addressFamily, self.socketType)
- addrLen = _iocp.maxAddrLen(skt.fileno())
- self.addressBuffer = _iocp.AllocateReadBuffer(addrLen)
-
-
- def __repr__(self):
- if self._realPortNumber is not None:
- return ("<%s on %s>" %
- (self.protocol.__class__, self._realPortNumber))
- else:
- return "<%s not connected>" % (self.protocol.__class__,)
-
-
- def getHandle(self):
- """
- Return a socket object.
- """
- return self.socket
-
-
- def startListening(self):
- """
- Create and bind my socket, and begin listening on it.
-
- This is called on unserialization, and must be called after creating a
- server to begin listening on the specified port.
- """
- self._bindSocket()
- self._connectToProtocol()
-
-
- def createSocket(self):
- return self.reactor.createSocket(self.addressFamily, self.socketType)
-
-
- def _bindSocket(self):
- try:
- skt = self.createSocket()
- skt.bind((self.interface, self.port))
- except socket.error, le:
- raise error.CannotListenError, (self.interface, self.port, le)
-
- # 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.protocol.__class__, self._realPortNumber))
-
- self.connected = True
- self.socket = skt
- self.getFileHandle = self.socket.fileno
-
-
- def _connectToProtocol(self):
- self.protocol.makeConnection(self)
- self.startReading()
- self.reactor.addActiveHandle(self)
-
-
- def cbRead(self, rc, bytes, evt):
- if self.reading:
- self.handleRead(rc, bytes, evt)
- self.doRead()
-
-
- def handleRead(self, rc, bytes, evt):
- if rc in (errno.WSAECONNREFUSED, errno.WSAECONNRESET,
- ERROR_CONNECTION_REFUSED, ERROR_PORT_UNREACHABLE):
- if self._connectedAddr:
- self.protocol.connectionRefused()
- elif rc:
- log.msg("error in recvfrom -- %s (%s)" %
- (errno.errorcode.get(rc, 'unknown error'), rc))
- else:
- try:
- self.protocol.datagramReceived(str(evt.buff[:bytes]),
- _iocp.makesockaddr(evt.addr_buff))
- except:
- log.err()
-
-
- def doRead(self):
- read = 0
- while self.reading:
- evt = _iocp.Event(self.cbRead, self)
-
- evt.buff = buff = self._readBuffers[0]
- evt.addr_buff = addr_buff = self.addressBuffer
- rc, bytes = _iocp.recvfrom(self.getFileHandle(), buff,
- addr_buff, evt)
-
- if (rc == ERROR_IO_PENDING
- or (not rc and read >= self.maxThroughput)):
- break
- else:
- evt.ignore = True
- self.handleRead(rc, bytes, evt)
- read += bytes
-
-
- def write(self, datagram, addr=None):
- """
- Write a datagram.
-
- @param addr: should be a tuple (ip, port), can be None in connected
- mode.
- """
- if self._connectedAddr:
- assert addr in (None, self._connectedAddr)
- try:
- return self.socket.send(datagram)
- except socket.error, se:
- no = se.args[0]
- if no == errno.WSAEINTR:
- return self.write(datagram)
- elif no == errno.WSAEMSGSIZE:
- raise error.MessageLengthError, "message too long"
- elif no in (errno.WSAECONNREFUSED, errno.WSAECONNRESET,
- ERROR_CONNECTION_REFUSED, ERROR_PORT_UNREACHABLE):
- self.protocol.connectionRefused()
- else:
- raise
- else:
- assert addr != None
- if not addr[0].replace(".", "").isdigit():
- warnings.warn("Please only pass IPs to write(), not hostnames",
- DeprecationWarning, stacklevel=2)
- try:
- return self.socket.sendto(datagram, addr)
- except socket.error, se:
- no = se.args[0]
- if no == errno.WSAEINTR:
- return self.write(datagram, addr)
- elif no == errno.WSAEMSGSIZE:
- raise error.MessageLengthError, "message too long"
- elif no in (errno.WSAECONNREFUSED, errno.WSAECONNRESET,
- ERROR_CONNECTION_REFUSED, ERROR_PORT_UNREACHABLE):
- # in non-connected UDP ECONNREFUSED is platform dependent,
- # I think and the info is not necessarily useful.
- # Nevertheless maybe we should call connectionRefused? XXX
- return
- else:
- raise
-
-
- def writeSequence(self, seq, addr):
- self.write("".join(seq), addr)
-
-
- def connect(self, host, port):
- """
- 'Connect' to remote server.
- """
- if self._connectedAddr:
- raise RuntimeError(
- "already connected, reconnecting is not currently supported "
- "(talk to itamar if you want this)")
- if not isIPAddress(host):
- raise ValueError, "please pass only IP addresses, not domain names"
- self._connectedAddr = (host, port)
- self.socket.connect((host, port))
-
-
- def _loseConnection(self):
- self.stopReading()
- self.reactor.removeActiveHandle(self)
- if self.connected: # actually means if we are *listening*
- from twisted.internet import reactor
- reactor.callLater(0, self.connectionLost)
-
-
- def stopListening(self):
- if self.connected:
- result = self.d = defer.Deferred()
- else:
- result = None
- self._loseConnection()
- return result
-
-
- def loseConnection(self):
- warnings.warn("Please use stopListening() to disconnect port",
- DeprecationWarning, stacklevel=2)
- self.stopListening()
-
-
- def connectionLost(self, reason=None):
- """
- Cleans up my socket.
- """
- log.msg('(Port %s Closed)' % self._realPortNumber)
- self._realPortNumber = None
- self.stopReading()
- if hasattr(self, "protocol"):
- # we won't have attribute in ConnectedPort, in cases
- # where there was an error in connection process
- self.protocol.doStop()
- self.connected = False
- self.disconnected = True
- self.socket.close()
- del self.socket
- del self.getFileHandle
- if hasattr(self, "d"):
- self.d.callback(None)
- del self.d
-
-
- def setLogStr(self):
- self.logstr = reflect.qual(self.protocol.__class__) + " (UDP)"
-
-
- 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',)))
-
-
-
-class MulticastMixin:
- """
- Implement multicast functionality.
- """
-
-
- def getOutgoingInterface(self):
- i = self.socket.getsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF)
- return socket.inet_ntoa(struct.pack("@i", i))
-
-
- def setOutgoingInterface(self, addr):
- """
- Returns Deferred of success.
- """
- return self.reactor.resolve(addr).addCallback(self._setInterface)
-
-
- def _setInterface(self, addr):
- i = socket.inet_aton(addr)
- self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, i)
- return 1
-
-
- def getLoopbackMode(self):
- return self.socket.getsockopt(socket.IPPROTO_IP,
- socket.IP_MULTICAST_LOOP)
-
-
- def setLoopbackMode(self, mode):
- mode = struct.pack("b", operator.truth(mode))
- self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP,
- mode)
-
-
- def getTTL(self):
- return self.socket.getsockopt(socket.IPPROTO_IP,
- socket.IP_MULTICAST_TTL)
-
-
- def setTTL(self, ttl):
- ttl = struct.pack("B", ttl)
- self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
-
-
- def joinGroup(self, addr, interface=""):
- """
- Join a multicast group. Returns Deferred of success.
- """
- return self.reactor.resolve(addr).addCallback(self._joinAddr1,
- interface, 1)
-
-
- def _joinAddr1(self, addr, interface, join):
- return self.reactor.resolve(interface).addCallback(self._joinAddr2,
- addr, join)
-
-
- def _joinAddr2(self, interface, addr, join):
- addr = socket.inet_aton(addr)
- interface = socket.inet_aton(interface)
- if join:
- cmd = socket.IP_ADD_MEMBERSHIP
- else:
- cmd = socket.IP_DROP_MEMBERSHIP
- try:
- self.socket.setsockopt(socket.IPPROTO_IP, cmd, addr + interface)
- except socket.error, e:
- return failure.Failure(error.MulticastJoinError(addr, interface,
- *e.args))
-
-
- def leaveGroup(self, addr, interface=""):
- """
- Leave multicast group, return Deferred of success.
- """
- return self.reactor.resolve(addr).addCallback(self._joinAddr1,
- interface, 0)
-
-
-
-class MulticastPort(MulticastMixin, Port):
- """
- UDP Port that supports multicasting.
- """
-
- implements(interfaces.IMulticastTransport)
-
-
- def __init__(self, port, proto, interface='', maxPacketSize=8192,
- reactor=None, listenMultiple=False):
- Port.__init__(self, port, proto, interface, maxPacketSize, reactor)
- self.listenMultiple = listenMultiple
-
-
- def createSocket(self):
- skt = Port.createSocket(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
-
-
diff --git a/tools/buildbot/pylibs/twisted/internet/kqreactor.py b/tools/buildbot/pylibs/twisted/internet/kqreactor.py
deleted file mode 100644
index 8de615c..0000000
--- a/tools/buildbot/pylibs/twisted/internet/kqreactor.py
+++ /dev/null
@@ -1,232 +0,0 @@
-# Copyright (c) 2001-2007 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-A kqueue()/kevent() based implementation of the Twisted main loop.
-
-To install the event loop (and you should do this before any connections,
-listeners or connectors are added)::
-
- | from twisted.internet import kqreactor
- | kqreactor.install()
-
-This reactor only works on FreeBSD and requires PyKQueue 1.3, which is
-available at: U{http://people.freebsd.org/~dwhite/PyKQueue/}
-
-Maintainer: U{Itamar Shtull-Trauring<mailto:twisted@itamarst.org>}
-
-
-
-You're going to need to patch PyKqueue::
-
- =====================================================
- --- PyKQueue-1.3/kqsyscallmodule.c Sun Jan 28 21:59:50 2001
- +++ PyKQueue-1.3/kqsyscallmodule.c.new Tue Jul 30 18:06:08 2002
- @@ -137,7 +137,7 @@
- }
-
- statichere PyTypeObject KQEvent_Type = {
- - PyObject_HEAD_INIT(NULL)
- + PyObject_HEAD_INIT(&PyType_Type)
- 0, // ob_size
- "KQEvent", // tp_name
- sizeof(KQEventObject), // tp_basicsize
- @@ -291,13 +291,14 @@
-
- /* Build timespec for timeout */
- totimespec.tv_sec = timeout / 1000;
- - totimespec.tv_nsec = (timeout % 1000) * 100000;
- + totimespec.tv_nsec = (timeout % 1000) * 1000000;
-
- // printf("timespec: sec=%d nsec=%d\\n", totimespec.tv_sec, totimespec.tv_nsec);
-
- /* Make the call */
- -
- + Py_BEGIN_ALLOW_THREADS
- gotNumEvents = kevent (self->fd, changelist, haveNumEvents, triggered, wantNumEvents, &totimespec);
- + Py_END_ALLOW_THREADS
-
- /* Don't need the input event list anymore, so get rid of it */
- free (changelist);
- @@ -361,7 +362,7 @@
- statichere PyTypeObject KQueue_Type = {
- /* The ob_type field must be initialized in the module init function
- * to be portable to Windows without using C++. */
- - PyObject_HEAD_INIT(NULL)
- + PyObject_HEAD_INIT(&PyType_Type)
- 0, /*ob_size*/
- "KQueue", /*tp_name*/
- sizeof(KQueueObject), /*tp_basicsize*/
-
-"""
-
-import errno, sys
-
-from zope.interface import implements
-
-from kqsyscall import EVFILT_READ, EVFILT_WRITE, EV_DELETE, EV_ADD
-from kqsyscall import kqueue, kevent
-
-from twisted.internet.interfaces import IReactorFDSet
-
-from twisted.python import log, failure
-from twisted.internet import main, posixbase
-
-
-class KQueueReactor(posixbase.PosixReactorBase):
- """
- A reactor that uses kqueue(2)/kevent(2).
-
- @ivar _kq: A L{kqueue} which will be used to check for I/O readiness.
-
- @ivar _selectables: A dictionary mapping integer file descriptors to
- instances of L{FileDescriptor} which have been registered with the
- reactor. All L{FileDescriptors} which are currently receiving read or
- write readiness notifications will be present as values in this
- dictionary.
-
- @ivar _reads: A dictionary mapping integer file descriptors to arbitrary
- values (this is essentially a set). Keys in this dictionary will be
- registered with C{_kq} for read readiness notifications which will be
- dispatched to the corresponding L{FileDescriptor} instances in
- C{_selectables}.
-
- @ivar _writes: A dictionary mapping integer file descriptors to arbitrary
- values (this is essentially a set). Keys in this dictionary will be
- registered with C{_kq} for write readiness notifications which will be
- dispatched to the corresponding L{FileDescriptor} instances in
- C{_selectables}.
- """
- implements(IReactorFDSet)
-
- def __init__(self):
- """
- Initialize kqueue object, file descriptor tracking dictionaries, and the
- base class.
- """
- self._kq = kqueue()
- self._reads = {}
- self._writes = {}
- self._selectables = {}
- posixbase.PosixReactorBase.__init__(self)
-
-
- def _updateRegistration(self, *args):
- self._kq.kevent([kevent(*args)], 0, 0)
-
- def addReader(self, reader):
- """Add a FileDescriptor for notification of data available to read.
- """
- fd = reader.fileno()
- if fd not in self._reads:
- self._selectables[fd] = reader
- self._reads[fd] = 1
- self._updateRegistration(fd, EVFILT_READ, EV_ADD)
-
- def addWriter(self, writer):
- """Add a FileDescriptor for notification of data available to write.
- """
- fd = writer.fileno()
- if fd not in self._writes:
- self._selectables[fd] = writer
- self._writes[fd] = 1
- self._updateRegistration(fd, EVFILT_WRITE, EV_ADD)
-
- def removeReader(self, reader):
- """Remove a Selectable for notification of data available to read.
- """
- fd = reader.fileno()
- if fd in self._reads:
- del self._reads[fd]
- if fd not in self._writes:
- del self._selectables[fd]
- self._updateRegistration(fd, EVFILT_READ, EV_DELETE)
-
- def removeWriter(self, writer):
- """Remove a Selectable for notification of data available to write.
- """
- fd = writer.fileno()
- if fd in self._writes:
- del self._writes[fd]
- if fd not in self._reads:
- del self._selectables[fd]
- self._updateRegistration(fd, EVFILT_WRITE, EV_DELETE)
-
- def removeAll(self):
- """Remove all selectables, and return a list of them."""
- if self.waker is not None:
- self.removeReader(self.waker)
- result = self._selectables.values()
- for fd in self._reads.keys():
- self._updateRegistration(fd, EVFILT_READ, EV_DELETE)
- for fd in self._writes.keys():
- self._updateRegistration(fd, EVFILT_WRITE, EV_DELETE)
- self._reads.clear()
- self._writes.clear()
- self._selectables.clear()
- if self.waker is not None:
- self.addReader(self.waker)
- return result
-
-
- def getReaders(self):
- return [self._selectables[fd] for fd in self._reads]
-
-
- def getWriters(self):
- return [self._selectables[fd] for fd in self._writes]
-
-
- def doKEvent(self, timeout):
- """Poll the kqueue for new events."""
- if timeout is None:
- timeout = 1000
- else:
- timeout = int(timeout * 1000) # convert seconds to milliseconds
-
- try:
- l = self._kq.kevent([], len(self._selectables), timeout)
- except OSError, e:
- if e[0] == errno.EINTR:
- return
- else:
- raise
- _drdw = self._doWriteOrRead
- for event in l:
- why = None
- fd, filter = event.ident, event.filter
- try:
- selectable = self._selectables[fd]
- except KeyError:
- # Handles the infrequent case where one selectable's
- # handler disconnects another.
- continue
- log.callWithLogger(selectable, _drdw, selectable, fd, filter)
-
- def _doWriteOrRead(self, selectable, fd, filter):
- try:
- if filter == EVFILT_READ:
- why = selectable.doRead()
- if filter == EVFILT_WRITE:
- why = selectable.doWrite()
- if not selectable.fileno() == fd:
- why = main.CONNECTION_LOST
- except:
- why = sys.exc_info()[1]
- log.deferr()
-
- if why:
- self.removeReader(selectable)
- self.removeWriter(selectable)
- selectable.connectionLost(failure.Failure(why))
-
- doIteration = doKEvent
-
-
-def install():
- k = KQueueReactor()
- main.installReactor(k)
-
-
-__all__ = ["KQueueReactor", "install"]
diff --git a/tools/buildbot/pylibs/twisted/internet/main.py b/tools/buildbot/pylibs/twisted/internet/main.py
deleted file mode 100644
index d8c5a5c..0000000
--- a/tools/buildbot/pylibs/twisted/internet/main.py
+++ /dev/null
@@ -1,28 +0,0 @@
-# -*- test-case-name: twisted.test.test_app -*-
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""Backwards compatability, and utility functions.
-
-In general, this module should not be used, other than by reactor authors
-who need to use the 'installReactor' method.
-
-Maintainer: U{Itamar Shtull-Trauring<mailto:twisted@itamarst.org>}
-"""
-
-import error
-
-CONNECTION_DONE = error.ConnectionDone('Connection done')
-CONNECTION_LOST = error.ConnectionLost('Connection lost')
-
-def installReactor(reactor):
- # this stuff should be common to all reactors.
- import twisted.internet
- import sys
- assert not sys.modules.has_key('twisted.internet.reactor'), \
- "reactor already installed"
- twisted.internet.reactor = reactor
- sys.modules['twisted.internet.reactor'] = reactor
-
-__all__ = ["CONNECTION_LOST", "CONNECTION_DONE", "installReactor"]
diff --git a/tools/buildbot/pylibs/twisted/internet/pollreactor.py b/tools/buildbot/pylibs/twisted/internet/pollreactor.py
deleted file mode 100644
index 353e006..0000000
--- a/tools/buildbot/pylibs/twisted/internet/pollreactor.py
+++ /dev/null
@@ -1,217 +0,0 @@
-# Copyright (c) 2001-2007 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-A poll() based implementation of the twisted main loop.
-
-To install the event loop (and you should do this before any connections,
-listeners or connectors are added)::
-
- from twisted.internet import pollreactor
- pollreactor.install()
-
-Maintainer: U{Itamar Shtull-Trauring<mailto:twisted@itamarst.org>}
-"""
-
-# System imports
-import errno, sys
-from select import error as SelectError, poll
-from select import POLLIN, POLLOUT, POLLHUP, POLLERR, POLLNVAL
-
-from zope.interface import implements
-
-# Twisted imports
-from twisted.python import log
-from twisted.internet import main, posixbase, error
-from twisted.internet.interfaces import IReactorFDSet
-
-POLL_DISCONNECTED = (POLLHUP | POLLERR | POLLNVAL)
-
-
-class PollReactor(posixbase.PosixReactorBase):
- """
- A reactor that uses poll(2).
-
- @ivar _poller: A L{poll} which will be used to check for I/O
- readiness.
-
- @ivar _selectables: A dictionary mapping integer file descriptors to
- instances of L{FileDescriptor} which have been registered with the
- reactor. All L{FileDescriptors} which are currently receiving read or
- write readiness notifications will be present as values in this
- dictionary.
-
- @ivar _reads: A dictionary mapping integer file descriptors to arbitrary
- values (this is essentially a set). Keys in this dictionary will be
- registered with C{_poller} for read readiness notifications which will
- be dispatched to the corresponding L{FileDescriptor} instances in
- C{_selectables}.
-
- @ivar _writes: A dictionary mapping integer file descriptors to arbitrary
- values (this is essentially a set). Keys in this dictionary will be
- registered with C{_poller} for write readiness notifications which will
- be dispatched to the corresponding L{FileDescriptor} instances in
- C{_selectables}.
- """
- implements(IReactorFDSet)
-
- def __init__(self):
- """
- Initialize polling object, file descriptor tracking dictionaries, and
- the base class.
- """
- self._poller = poll()
- self._selectables = {}
- self._reads = {}
- self._writes = {}
- posixbase.PosixReactorBase.__init__(self)
-
-
- def _updateRegistration(self, fd):
- """Register/unregister an fd with the poller."""
- try:
- self._poller.unregister(fd)
- except KeyError:
- pass
-
- mask = 0
- if fd in self._reads:
- mask = mask | POLLIN
- if fd in self._writes:
- mask = mask | POLLOUT
- if mask != 0:
- self._poller.register(fd, mask)
- else:
- if fd in self._selectables:
- del self._selectables[fd]
-
- def _dictRemove(self, selectable, mdict):
- try:
- # the easy way
- fd = selectable.fileno()
- # make sure the fd is actually real. In some situations we can get
- # -1 here.
- mdict[fd]
- except:
- # the hard way: necessary because fileno() may disappear at any
- # moment, thanks to python's underlying sockets impl
- for fd, fdes in self._selectables.items():
- if selectable is fdes:
- break
- else:
- # Hmm, maybe not the right course of action? This method can't
- # fail, because it happens inside error detection...
- return
- if fd in mdict:
- del mdict[fd]
- self._updateRegistration(fd)
-
- def addReader(self, reader):
- """Add a FileDescriptor for notification of data available to read.
- """
- fd = reader.fileno()
- if fd not in self._reads:
- self._selectables[fd] = reader
- self._reads[fd] = 1
- self._updateRegistration(fd)
-
- def addWriter(self, writer):
- """Add a FileDescriptor for notification of data available to write.
- """
- fd = writer.fileno()
- if fd not in self._writes:
- self._selectables[fd] = writer
- self._writes[fd] = 1
- self._updateRegistration(fd)
-
- def removeReader(self, reader):
- """Remove a Selectable for notification of data available to read.
- """
- return self._dictRemove(reader, self._reads)
-
- def removeWriter(self, writer):
- """Remove a Selectable for notification of data available to write.
- """
- return self._dictRemove(writer, self._writes)
-
- def removeAll(self):
- """Remove all selectables, and return a list of them."""
- if self.waker is not None:
- self.removeReader(self.waker)
- result = self._selectables.values()
- fds = self._selectables.keys()
- self._reads.clear()
- self._writes.clear()
- self._selectables.clear()
- for fd in fds:
- self._poller.unregister(fd)
-
- if self.waker is not None:
- self.addReader(self.waker)
- return result
-
- def doPoll(self, timeout):
- """Poll the poller for new events."""
- if timeout is not None:
- timeout = int(timeout * 1000) # convert seconds to milliseconds
-
- try:
- l = self._poller.poll(timeout)
- except SelectError, e:
- if e[0] == errno.EINTR:
- return
- else:
- raise
- _drdw = self._doReadOrWrite
- for fd, event in l:
- try:
- selectable = self._selectables[fd]
- except KeyError:
- # Handles the infrequent case where one selectable's
- # handler disconnects another.
- continue
- log.callWithLogger(selectable, _drdw, selectable, fd, event)
-
- doIteration = doPoll
-
- def _doReadOrWrite(self, selectable, fd, event):
- why = None
- inRead = False
- if event & POLL_DISCONNECTED and not (event & POLLIN):
- why = main.CONNECTION_LOST
- else:
- try:
- if event & POLLIN:
- why = selectable.doRead()
- inRead = True
- if not why and event & POLLOUT:
- why = selectable.doWrite()
- inRead = False
- if not selectable.fileno() == fd:
- why = error.ConnectionFdescWentAway('Filedescriptor went away')
- inRead = False
- except:
- log.deferr()
- why = sys.exc_info()[1]
- if why:
- self._disconnectSelectable(selectable, why, inRead)
-
-
- def getReaders(self):
- return [self._selectables[fd] for fd in self._reads]
-
-
- def getWriters(self):
- return [self._selectables[fd] for fd in self._writes]
-
-
-
-def install():
- """Install the poll() reactor."""
- p = PollReactor()
- from twisted.internet.main import installReactor
- installReactor(p)
-
-
-__all__ = ["PollReactor", "install"]
diff --git a/tools/buildbot/pylibs/twisted/internet/posixbase.py b/tools/buildbot/pylibs/twisted/internet/posixbase.py
deleted file mode 100644
index b0fc0f9..0000000
--- a/tools/buildbot/pylibs/twisted/internet/posixbase.py
+++ /dev/null
@@ -1,406 +0,0 @@
-# -*- test-case-name: twisted.test.test_internet -*-
-#
-# Copyright (c) 2001-2008 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-Posix reactor base class
-
-Maintainer: U{Itamar Shtull-Trauring<mailto:twisted@itamarst.org>}
-"""
-
-import warnings
-import socket
-import errno
-import os
-
-from zope.interface import implements, classImplements
-
-from twisted.internet.interfaces import IReactorUNIX, IReactorUNIXDatagram
-from twisted.internet.interfaces import IReactorTCP, IReactorUDP, IReactorSSL, IReactorArbitrary
-from twisted.internet.interfaces import IReactorProcess, IReactorMulticast
-from twisted.internet.interfaces import IHalfCloseableDescriptor
-from twisted.internet import error
-from twisted.internet import tcp, udp
-
-from twisted.python import log, failure, util
-from twisted.persisted import styles
-from twisted.python.runtime import platformType, platform
-
-from twisted.internet.base import ReactorBase, _SignalReactorMixin
-
-try:
- from twisted.internet import ssl
- sslEnabled = True
-except ImportError:
- sslEnabled = False
-
-try:
- from twisted.internet import unix
- unixEnabled = True
-except ImportError:
- unixEnabled = False
-
-processEnabled = False
-if platformType == 'posix':
- from twisted.internet import fdesc
- import process
- processEnabled = True
-
-if platform.isWindows():
- try:
- import win32process
- processEnabled = True
- except ImportError:
- win32process = None
-
-
-class _Win32Waker(log.Logger, styles.Ephemeral):
- """I am a workaround for the lack of pipes on win32.
-
- I am a pair of connected sockets which can wake up the main loop
- from another thread.
- """
- disconnected = 0
-
- def __init__(self, reactor):
- """Initialize.
- """
- self.reactor = reactor
- # Following select_trigger (from asyncore)'s example;
- server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- client.setsockopt(socket.IPPROTO_TCP, 1, 1)
- server.bind(('127.0.0.1', 0))
- server.listen(1)
- client.connect(server.getsockname())
- reader, clientaddr = server.accept()
- client.setblocking(0)
- reader.setblocking(0)
- self.r = reader
- self.w = client
- self.fileno = self.r.fileno
-
- def wakeUp(self):
- """Send a byte to my connection.
- """
- try:
- util.untilConcludes(self.w.send, 'x')
- except socket.error, (err, msg):
- if err != errno.WSAEWOULDBLOCK:
- raise
-
- def doRead(self):
- """Read some data from my connection.
- """
- try:
- self.r.recv(8192)
- except socket.error:
- pass
-
- def connectionLost(self, reason):
- self.r.close()
- self.w.close()
- self.reactor.waker = None
-
-class _UnixWaker(log.Logger, styles.Ephemeral):
- """This class provides a simple interface to wake up the event loop.
-
- This is used by threads or signals to wake up the event loop.
- """
- disconnected = 0
-
- i = None
- o = None
-
- def __init__(self, reactor):
- """Initialize.
- """
- self.reactor = reactor
- self.i, self.o = os.pipe()
- fdesc.setNonBlocking(self.i)
- fdesc.setNonBlocking(self.o)
- self.fileno = lambda: self.i
-
- def doRead(self):
- """Read some bytes from the pipe.
- """
- fdesc.readFromFD(self.fileno(), lambda data: None)
-
- def wakeUp(self):
- """Write one byte to the pipe, and flush it.
- """
- # We don't use fdesc.writeToFD since we need to distinguish
- # between EINTR (try again) and EAGAIN (do nothing).
- if self.o is not None:
- try:
- util.untilConcludes(os.write, self.o, 'x')
- except OSError, e:
- if e.errno != errno.EAGAIN:
- raise
-
- def connectionLost(self, reason):
- """Close both ends of my pipe.
- """
- if not hasattr(self, "o"):
- return
- for fd in self.i, self.o:
- try:
- os.close(fd)
- except IOError:
- pass
- del self.i, self.o
- self.reactor.waker = None
-
-
-if platformType == 'posix':
- _Waker = _UnixWaker
-elif platformType == 'win32':
- _Waker = _Win32Waker
-
-
-class PosixReactorBase(_SignalReactorMixin, ReactorBase):
- """
- A basis for reactors that use file descriptors.
- """
- implements(IReactorArbitrary, IReactorTCP, IReactorUDP, IReactorMulticast)
-
- def __init__(self):
- ReactorBase.__init__(self)
- if self.usingThreads or platformType == "posix":
- self.installWaker()
-
-
- def _disconnectSelectable(self, selectable, why, isRead, faildict={
- error.ConnectionDone: failure.Failure(error.ConnectionDone()),
- error.ConnectionLost: failure.Failure(error.ConnectionLost())
- }):
- """
- Utility function for disconnecting a selectable.
-
- Supports half-close notification, isRead should be boolean indicating
- whether error resulted from doRead().
- """
- self.removeReader(selectable)
- f = faildict.get(why.__class__)
- if f:
- if (isRead and why.__class__ == error.ConnectionDone
- and IHalfCloseableDescriptor.providedBy(selectable)):
- selectable.readConnectionLost(f)
- else:
- self.removeWriter(selectable)
- selectable.connectionLost(f)
- else:
- self.removeWriter(selectable)
- selectable.connectionLost(failure.Failure(why))
-
- def installWaker(self):
- """
- Install a `waker' to allow threads and signals to wake up the IO thread.
-
- We use the self-pipe trick (http://cr.yp.to/docs/selfpipe.html) to wake
- the reactor. On Windows we use a pair of sockets.
- """
- if not self.waker:
- self.waker = _Waker(self)
- self.addReader(self.waker)
-
-
- # IReactorProcess
-
- def spawnProcess(self, processProtocol, executable, args=(),
- env={}, path=None,
- uid=None, gid=None, usePTY=0, childFDs=None):
- args, env = self._checkProcessArgs(args, env)
- if platformType == 'posix':
- if usePTY:
- if childFDs is not None:
- raise ValueError("Using childFDs is not supported with usePTY=True.")
- return process.PTYProcess(self, executable, args, env, path,
- processProtocol, uid, gid, usePTY)
- else:
- return process.Process(self, executable, args, env, path,
- processProtocol, uid, gid, childFDs)
- elif platformType == "win32":
- if uid is not None or gid is not None:
- raise ValueError("The uid and gid parameters are not supported on Windows.")
- if usePTY:
- raise ValueError("The usePTY parameter is not supported on Windows.")
- if childFDs:
- raise ValueError("Customizing childFDs is not supported on Windows.")
-
- if win32process:
- from twisted.internet._dumbwin32proc import Process
- return Process(self, processProtocol, executable, args, env, path)
- else:
- raise NotImplementedError, "spawnProcess not available since pywin32 is not installed."
- else:
- raise NotImplementedError, "spawnProcess only available on Windows or POSIX."
-
- # IReactorUDP
-
- def listenUDP(self, port, protocol, interface='', maxPacketSize=8192):
- """Connects a given L{DatagramProtocol} to the given numeric UDP port.
-
- @returns: object conforming to L{IListeningPort}.
- """
- p = udp.Port(port, protocol, interface, maxPacketSize, self)
- p.startListening()
- return p
-
- def connectUDP(self, remotehost, remoteport, protocol, localport=0,
- interface='', maxPacketSize=8192):
- """DEPRECATED.
-
- Connects a L{ConnectedDatagramProtocol} instance to a UDP port.
- """
- warnings.warn("use listenUDP and then transport.connect().", DeprecationWarning, stacklevel=2)
- p = udp.ConnectedPort((remotehost, remoteport), localport, protocol, interface, maxPacketSize, self)
- p.startListening()
- return p
-
-
- # IReactorMulticast
-
- def listenMulticast(self, port, protocol, interface='', maxPacketSize=8192, listenMultiple=False):
- """Connects a given DatagramProtocol to the given numeric UDP port.
-
- EXPERIMENTAL.
-
- @returns: object conforming to IListeningPort.
- """
- p = udp.MulticastPort(port, protocol, interface, maxPacketSize, self, listenMultiple)
- p.startListening()
- return p
-
-
- # IReactorUNIX
-
- def connectUNIX(self, address, factory, timeout=30, checkPID=0):
- """@see: twisted.internet.interfaces.IReactorUNIX.connectUNIX
- """
- assert unixEnabled, "UNIX support is not present"
- c = unix.Connector(address, factory, timeout, self, checkPID)
- c.connect()
- return c
-
- def listenUNIX(self, address, factory, backlog=50, mode=0666, wantPID=0):
- """@see: twisted.internet.interfaces.IReactorUNIX.listenUNIX
- """
- assert unixEnabled, "UNIX support is not present"
- p = unix.Port(address, factory, backlog, mode, self, wantPID)
- p.startListening()
- return p
-
-
- # IReactorUNIXDatagram
-
- def listenUNIXDatagram(self, address, protocol, maxPacketSize=8192, mode=0666):
- """Connects a given L{DatagramProtocol} to the given path.
-
- EXPERIMENTAL.
-
- @returns: object conforming to L{IListeningPort}.
- """
- assert unixEnabled, "UNIX support is not present"
- p = unix.DatagramPort(address, protocol, maxPacketSize, mode, self)
- p.startListening()
- return p
-
- def connectUNIXDatagram(self, address, protocol, maxPacketSize=8192, mode=0666, bindAddress=None):
- """Connects a L{ConnectedDatagramProtocol} instance to a path.
-
- EXPERIMENTAL.
- """
- assert unixEnabled, "UNIX support is not present"
- p = unix.ConnectedDatagramPort(address, protocol, maxPacketSize, mode, bindAddress, self)
- p.startListening()
- return p
-
-
- # IReactorTCP
-
- def listenTCP(self, port, factory, backlog=50, interface=''):
- """@see: twisted.internet.interfaces.IReactorTCP.listenTCP
- """
- p = tcp.Port(port, factory, backlog, interface, self)
- p.startListening()
- return p
-
- def connectTCP(self, host, port, factory, timeout=30, bindAddress=None):
- """@see: twisted.internet.interfaces.IReactorTCP.connectTCP
- """
- c = tcp.Connector(host, port, factory, timeout, bindAddress, self)
- c.connect()
- return c
-
- # IReactorSSL (sometimes, not implemented)
-
- def connectSSL(self, host, port, factory, contextFactory, timeout=30, bindAddress=None):
- """@see: twisted.internet.interfaces.IReactorSSL.connectSSL
- """
- assert sslEnabled, "SSL support is not present"
- c = ssl.Connector(host, port, factory, contextFactory, timeout, bindAddress, self)
- c.connect()
- return c
-
- def listenSSL(self, port, factory, contextFactory, backlog=50, interface=''):
- """@see: twisted.internet.interfaces.IReactorSSL.listenSSL
- """
- assert sslEnabled, "SSL support is not present"
- p = ssl.Port(port, factory, contextFactory, backlog, interface, self)
- p.startListening()
- return p
-
- # IReactorArbitrary
- def listenWith(self, portType, *args, **kw):
- kw['reactor'] = self
- p = portType(*args, **kw)
- p.startListening()
- return p
-
- def connectWith(self, connectorType, *args, **kw):
- kw['reactor'] = self
- c = connectorType(*args, **kw)
- c.connect()
- return c
-
- def _removeAll(self, readers, writers):
- """
- Remove all readers and writers, and return list of Selectables.
-
- Meant for calling from subclasses, to implement removeAll, like::
-
- def removeAll(self):
- return self._removeAll(reads, writes)
-
- where C{reads} and C{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)
-if processEnabled:
- classImplements(PosixReactorBase, IReactorProcess)
-
-__all__ = ["PosixReactorBase"]
diff --git a/tools/buildbot/pylibs/twisted/internet/process.py b/tools/buildbot/pylibs/twisted/internet/process.py
deleted file mode 100644
index 93aad22..0000000
--- a/tools/buildbot/pylibs/twisted/internet/process.py
+++ /dev/null
@@ -1,922 +0,0 @@
-# -*- test-case-name: twisted.test.test_process -*-
-# Copyright (c) 2001-2007 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-UNIX Process management.
-
-Do NOT use this module directly - use reactor.spawnProcess() instead.
-
-Maintainer: U{Itamar Shtull-Trauring<mailto:twisted@itamarst.org>}
-"""
-
-# System Imports
-import gc, os, sys, traceback, select, signal, errno
-import warnings
-
-try:
- import pty
-except ImportError:
- pty = None
-
-try:
- import fcntl, termios
-except ImportError:
- fcntl = None
-
-from twisted.persisted import styles
-from twisted.python import log, failure
-from twisted.python.util import switchUID
-from twisted.internet import fdesc, abstract, error
-from twisted.internet.main import CONNECTION_LOST, CONNECTION_DONE
-
-# Some people were importing this, which is incorrect, just keeping it
-# here for backwards compatibility:
-ProcessExitedAlready = error.ProcessExitedAlready
-
-reapProcessHandlers = {}
-
-def reapAllProcesses():
- """
- Reap all registered processes.
- """
- for process in reapProcessHandlers.values():
- process.reapProcess()
-
-
-def registerReapProcessHandler(pid, process):
- """
- Register a process handler for the given pid, in case L{reapAllProcesses}
- is called.
-
- @param pid: the pid of the process.
- @param process: a process handler.
- """
- if pid in reapProcessHandlers:
- raise RuntimeError("Try to register an already registered process.")
- try:
- auxPID, status = os.waitpid(pid, os.WNOHANG)
- except:
- log.msg('Failed to reap %d:' % pid)
- log.err()
- auxPID = None
- if auxPID:
- process.processEnded(status)
- else:
- # if auxPID is 0, there are children but none have exited
- reapProcessHandlers[pid] = process
-
-
-def unregisterReapProcessHandler(pid, process):
- """
- Unregister a process handler previously registered with
- L{registerReapProcessHandler}.
- """
- if not (pid in reapProcessHandlers
- and reapProcessHandlers[pid] == process):
- raise RuntimeError("Try to unregister a process not registered.")
- del reapProcessHandlers[pid]
-
-
-def detectLinuxBrokenPipeBehavior():
- """
- On some Linux version, write-only pipe are detected as readable. This
- function is here to check if this bug is present or not.
-
- See L{ProcessWriter.doRead} for a more detailed explanation.
- """
- global brokenLinuxPipeBehavior
- r, w = os.pipe()
- os.write(w, 'a')
- reads, writes, exes = select.select([w], [], [], 0)
- if reads:
- # Linux < 2.6.11 says a write-only pipe is readable.
- brokenLinuxPipeBehavior = True
- else:
- brokenLinuxPipeBehavior = False
- os.close(r)
- os.close(w)
-
-# Call at import time
-detectLinuxBrokenPipeBehavior()
-
-
-class ProcessWriter(abstract.FileDescriptor):
- """
- (Internal) Helper class to write into a Process's input pipe.
-
- I am a helper which describes a selectable asynchronous writer to a
- process's input pipe, including stdin.
- """
- connected = 1
- ic = 0
- enableReadHack = False
-
- def __init__(self, reactor, proc, name, fileno, forceReadHack=False):
- """
- Initialize, specifying a Process instance to connect to.
- """
- abstract.FileDescriptor.__init__(self, reactor)
- fdesc.setNonBlocking(fileno)
- self.proc = proc
- self.name = name
- self.fd = fileno
-
- if forceReadHack:
- self.enableReadHack = True
- else:
- # Detect if this fd is actually a write-only fd. If it's
- # valid to read, don't try to detect closing via read.
- # This really only means that we cannot detect a TTY's write
- # pipe being closed.
- try:
- os.read(self.fileno(), 0)
- except OSError:
- # It's a write-only pipe end, enable hack
- self.enableReadHack = True
-
- if self.enableReadHack:
- self.startReading()
-
- def fileno(self):
- """
- Return the fileno() of my process's stdin.
- """
- return self.fd
-
- def writeSomeData(self, data):
- """
- Write some data to the open process.
- """
- rv = fdesc.writeToFD(self.fd, data)
- if rv == len(data) and self.enableReadHack:
- self.startReading()
- return rv
-
- def write(self, data):
- self.stopReading()
- abstract.FileDescriptor.write(self, data)
-
- def doRead(self):
- """
- The only way a write pipe can become "readable" is at EOF, because the
- child has closed it, and we're using a reactor which doesn't
- distinguish between readable and closed (such as the select reactor).
-
- Except that's not true on linux < 2.6.11. It has the following
- characteristics: write pipe is completely empty => POLLOUT (writable in
- select), write pipe is not completely empty => POLLIN (readable in
- select), write pipe's reader closed => POLLIN|POLLERR (readable and
- writable in select)
-
- That's what this funky code is for. If linux was not broken, this
- function could be simply "return CONNECTION_LOST".
-
- BUG: We call select no matter what the reactor.
- If the reactor is pollreactor, and the fd is > 1024, this will fail.
- (only occurs on broken versions of linux, though).
- """
- if self.enableReadHack:
- if brokenLinuxPipeBehavior:
- fd = self.fd
- r, w, x = select.select([fd], [fd], [], 0)
- if r and w:
- return CONNECTION_LOST
- else:
- return CONNECTION_LOST
- else:
- self.stopReading()
-
- def connectionLost(self, reason):
- """
- See abstract.FileDescriptor.connectionLost.
- """
- # At least on OS X 10.4, exiting while stdout is non-blocking can
- # result in data loss. For some reason putting the file descriptor
- # back into blocking mode seems to resolve this issue.
- fdesc.setBlocking(self.fd)
-
- abstract.FileDescriptor.connectionLost(self, reason)
- self.proc.childConnectionLost(self.name, reason)
-
-
-
-class ProcessReader(abstract.FileDescriptor):
- """
- ProcessReader
-
- I am a selectable representation of a process's output pipe, such as
- stdout and stderr.
- """
- connected = 1
-
- def __init__(self, reactor, proc, name, fileno):
- """
- Initialize, specifying a process to connect to.
- """
- abstract.FileDescriptor.__init__(self, reactor)
- fdesc.setNonBlocking(fileno)
- self.proc = proc
- self.name = name
- self.fd = fileno
- self.startReading()
-
- def fileno(self):
- """
- Return the fileno() of my process's stderr.
- """
- return self.fd
-
- def writeSomeData(self, data):
- # the only time this is actually called is after .loseConnection Any
- # actual write attempt would fail, so we must avoid that. This hack
- # allows us to use .loseConnection on both readers and writers.
- assert data == ""
- return CONNECTION_LOST
-
- def doRead(self):
- """
- This is called when the pipe becomes readable.
- """
- return fdesc.readFromFD(self.fd, self.dataReceived)
-
- def dataReceived(self, data):
- self.proc.childDataReceived(self.name, data)
-
- def loseConnection(self):
- if self.connected and not self.disconnecting:
- self.disconnecting = 1
- self.stopReading()
- self.reactor.callLater(0, self.connectionLost,
- failure.Failure(CONNECTION_DONE))
-
- def connectionLost(self, reason):
- """
- Close my end of the pipe, signal the Process (which signals the
- ProcessProtocol).
- """
- abstract.FileDescriptor.connectionLost(self, reason)
- self.proc.childConnectionLost(self.name, reason)
-
-
-class _BaseProcess(styles.Ephemeral, object):
- """
- Base class for Process and PTYProcess.
- """
-
- status = -1
- pid = None
-
- def reapProcess(self):
- """
- Try to reap a process (without blocking) via waitpid.
-
- This is called when sigchild is caught or a Process object loses its
- "connection" (stdout is closed) This ought to result in reaping all
- zombie processes, since it will be called twice as often as it needs
- to be.
-
- (Unfortunately, this is a slightly experimental approach, since
- UNIX has no way to be really sure that your process is going to
- go away w/o blocking. I don't want to block.)
- """
- try:
- try:
- pid, status = os.waitpid(self.pid, os.WNOHANG)
- except OSError, e:
- if e.errno == errno.ECHILD:
- # no child process
- pid = None
- else:
- raise
- except:
- log.msg('Failed to reap %d:' % self.pid)
- log.err()
- pid = None
- if pid:
- self.processEnded(status)
- unregisterReapProcessHandler(pid, self)
-
- def signalProcess(self, signalID):
- """
- Send the given signal C{signalID} to the process. It'll translate a
- few signals ('HUP', 'STOP', 'INT', 'KILL', 'TERM') from a string
- representation to its int value, otherwise it'll pass directly the
- value provided
-
- @type signalID: C{str} or C{int}
- """
- if signalID in ('HUP', 'STOP', 'INT', 'KILL', 'TERM'):
- signalID = getattr(signal, 'SIG%s' % (signalID,))
- if self.pid is None:
- raise ProcessExitedAlready()
- os.kill(self.pid, signalID)
-
- def maybeCallProcessEnded(self):
- """
- Call processEnded on protocol after final cleanup.
- """
- try:
- exitCode = sig = None
- if self.status != -1:
- if os.WIFEXITED(self.status):
- exitCode = os.WEXITSTATUS(self.status)
- else:
- sig = os.WTERMSIG(self.status)
- else:
- pass # don't think this can happen
- if exitCode or sig:
- e = error.ProcessTerminated(exitCode, sig, self.status)
- else:
- e = error.ProcessDone(self.status)
- if self.proto is not None:
- self.proto.processEnded(failure.Failure(e))
- self.proto = None
- except:
- log.err()
-
- def _fork(self, path, uid, gid, executable, args, environment, **kwargs):
- """
- Fork and then exec sub-process.
-
- @param path: the path where to run the new process.
- @type path: C{str}
- @param uid: if defined, the uid used to run the new process.
- @type uid: C{int}
- @param gid: if defined, the gid used to run the new process.
- @type gid: C{int}
- @param executable: the executable to run in a new process.
- @type executable: C{str}
- @param args: arguments used to create the new process.
- @type args: C{list}.
- @param environment: environment used for the new process.
- @type environment: C{dict}.
- @param kwargs: keyword arguments to L{_setupChild} method.
- """
- settingUID = (uid is not None) or (gid is not None)
- if settingUID:
- curegid = os.getegid()
- currgid = os.getgid()
- cureuid = os.geteuid()
- curruid = os.getuid()
- if uid is None:
- uid = cureuid
- if gid is None:
- gid = curegid
- # prepare to change UID in subprocess
- os.setuid(0)
- os.setgid(0)
-
- collectorEnabled = gc.isenabled()
- gc.disable()
- try:
- self.pid = os.fork()
- except:
- # Still in the parent process
- if collectorEnabled:
- gc.enable()
- raise
- else:
- if self.pid == 0: # pid is 0 in the child process
- # do not put *ANY* code outside the try block. The child process
- # must either exec or _exit. If it gets outside this block (due
- # to an exception that is not handled here, but which might be
- # handled higher up), there will be two copies of the parent
- # running in parallel, doing all kinds of damage.
-
- # After each change to this code, review it to make sure there
- # are no exit paths.
- try:
- # Stop debugging. If I am, I don't care anymore.
- sys.settrace(None)
- self._setupChild(**kwargs)
- self._execChild(path, settingUID, uid, gid,
- executable, args, environment)
- except:
- # If there are errors, bail and try to write something
- # descriptive to stderr.
- # XXX: The parent's stderr isn't necessarily fd 2 anymore, or
- # even still available
- # XXXX: however even libc assumes write(2, err) is a useful
- # thing to attempt
- try:
- stderr = os.fdopen(2, 'w')
- stderr.write("Upon execvpe %s %s in environment %s\n:" %
- (executable, str(args),
- "id %s" % id(environment)))
- traceback.print_exc(file=stderr)
- stderr.flush()
- for fd in range(3):
- os.close(fd)
- except:
- pass # make *sure* the child terminates
- # Did you read the comment about not adding code here?
- os._exit(1)
-
- # we are now in parent process
- if collectorEnabled:
- gc.enable()
- self.status = -1 # this records the exit status of the child
- if settingUID:
- os.setregid(currgid, curegid)
- os.setreuid(curruid, cureuid)
-
- def _setupChild(self, *args, **kwargs):
- """
- Setup the child process. Override in subclasses.
- """
- raise NotImplementedError()
-
- def _execChild(self, path, settingUID, uid, gid,
- executable, args, environment):
- """
- The exec() which is done in the forked child.
- """
- if path:
- os.chdir(path)
- # set the UID before I actually exec the process
- if settingUID:
- switchUID(uid, gid)
- os.execvpe(executable, args, environment)
-
- def __repr__(self):
- """
- String representation of a process.
- """
- return "<%s pid=%s status=%s>" % (self.__class__.__name__,
- self.pid, self.status)
-
-class Process(_BaseProcess):
- """
- An operating-system Process.
-
- This represents an operating-system process with arbitrary input/output
- pipes connected to it. Those pipes may represent standard input,
- standard output, and standard error, or any other file descriptor.
-
- On UNIX, this is implemented using fork(), exec(), pipe()
- and fcntl(). These calls may not exist elsewhere so this
- code is not cross-platform. (also, windows can only select
- on sockets...)
- """
-
- debug = False
- debug_child = False
-
- status = -1
- pid = None
-
- processWriterFactory = ProcessWriter
- processReaderFactory = ProcessReader
-
- def __init__(self,
- reactor, executable, args, environment, path, proto,
- uid=None, gid=None, childFDs=None):
- """
- Spawn an operating-system process.
-
- This is where the hard work of disconnecting all currently open
- files / forking / executing the new process happens. (This is
- executed automatically when a Process is instantiated.)
-
- This will also run the subprocess as a given user ID and group ID, if
- specified. (Implementation Note: this doesn't support all the arcane
- nuances of setXXuid on UNIX: it will assume that either your effective
- or real UID is 0.)
- """
- if not proto:
- assert 'r' not in childFDs.values()
- assert 'w' not in childFDs.values()
- if not signal.getsignal(signal.SIGCHLD):
- warnings.warn(
- error.PotentialZombieWarning.MESSAGE,
- error.PotentialZombieWarning,
- stacklevel=3)
-
- self.lostProcess = False
-
- self.pipes = {}
- # keys are childFDs, we can sense them closing
- # values are ProcessReader/ProcessWriters
-
- helpers = {}
- # keys are childFDs
- # values are parentFDs
-
- if childFDs is None:
- childFDs = {0: "w", # we write to the child's stdin
- 1: "r", # we read from their stdout
- 2: "r", # and we read from their stderr
- }
-
- debug = self.debug
- if debug: print "childFDs", childFDs
-
- # fdmap.keys() are filenos of pipes that are used by the child.
- fdmap = {} # maps childFD to parentFD
- for childFD, target in childFDs.items():
- if debug: print "[%d]" % childFD, target
- if target == "r":
- # we need a pipe that the parent can read from
- readFD, writeFD = os.pipe()
- if debug: print "readFD=%d, writeFD=%d" % (readFD, writeFD)
- fdmap[childFD] = writeFD # child writes to this
- helpers[childFD] = readFD # parent reads from this
- elif target == "w":
- # we need a pipe that the parent can write to
- readFD, writeFD = os.pipe()
- if debug: print "readFD=%d, writeFD=%d" % (readFD, writeFD)
- fdmap[childFD] = readFD # child reads from this
- helpers[childFD] = writeFD # parent writes to this
- else:
- assert type(target) == int, '%r should be an int' % (target,)
- fdmap[childFD] = target # parent ignores this
- if debug: print "fdmap", fdmap
- if debug: print "helpers", helpers
- # the child only cares about fdmap.values()
-
- self._fork(path, uid, gid, executable, args, environment, fdmap=fdmap)
-
- # we are the parent process:
- self.proto = proto
-
- # arrange for the parent-side pipes to be read and written
- for childFD, parentFD in helpers.items():
- os.close(fdmap[childFD])
-
- if childFDs[childFD] == "r":
- reader = self.processReaderFactory(reactor, self, childFD,
- parentFD)
- self.pipes[childFD] = reader
-
- if childFDs[childFD] == "w":
- writer = self.processWriterFactory(reactor, self, childFD,
- parentFD, forceReadHack=True)
- self.pipes[childFD] = writer
-
- try:
- # the 'transport' is used for some compatibility methods
- if self.proto is not None:
- self.proto.makeConnection(self)
- except:
- log.err()
- registerReapProcessHandler(self.pid, self)
-
- def _setupChild(self, fdmap):
- """
- fdmap[childFD] = parentFD
-
- The child wants to end up with 'childFD' attached to what used to be
- the parent's parentFD. As an example, a bash command run like
- 'command 2>&1' would correspond to an fdmap of {0:0, 1:1, 2:1}.
- 'command >foo.txt' would be {0:0, 1:os.open('foo.txt'), 2:2}.
-
- This is accomplished in two steps::
-
- 1. close all file descriptors that aren't values of fdmap. This
- means 0 .. maxfds.
-
- 2. for each childFD::
-
- - if fdmap[childFD] == childFD, the descriptor is already in
- place. Make sure the CLOEXEC flag is not set, then delete
- the entry from fdmap.
-
- - if childFD is in fdmap.values(), then the target descriptor
- is busy. Use os.dup() to move it elsewhere, update all
- fdmap[childFD] items that point to it, then close the
- original. Then fall through to the next case.
-
- - now fdmap[childFD] is not in fdmap.values(), and is free.
- Use os.dup2() to move it to the right place, then close the
- original.
- """
-
- debug = self.debug_child
- if debug:
- errfd = sys.stderr
- errfd.write("starting _setupChild\n")
-
- destList = fdmap.values()
- try:
- import resource
- maxfds = resource.getrlimit(resource.RLIMIT_NOFILE)[1] + 1
- # OS-X reports 9223372036854775808. That's a lot of fds to close
- if maxfds > 1024:
- maxfds = 1024
- except:
- maxfds = 256
-
- for fd in xrange(maxfds):
- if fd in destList:
- continue
- if debug and fd == errfd.fileno():
- continue
- try:
- os.close(fd)
- except:
- pass
-
- # at this point, the only fds still open are the ones that need to
- # be moved to their appropriate positions in the child (the targets
- # of fdmap, i.e. fdmap.values() )
-
- if debug: print >>errfd, "fdmap", fdmap
- childlist = fdmap.keys()
- childlist.sort()
-
- for child in childlist:
- target = fdmap[child]
- if target == child:
- # fd is already in place
- if debug: print >>errfd, "%d already in place" % target
- if fcntl and hasattr(fcntl, 'FD_CLOEXEC'):
- old = fcntl.fcntl(child, fcntl.F_GETFD)
- fcntl.fcntl(child,
- fcntl.F_SETFD, old & ~fcntl.FD_CLOEXEC)
- else:
- if child in fdmap.values():
- # we can't replace child-fd yet, as some other mapping
- # still needs the fd it wants to target. We must preserve
- # that old fd by duping it to a new home.
- newtarget = os.dup(child) # give it a safe home
- if debug: print >>errfd, "os.dup(%d) -> %d" % (child,
- newtarget)
- os.close(child) # close the original
- for c, p in fdmap.items():
- if p == child:
- fdmap[c] = newtarget # update all pointers
- # now it should be available
- if debug: print >>errfd, "os.dup2(%d,%d)" % (target, child)
- os.dup2(target, child)
-
- # At this point, the child has everything it needs. We want to close
- # everything that isn't going to be used by the child, i.e.
- # everything not in fdmap.keys(). The only remaining fds open are
- # those in fdmap.values().
-
- # Any given fd may appear in fdmap.values() multiple times, so we
- # need to remove duplicates first.
-
- old = []
- for fd in fdmap.values():
- if not fd in old:
- if not fd in fdmap.keys():
- old.append(fd)
- if debug: print >>errfd, "old", old
- for fd in old:
- os.close(fd)
-
- def writeToChild(self, childFD, data):
- self.pipes[childFD].write(data)
-
- def closeChildFD(self, childFD):
- # for writer pipes, loseConnection tries to write the remaining data
- # out to the pipe before closing it
- # if childFD is not in the list of pipes, assume that it is already
- # closed
- if childFD in self.pipes:
- self.pipes[childFD].loseConnection()
-
- def pauseProducing(self):
- for p in self.pipes.itervalues():
- if isinstance(p, ProcessReader):
- p.stopReading()
-
- def resumeProducing(self):
- for p in self.pipes.itervalues():
- if isinstance(p, ProcessReader):
- p.startReading()
-
- # compatibility
- def closeStdin(self):
- """
- Call this to close standard input on this process.
- """
- self.closeChildFD(0)
-
- def closeStdout(self):
- self.closeChildFD(1)
-
- def closeStderr(self):
- self.closeChildFD(2)
-
- def loseConnection(self):
- self.closeStdin()
- self.closeStderr()
- self.closeStdout()
-
- def write(self, data):
- """
- Call this to write to standard input on this process.
-
- NOTE: This will silently lose data if there is no standard input.
- """
- if 0 in self.pipes:
- self.pipes[0].write(data)
-
- def registerProducer(self, producer, streaming):
- """
- Call this to register producer for standard input.
-
- If there is no standard input producer.stopProducing() will
- be called immediately.
- """
- if 0 in self.pipes:
- self.pipes[0].registerProducer(producer, streaming)
- else:
- producer.stopProducing()
-
- def unregisterProducer(self):
- """
- Call this to unregister producer for standard input."""
- if 0 in self.pipes:
- self.pipes[0].unregisterProducer()
-
- def writeSequence(self, seq):
- """
- Call this to write to standard input on this process.
-
- NOTE: This will silently lose data if there is no standard input.
- """
- if 0 in self.pipes:
- self.pipes[0].writeSequence(seq)
-
- def childDataReceived(self, name, data):
- self.proto.childDataReceived(name, data)
-
- def processEnded(self, status):
- # this is called when the child terminates (SIGCHLD)
- self.status = status
- self.lostProcess = True
- self.pid = None
- self.maybeCallProcessEnded()
-
- def childConnectionLost(self, childFD, reason):
- # this is called when one of the helpers (ProcessReader or
- # ProcessWriter) notices their pipe has been closed
- os.close(self.pipes[childFD].fileno())
- del self.pipes[childFD]
- try:
- self.proto.childConnectionLost(childFD)
- except:
- log.err()
- self.maybeCallProcessEnded()
-
- def maybeCallProcessEnded(self):
- # we don't call ProcessProtocol.processEnded until:
- # the child has terminated, AND
- # all writers have indicated an error status, AND
- # all readers have indicated EOF
- # This insures that we've gathered all output from the process.
- if self.pipes:
- return
- if not self.lostProcess:
- self.reapProcess()
- return
- _BaseProcess.maybeCallProcessEnded(self)
-
-
-class PTYProcess(abstract.FileDescriptor, _BaseProcess):
- """
- An operating-system Process that uses PTY support.
- """
- status = -1
- pid = None
-
- def __init__(self, reactor, executable, args, environment, path, proto,
- uid=None, gid=None, usePTY=None):
- """
- Spawn an operating-system process.
-
- This is where the hard work of disconnecting all currently open
- files / forking / executing the new process happens. (This is
- executed automatically when a Process is instantiated.)
-
- This will also run the subprocess as a given user ID and group ID, if
- specified. (Implementation Note: this doesn't support all the arcane
- nuances of setXXuid on UNIX: it will assume that either your effective
- or real UID is 0.)
- """
- if pty is None and not isinstance(usePTY, (tuple, list)):
- # no pty module and we didn't get a pty to use
- raise NotImplementedError(
- "cannot use PTYProcess on platforms without the pty module.")
- abstract.FileDescriptor.__init__(self, reactor)
-
- if isinstance(usePTY, (tuple, list)):
- masterfd, slavefd, ttyname = usePTY
- else:
- masterfd, slavefd = pty.openpty()
- ttyname = os.ttyname(slavefd)
-
- self._fork(path, uid, gid, executable, args, environment,
- masterfd=masterfd, slavefd=slavefd)
-
- # we are now in parent process:
- os.close(slavefd)
- fdesc.setNonBlocking(masterfd)
- self.fd = masterfd
- self.startReading()
- self.connected = 1
- self.proto = proto
- self.lostProcess = 0
- self.status = -1
- try:
- self.proto.makeConnection(self)
- except:
- log.err()
- registerReapProcessHandler(self.pid, self)
-
- def _setupChild(self, masterfd, slavefd):
- """
- Setup child process after fork() but before exec().
- """
- os.close(masterfd)
- if hasattr(termios, 'TIOCNOTTY'):
- try:
- fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY)
- except OSError:
- pass
- else:
- try:
- fcntl.ioctl(fd, termios.TIOCNOTTY, '')
- except:
- pass
- os.close(fd)
-
- os.setsid()
-
- if hasattr(termios, 'TIOCSCTTY'):
- fcntl.ioctl(slavefd, termios.TIOCSCTTY, '')
-
- for fd in range(3):
- if fd != slavefd:
- os.close(fd)
-
- os.dup2(slavefd, 0) # stdin
- os.dup2(slavefd, 1) # stdout
- os.dup2(slavefd, 2) # stderr
-
- for fd in xrange(3, 256):
- try:
- os.close(fd)
- except:
- pass
-
- # PTYs do not have stdin/stdout/stderr. They only have in and out, just
- # like sockets. You cannot close one without closing off the entire PTY.
- def closeStdin(self):
- pass
-
- def closeStdout(self):
- pass
-
- def closeStderr(self):
- pass
-
- def processEnded(self, status):
- self.status = status
- self.lostProcess += 1
- self.pid = None
- self.maybeCallProcessEnded()
-
- def doRead(self):
- """
- Called when my standard output stream is ready for reading.
- """
- return fdesc.readFromFD(
- self.fd,
- lambda data: self.proto.childDataReceived(1, data))
-
- def fileno(self):
- """
- This returns the file number of standard output on this process.
- """
- return self.fd
-
- def maybeCallProcessEnded(self):
- # two things must happen before we call the ProcessProtocol's
- # processEnded method. 1: the child process must die and be reaped
- # (which calls our own processEnded method). 2: the child must close
- # their stdin/stdout/stderr fds, causing the pty to close, causing
- # our connectionLost method to be called. #2 can also be triggered
- # by calling .loseConnection().
- if self.lostProcess == 2:
- _BaseProcess.maybeCallProcessEnded(self)
-
- def connectionLost(self, reason):
- """
- I call this to clean up when one or all of my connections has died.
- """
- abstract.FileDescriptor.connectionLost(self, reason)
- os.close(self.fd)
- self.lostProcess += 1
- self.maybeCallProcessEnded()
-
- def writeSomeData(self, data):
- """
- Write some data to the open process.
- """
- return fdesc.writeToFD(self.fd, data)
-
diff --git a/tools/buildbot/pylibs/twisted/internet/protocol.py b/tools/buildbot/pylibs/twisted/internet/protocol.py
deleted file mode 100644
index 7bc2925..0000000
--- a/tools/buildbot/pylibs/twisted/internet/protocol.py
+++ /dev/null
@@ -1,674 +0,0 @@
-# -*- test-case-name: twisted.test.test_factories -*-
-#
-# Copyright (c) 2001-2008 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-Standard implementations of Twisted protocol-related interfaces.
-
-Start here if you are looking to write a new protocol implementation for
-Twisted. The Protocol class contains some introductory material.
-
-Maintainer: U{Itamar Shtull-Trauring<mailto:twisted@itamarst.org>}
-"""
-
-import random
-from zope.interface import implements
-
-# Twisted Imports
-from twisted.python import log, failure, components
-from twisted.internet import interfaces, error, defer
-
-
-class Factory:
- """This is a factory which produces protocols.
-
- By default, buildProtocol will create a protocol of the class given in
- self.protocol.
- """
-
- implements(interfaces.IProtocolFactory)
-
- # put a subclass of Protocol here:
- protocol = None
-
- numPorts = 0
- noisy = True
-
- def doStart(self):
- """Make sure startFactory is called.
-
- Users should not call this function themselves!
- """
- if not self.numPorts:
- if self.noisy:
- log.msg("Starting factory %r" % self)
- self.startFactory()
- self.numPorts = self.numPorts + 1
-
- def doStop(self):
- """Make sure stopFactory is called.
-
- Users should not call this function themselves!
- """
- if self.numPorts == 0:
- # this shouldn't happen, but does sometimes and this is better
- # than blowing up in assert as we did previously.
- return
- self.numPorts = self.numPorts - 1
- if not self.numPorts:
- if self.noisy:
- log.msg("Stopping factory %r" % self)
- self.stopFactory()
-
- def startFactory(self):
- """This will be called before I begin listening on a Port or Connector.
-
- It will only be called once, even if the factory is connected
- to multiple ports.
-
- This can be used to perform 'unserialization' tasks that
- are best put off until things are actually running, such
- as connecting to a database, opening files, etcetera.
- """
-
- def stopFactory(self):
- """This will be called before I stop listening on all Ports/Connectors.
-
- This can be overridden to perform 'shutdown' tasks such as disconnecting
- database connections, closing files, etc.
-
- 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
-
-
-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}
- """
-
- def clientConnectionLost(self, connector, reason):
- """Called when an established connection is lost.
-
- It may be useful to call connector.connect() - this will reconnect.
-
- @type reason: L{twisted.python.failure.Failure}
- """
-
-
-class _InstanceFactory(ClientFactory):
- """Factory used by ClientCreator."""
-
- noisy = False
-
- def __init__(self, reactor, instance, deferred):
- self.reactor = reactor
- self.instance = instance
- self.deferred = deferred
-
- def __repr__(self):
- return "<ClientCreator factory: %r>" % (self.instance, )
-
- def buildProtocol(self, addr):
- self.reactor.callLater(0, self.deferred.callback, self.instance)
- del self.deferred
- return self.instance
-
- def clientConnectionFailed(self, connector, reason):
- self.reactor.callLater(0, self.deferred.errback, reason)
- del self.deferred
-
-
-class ClientCreator:
- """Client connections that do not require a factory.
-
- The various connect* methods create a protocol instance using the given
- protocol class and arguments, and connect it, returning a Deferred of the
- resulting protocol instance.
-
- Useful for cases when we don't really need a factory. Mainly this
- is when there is no shared state between protocol instances, and no need
- to reconnect.
- """
-
- def __init__(self, reactor, protocolClass, *args, **kwargs):
- self.reactor = reactor
- self.protocolClass = protocolClass
- self.args = args
- self.kwargs = kwargs
-
- def connectTCP(self, host, port, timeout=30, bindAddress=None):
- """Connect to remote host, return Deferred of resulting protocol instance."""
- d = defer.Deferred()
- f = _InstanceFactory(self.reactor, self.protocolClass(*self.args, **self.kwargs), d)
- self.reactor.connectTCP(host, port, f, timeout=timeout, bindAddress=bindAddress)
- return d
-
- def connectUNIX(self, address, timeout = 30, checkPID=0):
- """Connect to Unix socket, return Deferred of resulting protocol instance."""
- d = defer.Deferred()
- f = _InstanceFactory(self.reactor, self.protocolClass(*self.args, **self.kwargs), d)
- self.reactor.connectUNIX(address, f, timeout = timeout, checkPID=checkPID)
- return d
-
- def connectSSL(self, host, port, contextFactory, timeout=30, bindAddress=None):
- """Connect to SSL server, return Deferred of resulting protocol instance."""
- d = defer.Deferred()
- f = _InstanceFactory(self.reactor, self.protocolClass(*self.args, **self.kwargs), d)
- self.reactor.connectSSL(host, port, f, contextFactory, timeout=timeout, bindAddress=bindAddress)
- return d
-
-
-class ReconnectingClientFactory(ClientFactory):
- """My clients auto-reconnect with an exponential back-off.
-
- Note that clients should call my resetDelay method after they have
- connected successfully.
-
- @ivar maxDelay: Maximum number of seconds between connection attempts.
- @ivar initialDelay: Delay for the first reconnection attempt.
- @ivar factor: a multiplicitive factor by which the delay grows
- @ivar jitter: percentage of randomness to introduce into the delay length
- to prevent stampeding.
- """
- maxDelay = 3600
- initialDelay = 1.0
- # Note: These highly sensitive factors have been precisely measured by
- # the National Institute of Science and Technology. Take extreme care
- # in altering them, or you may damage your Internet!
- factor = 2.7182818284590451 # (math.e)
- # Phi = 1.6180339887498948 # (Phi is acceptable for use as a
- # factor if e is too large for your application.)
- jitter = 0.11962656492 # molar Planck constant times c, Jule meter/mole
-
- delay = initialDelay
- retries = 0
- maxRetries = None
- _callID = None
- connector = None
-
- continueTrying = 1
-
- def clientConnectionFailed(self, connector, reason):
- if self.continueTrying:
- self.connector = connector
- self.retry()
-
- def clientConnectionLost(self, connector, unused_reason):
- if self.continueTrying:
- self.connector = connector
- self.retry()
-
- def retry(self, connector=None):
- """Have this connector connect again, after a suitable delay.
- """
- if not self.continueTrying:
- if self.noisy:
- log.msg("Abandoning %s on explicit request" % (connector,))
- return
-
- if connector is None:
- if self.connector is None:
- raise ValueError("no connector to retry")
- else:
- connector = self.connector
-
- self.retries += 1
- if self.maxRetries is not None and (self.retries > self.maxRetries):
- if self.noisy:
- log.msg("Abandoning %s after %d retries." %
- (connector, self.retries))
- return
-
- self.delay = min(self.delay * self.factor, self.maxDelay)
- if self.jitter:
- self.delay = random.normalvariate(self.delay,
- self.delay * self.jitter)
-
- if self.noisy:
- log.msg("%s will retry in %d seconds" % (connector, self.delay,))
- from twisted.internet import reactor
-
- def reconnector():
- self._callID = None
- connector.connect()
- self._callID = reactor.callLater(self.delay, reconnector)
-
- def stopTrying(self):
- """I put a stop to any attempt to reconnect in progress.
- """
- # ??? Is this function really stopFactory?
- if self._callID:
- self._callID.cancel()
- self._callID = None
- if self.connector:
- # Hopefully this doesn't just make clientConnectionFailed
- # retry again.
- try:
- self.connector.stopConnecting()
- except error.NotConnectingError:
- pass
- self.continueTrying = 0
-
- def resetDelay(self):
- """Call me after a successful connection to reset.
-
- I reset the delay and the retry counter.
- """
- self.delay = self.initialDelay
- self.retries = 0
- self._callID = None
- self.continueTrying = 1
-
-
- def __getstate__(self):
- """
- Remove all of the state which is mutated by connection attempts and
- failures, returning just the state which describes how reconnections
- should be attempted. This will make the unserialized instance
- behave just as this one did when it was first instantiated.
- """
- state = self.__dict__.copy()
- for key in ['connector', 'retries', 'delay',
- 'continueTrying', '_callID']:
- if key in state:
- del state[key]
- return state
-
-
-
-class ServerFactory(Factory):
- """Subclass this to indicate that your protocol.Factory is only usable for servers.
- """
-
-
-class BaseProtocol:
- """This is the abstract superclass of all protocols.
-
- If you are going to write a new protocol for Twisted, start here. The
- docstrings of this class explain how you can get started. Any protocol
- implementation, either client or server, should be a subclass of me.
-
- My API is quite simple. Implement dataReceived(data) to handle both
- event-based and synchronous input; output can be sent through the
- 'transport' attribute, which is to be an instance that implements
- L{twisted.internet.interfaces.ITransport}.
-
- Some subclasses exist already to help you write common types of protocols:
- see the L{twisted.protocols.basic} module for a few of them.
- """
-
- connected = 0
- transport = None
-
- def makeConnection(self, transport):
- """Make a connection to a transport and a server.
-
- This sets the 'transport' attribute of this Protocol, and calls the
- connectionMade() callback.
- """
- self.connected = 1
- self.transport = transport
- self.connectionMade()
-
- def connectionMade(self):
- """Called when a connection is made.
-
- This may be considered the initializer of the protocol, because
- it is called when the connection is completed. For clients,
- this is called once the connection to the server has been
- established; for servers, this is called after an accept() call
- stops blocking and a socket has been received. If you need to
- send any greeting or initial message, do it here.
- """
-
-connectionDone=failure.Failure(error.ConnectionDone())
-connectionDone.cleanFailure()
-
-
-class Protocol(BaseProtocol):
-
- implements(interfaces.IProtocol)
-
- def dataReceived(self, data):
- """Called whenever data is received.
-
- Use this method to translate to a higher-level message. Usually, some
- callback will be made upon the receipt of each complete protocol
- message.
-
- @param data: a string of indeterminate length. Please keep in mind
- that you will probably need to buffer some data, as partial
- (or multiple) protocol messages may be received! I recommend
- that unit tests for protocols call through to this method with
- differing chunk sizes, down to one byte at a time.
- """
-
- def connectionLost(self, reason=connectionDone):
- """Called when the connection is shut down.
-
- Clear any circular references here, and any external references
- to this Protocol. The connection has been closed.
-
- @type reason: L{twisted.python.failure.Failure}
- """
-
-
-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
-
-components.registerAdapter(ProtocolToConsumerAdapter, interfaces.IProtocol,
- interfaces.IConsumer)
-
-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
-
-components.registerAdapter(ConsumerToProtocolAdapter, interfaces.IConsumer,
- interfaces.IProtocol)
-
-class ProcessProtocol(BaseProtocol):
- """
- Base process protocol implementation which does simple dispatching for
- stdin, stdout, and stderr file descriptors.
- """
- implements(interfaces.IProcessProtocol)
-
- def childDataReceived(self, childFD, data):
- if childFD == 1:
- self.outReceived(data)
- elif childFD == 2:
- self.errReceived(data)
-
-
- def outReceived(self, data):
- """
- Some data was received from stdout.
- """
-
-
- def errReceived(self, data):
- """
- Some data was received from stderr.
- """
-
-
- def childConnectionLost(self, childFD):
- if childFD == 0:
- self.inConnectionLost()
- elif childFD == 1:
- self.outConnectionLost()
- elif childFD == 2:
- self.errConnectionLost()
-
-
- def inConnectionLost(self):
- """
- This will be called when stdin is closed.
- """
-
-
- def outConnectionLost(self):
- """
- This will be called when stdout is closed.
- """
-
-
- def errConnectionLost(self):
- """
- This will be called when stderr is closed.
- """
-
-
- def processEnded(self, reason):
- """
- This will be called when the subprocess is finished.
-
- @type reason: L{twisted.python.failure.Failure}
- """
-
-
-class AbstractDatagramProtocol:
- """
- Abstract protocol for datagram-oriented transports, e.g. IP, ICMP, ARP, UDP.
- """
-
- transport = None
- numPorts = 0
- noisy = True
-
- def __getstate__(self):
- d = self.__dict__.copy()
- d['transport'] = None
- return d
-
- def doStart(self):
- """Make sure startProtocol is called.
-
- This will be called by makeConnection(), users should not call it.
- """
- if not self.numPorts:
- if self.noisy:
- log.msg("Starting protocol %s" % self)
- self.startProtocol()
- self.numPorts = self.numPorts + 1
-
- def doStop(self):
- """Make sure stopProtocol is called.
-
- This will be called by the port, users should not call it.
- """
- assert self.numPorts > 0
- self.numPorts = self.numPorts - 1
- self.transport = None
- if not self.numPorts:
- if self.noisy:
- log.msg("Stopping protocol %s" % self)
- self.stopProtocol()
-
- def startProtocol(self):
- """Called when a transport is connected to this protocol.
-
- Will only be called once, even if multiple ports are connected.
- """
-
- def stopProtocol(self):
- """Called when the transport is disconnected.
-
- Will only be called once, after all ports are disconnected.
- """
-
- def makeConnection(self, transport):
- """Make a connection to a transport and a server.
-
- This sets the 'transport' attribute of this DatagramProtocol, and calls the
- doStart() callback.
- """
- assert self.transport == None
- self.transport = transport
- self.doStart()
-
- def datagramReceived(self, datagram, addr):
- """Called when a datagram is received.
-
- @param datagram: the string received from the transport.
- @param addr: tuple of source of datagram.
- """
-
-
-class DatagramProtocol(AbstractDatagramProtocol):
- """
- Protocol for datagram-oriented transport, e.g. UDP.
-
- @type transport: C{NoneType} or
- L{IUDPTransport<twisted.internet.interfaces.IUDPTransport>} provider
- @ivar transport: The transport with which this protocol is associated,
- if it is associated with one.
- """
-
- def connectionRefused(self):
- """Called due to error from write in connected mode.
-
- Note this is a result of ICMP message generated by *previous*
- write.
- """
-
-
-class ConnectedDatagramProtocol(DatagramProtocol):
- """Protocol for connected datagram-oriented transport.
-
- No longer necessary for UDP.
- """
-
- def datagramReceived(self, datagram):
- """Called when a datagram is received.
-
- @param datagram: the string received from the transport.
- """
-
- def connectionFailed(self, failure):
- """Called if connecting failed.
-
- Usually this will be due to a DNS lookup failure.
- """
-
-
-
-class FileWrapper:
- """A wrapper around a file-like object to make it behave as a Transport.
-
- This doesn't actually stream the file to the attached protocol,
- and is thus useful mainly as a utility for debugging protocols.
- """
-
- implements(interfaces.ITransport)
-
- closed = 0
- disconnecting = 0
- producer = None
- streamingProducer = 0
-
- def __init__(self, file):
- self.file = file
-
- def write(self, data):
- try:
- self.file.write(data)
- except:
- self.handleException()
- # self._checkProducer()
-
- def _checkProducer(self):
- # Cheating; this is called at "idle" times to allow producers to be
- # found and dealt with
- if self.producer:
- self.producer.resumeProducing()
-
- def registerProducer(self, producer, streaming):
- """From abstract.FileDescriptor
- """
- self.producer = producer
- self.streamingProducer = streaming
- if not streaming:
- producer.resumeProducing()
-
- def unregisterProducer(self):
- self.producer = None
-
- def stopConsuming(self):
- self.unregisterProducer()
- self.loseConnection()
-
- def writeSequence(self, iovec):
- self.write("".join(iovec))
-
- def loseConnection(self):
- self.closed = 1
- try:
- self.file.close()
- except (IOError, OSError):
- self.handleException()
-
- def getPeer(self):
- # XXX: According to ITransport, this should return an IAddress!
- return 'file', 'file'
-
- def getHost(self):
- # XXX: According to ITransport, this should return an IAddress!
- return 'file'
-
- def handleException(self):
- pass
-
- def resumeProducing(self):
- # Never sends data anyways
- pass
-
- def pauseProducing(self):
- # Never sends data anyways
- pass
-
- def stopProducing(self):
- self.loseConnection()
-
-
-__all__ = ["Factory", "ClientFactory", "ReconnectingClientFactory", "connectionDone",
- "Protocol", "ProcessProtocol", "FileWrapper", "ServerFactory",
- "AbstractDatagramProtocol", "DatagramProtocol", "ConnectedDatagramProtocol",
- "ClientCreator"]
diff --git a/tools/buildbot/pylibs/twisted/internet/pyuisupport.py b/tools/buildbot/pylibs/twisted/internet/pyuisupport.py
deleted file mode 100644
index a845e19..0000000
--- a/tools/buildbot/pylibs/twisted/internet/pyuisupport.py
+++ /dev/null
@@ -1,37 +0,0 @@
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-This module integrates PyUI with twisted.internet's mainloop.
-
-Maintainer: U{Jp Calderone<mailto:exarkun@twistedmatrix.com>}
-
-See doc/examples/pyuidemo.py for example usage.
-"""
-
-# System imports
-import pyui
-
-def _guiUpdate(reactor, delay):
- pyui.draw()
- if pyui.update() == 0:
- pyui.quit()
- reactor.stop()
- else:
- reactor.callLater(delay, _guiUpdate, reactor, delay)
-
-
-def install(ms=10, reactor=None, args=(), kw={}):
- """
- Schedule PyUI's display to be updated approximately every C{ms}
- milliseconds, and initialize PyUI with the specified arguments.
- """
- d = pyui.init(*args, **kw)
-
- if reactor is None:
- from twisted.internet import reactor
- _guiUpdate(reactor, ms / 1000.0)
- return d
-
-__all__ = ["install"]
diff --git a/tools/buildbot/pylibs/twisted/internet/qtreactor.py b/tools/buildbot/pylibs/twisted/internet/qtreactor.py
deleted file mode 100644
index 7754ad8..0000000
--- a/tools/buildbot/pylibs/twisted/internet/qtreactor.py
+++ /dev/null
@@ -1,15 +0,0 @@
-try:
- # 'import qtreactor' would have imported this file instead of the
- # top-level qtreactor. __import__ does the right thing
- # (kids, don't repeat this at home)
- install = __import__('qtreactor').install
-except ImportError:
- from twisted.plugins.qtreactor_stub import errorMessage
- raise ImportError(errorMessage)
-else:
- import warnings
- warnings.warn("Please use qtreactor instead of twisted.internet.qtreactor",
- category=DeprecationWarning)
-
-__all__ = ['install']
-
diff --git a/tools/buildbot/pylibs/twisted/internet/reactor.py b/tools/buildbot/pylibs/twisted/internet/reactor.py
deleted file mode 100644
index 1fa2861..0000000
--- a/tools/buildbot/pylibs/twisted/internet/reactor.py
+++ /dev/null
@@ -1,12 +0,0 @@
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-See twisted.internet.interfaces.IReactor*.
-"""
-import sys
-del sys.modules['twisted.internet.reactor']
-#from twisted.python import log
-#log.msg("Installing SelectReactor, since unspecified.")
-from twisted.internet import selectreactor
-selectreactor.install()
diff --git a/tools/buildbot/pylibs/twisted/internet/selectreactor.py b/tools/buildbot/pylibs/twisted/internet/selectreactor.py
deleted file mode 100644
index 0d79e55..0000000
--- a/tools/buildbot/pylibs/twisted/internet/selectreactor.py
+++ /dev/null
@@ -1,204 +0,0 @@
-# -*- test-case-name: twisted.test.test_internet -*-
-# Copyright (c) 2001-2007 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-Select reactor
-
-Maintainer: U{Itamar Shtull-Trauring<mailto:twisted@itamarst.org>}
-"""
-
-from time import sleep
-import sys
-import select
-from errno import EINTR, EBADF
-
-from zope.interface import implements
-
-from twisted.internet.interfaces import IReactorFDSet
-from twisted.internet import error
-from twisted.internet import posixbase
-from twisted.python import log
-from twisted.python.runtime import platformType
-
-
-def win32select(r, w, e, timeout=None):
- """Win32 select wrapper."""
- if not (r or w):
- # windows select() exits immediately when no sockets
- if timeout is None:
- timeout = 0.01
- else:
- timeout = min(timeout, 0.001)
- sleep(timeout)
- return [], [], []
- # windows doesn't process 'signals' inside select(), so we set a max
- # time or ctrl-c will never be recognized
- if timeout is None or timeout > 0.5:
- timeout = 0.5
- r, w, e = select.select(r, w, w, timeout)
- return r, w + e, []
-
-if platformType == "win32":
- _select = win32select
-else:
- _select = select.select
-
-# Exceptions that doSelect might return frequently
-_NO_FILENO = error.ConnectionFdescWentAway('Handler has no fileno method')
-_NO_FILEDESC = error.ConnectionFdescWentAway('Filedescriptor went away')
-
-class SelectReactor(posixbase.PosixReactorBase):
- """
- A select() based reactor - runs on all POSIX platforms and on Win32.
-
- @ivar _reads: A dictionary mapping L{FileDescriptor} instances to arbitrary
- values (this is essentially a set). Keys in this dictionary will be
- checked for read events.
-
- @ivar _writes: A dictionary mapping L{FileDescriptor} instances to
- arbitrary values (this is essentially a set). Keys in this dictionary
- will be checked for writability.
- """
- implements(IReactorFDSet)
-
- def __init__(self):
- """
- Initialize file descriptor tracking dictionaries and the base class.
- """
- self._reads = {}
- self._writes = {}
- posixbase.PosixReactorBase.__init__(self)
-
-
- def _preenDescriptors(self):
- log.msg("Malformed file descriptor found. Preening lists.")
- readers = self._reads.keys()
- writers = self._writes.keys()
- self._reads.clear()
- self._writes.clear()
- for selDict, selList in ((self._reads, readers),
- (self._writes, writers)):
- for selectable in selList:
- try:
- select.select([selectable], [selectable], [selectable], 0)
- except Exception, e:
- log.msg("bad descriptor %s" % selectable)
- self._disconnectSelectable(selectable, e, False)
- else:
- selDict[selectable] = 1
-
-
- def doSelect(self, timeout):
- """
- Run one iteration of the I/O monitor loop.
-
- This will run all selectables who had input or output readiness
- waiting for them.
- """
- while 1:
- try:
- r, w, ignored = _select(self._reads.keys(),
- self._writes.keys(),
- [], timeout)
- break
- except ValueError, ve:
- # Possibly a file descriptor has gone negative?
- log.err()
- self._preenDescriptors()
- except TypeError, te:
- # Something *totally* invalid (object w/o fileno, non-integral
- # result) was passed
- log.err()
- self._preenDescriptors()
- except (select.error, IOError), se:
- # select(2) encountered an error
- if se.args[0] in (0, 2):
- # windows does this if it got an empty list
- if (not self._reads) and (not self._writes):
- return
- else:
- raise
- elif se.args[0] == EINTR:
- return
- elif se.args[0] == EBADF:
- self._preenDescriptors()
- else:
- # OK, I really don't know what's going on. Blow up.
- raise
- _drdw = self._doReadOrWrite
- _logrun = log.callWithLogger
- for selectables, method, fdset in ((r, "doRead", self._reads),
- (w,"doWrite", self._writes)):
- for selectable in selectables:
- # if this was disconnected in another thread, kill it.
- # ^^^^ --- what the !@#*? serious! -exarkun
- if selectable not in fdset:
- continue
- # This for pausing input when we're not ready for more.
- _logrun(selectable, _drdw, selectable, method, dict)
-
- doIteration = doSelect
-
- def _doReadOrWrite(self, selectable, method, dict):
- try:
- why = getattr(selectable, method)()
- handfn = getattr(selectable, 'fileno', None)
- if not handfn:
- why = _NO_FILENO
- elif handfn() == -1:
- why = _NO_FILEDESC
- except:
- why = sys.exc_info()[1]
- log.err()
- if why:
- self._disconnectSelectable(selectable, why, method=="doRead")
-
- def addReader(self, reader):
- """
- Add a FileDescriptor for notification of data available to read.
- """
- self._reads[reader] = 1
-
- def addWriter(self, writer):
- """
- Add a FileDescriptor for notification of data available to write.
- """
- self._writes[writer] = 1
-
- def removeReader(self, reader):
- """
- Remove a Selectable for notification of data available to read.
- """
- if reader in self._reads:
- del self._reads[reader]
-
- def removeWriter(self, writer):
- """
- Remove a Selectable for notification of data available to write.
- """
- if writer in self._writes:
- del self._writes[writer]
-
- def removeAll(self):
- return self._removeAll(self._reads, self._writes)
-
-
- def getReaders(self):
- return self._reads.keys()
-
-
- def getWriters(self):
- return self._writes.keys()
-
-
-
-def install():
- """Configure the twisted mainloop to be run using the select() reactor.
- """
- reactor = SelectReactor()
- from twisted.internet.main import installReactor
- installReactor(reactor)
-
-__all__ = ['install']
diff --git a/tools/buildbot/pylibs/twisted/internet/serialport.py b/tools/buildbot/pylibs/twisted/internet/serialport.py
deleted file mode 100644
index 6ac58ae..0000000
--- a/tools/buildbot/pylibs/twisted/internet/serialport.py
+++ /dev/null
@@ -1,65 +0,0 @@
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-Serial Port Protocol
-"""
-
-# system imports
-import os, sys
-
-# all of them require pyserial at the moment, so check that first
-import serial
-from serial import PARITY_NONE, PARITY_EVEN, PARITY_ODD
-from serial import STOPBITS_ONE, STOPBITS_TWO
-from serial import FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS
-
-# common code for serial ports
-class BaseSerialPort:
- def setBaudRate(self, baudrate):
- if hasattr(self._serial, "setBaudrate"):
- self._serial.setBaudrate(baudrate)
- else:
- self._serial.setBaudRate(baudrate)
-
- def inWaiting(self):
- return self._serial.inWaiting()
-
- def flushInput(self):
- self._serial.flushInput()
-
- def flushOutput(self):
- self._serial.flushOutput()
-
- def sendBreak(self):
- self._serial.sendBreak()
-
- def getDSR(self):
- return self._serial.getDSR()
-
- def getCD(self):
- return self._serial.getCD()
-
- def getRI(self):
- return self._serial.getRI()
-
- def getCTS(self):
- return self._serial.getCTS()
-
- def setDTR(self, on = 1):
- self._serial.setDTR(on)
-
- def setRTS(self, on = 1):
- self._serial.setRTS(on)
-
-class SerialPort(BaseSerialPort):
- pass
-
-# replace SerialPort with appropriate serial port
-if os.name == 'posix':
- from twisted.internet._posixserialport import SerialPort
-elif os.name == 'java':
- from twisted.internet._javaserialport import SerialPort
-elif sys.platform == 'win32':
- from twisted.internet._win32serialport import SerialPort
diff --git a/tools/buildbot/pylibs/twisted/internet/ssl.py b/tools/buildbot/pylibs/twisted/internet/ssl.py
deleted file mode 100644
index 23bd1e9..0000000
--- a/tools/buildbot/pylibs/twisted/internet/ssl.py
+++ /dev/null
@@ -1,205 +0,0 @@
-# -*- test-case-name: twisted.test.test_ssl -*-
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-SSL transport. Requires PyOpenSSL (http://pyopenssl.sf.net).
-
-SSL connections require a ContextFactory so they can create SSL contexts.
-End users should only use the ContextFactory classes directly - for SSL
-connections use the reactor.connectSSL/listenSSL and so on, as documented
-in IReactorSSL.
-
-All server context factories should inherit from ContextFactory, and all
-client context factories should inherit from ClientContextFactory. At the
-moment this is not enforced, but in the future it might be.
-
-Future Plans:
- - split module so reactor-specific classes are in a separate module
- - support for switching TCP into SSL
- - more options
-
-Maintainer: U{Itamar Shtull-Trauring<mailto:twisted@itamarst.org>}
-"""
-
-# If something goes wrong, most notably an OpenSSL import failure,
-# sys.modules['twisted.internet.ssl'] will be bound to a partially
-# initialized module object. This is wacko, but we will take advantage
-# of it to publish whether or not SSL is available.
-# See the end of this module for the other half of this solution.
-
-# The correct idiom to import this module is thus:
-
-# try:
-# from twisted.internet import ssl
-# except ImportError:
-# # happens the first time the interpreter tries to import it
-# ssl = None
-# if ssl and not ssl.supported:
-# # happens second and later times
-# ssl = None
-
-supported = False
-
-# System imports
-from OpenSSL import SSL
-from zope.interface import implements, implementsOnly, implementedBy
-
-# sibling imports
-import tcp, interfaces
-
-# Twisted imports
-from twisted.internet import base, address
-
-
-class ContextFactory:
- """A factory for SSL context objects, for server SSL connections."""
-
- isClient = 0
-
- def getContext(self):
- """Return a SSL.Context object. override in subclasses."""
- raise NotImplementedError
-
-
-class DefaultOpenSSLContextFactory(ContextFactory):
-
- def __init__(self, privateKeyFileName, certificateFileName,
- sslmethod=SSL.SSLv23_METHOD):
- """
- @param privateKeyFileName: Name of a file containing a private key
- @param certificateFileName: Name of a file containing a certificate
- @param sslmethod: The SSL method to use
- """
- self.privateKeyFileName = privateKeyFileName
- self.certificateFileName = certificateFileName
- self.sslmethod = sslmethod
- self.cacheContext()
-
- def cacheContext(self):
- ctx = SSL.Context(self.sslmethod)
- ctx.use_certificate_file(self.certificateFileName)
- ctx.use_privatekey_file(self.privateKeyFileName)
- self._context = ctx
-
- def __getstate__(self):
- d = self.__dict__.copy()
- del d['_context']
- return d
-
- def __setstate__(self, state):
- self.__dict__ = state
- self.cacheContext()
-
- def getContext(self):
- """Create an SSL context.
- """
- return self._context
-
-
-class ClientContextFactory:
- """A context factory for SSL clients."""
-
- isClient = 1
- method = SSL.SSLv3_METHOD
-
- def getContext(self):
- return SSL.Context(self.method)
-
-
-class Client(tcp.Client):
- """I am an SSL client."""
-
- implementsOnly(interfaces.ISSLTransport,
- *[i for i in implementedBy(tcp.Client) if i != interfaces.ITLSTransport])
-
- def __init__(self, host, port, bindAddress, ctxFactory, connector, reactor=None):
- # tcp.Client.__init__ depends on self.ctxFactory being set
- self.ctxFactory = ctxFactory
- tcp.Client.__init__(self, host, port, bindAddress, connector, reactor)
-
- 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)
-
-
-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 Port(tcp.Port):
- """I am an SSL port."""
- _socketShutdownMethod = 'sock_shutdown'
-
- transport = Server
-
- def __init__(self, port, factory, ctxFactory, backlog=50, interface='', reactor=None):
- tcp.Port.__init__(self, port, factory, backlog, interface, reactor)
- self.ctxFactory = ctxFactory
-
- def createInternetSocket(self):
- """(internal) create an SSL socket
- """
- sock = tcp.Port.createInternetSocket(self)
- return SSL.Connection(self.ctxFactory.getContext(), sock)
-
- def _preMakeConnection(self, transport):
- # *Don't* call startTLS here
- # The transport already has the SSL.Connection object from above
- transport._startTLS()
- return tcp.Port._preMakeConnection(self, transport)
-
-
-class Connector(base.BaseConnector):
- def __init__(self, host, port, factory, contextFactory, timeout, bindAddress, reactor=None):
- self.host = host
- self.port = port
- self.bindAddress = bindAddress
- self.contextFactory = contextFactory
- base.BaseConnector.__init__(self, factory, timeout, reactor)
-
- def _makeTransport(self):
- return Client(self.host, self.port, self.bindAddress, self.contextFactory, self, self.reactor)
-
- def getDestination(self):
- return address.IPv4Address('TCP', self.host, self.port, 'SSL')
-
-from twisted.internet._sslverify import DistinguishedName, DN, Certificate
-from twisted.internet._sslverify import CertificateRequest, PrivateCertificate
-from twisted.internet._sslverify import KeyPair
-from twisted.internet._sslverify import OpenSSLCertificateOptions as CertificateOptions
-
-__all__ = [
- "ContextFactory", "DefaultOpenSSLContextFactory", "ClientContextFactory",
-
- 'DistinguishedName', 'DN',
- 'Certificate', 'CertificateRequest', 'PrivateCertificate',
- 'KeyPair',
- 'CertificateOptions',
- ]
-
-supported = True
diff --git a/tools/buildbot/pylibs/twisted/internet/stdio.py b/tools/buildbot/pylibs/twisted/internet/stdio.py
deleted file mode 100644
index b10766e..0000000
--- a/tools/buildbot/pylibs/twisted/internet/stdio.py
+++ /dev/null
@@ -1,31 +0,0 @@
-# -*- test-case-name: twisted.test.test_process.ProcessTestCase.testStdio -*-
-
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Standard input/out/err support.
-
-This module exposes one name, StandardIO, which is a factory that takes an
-IProtocol provider as an argument. It connects that protocol to standard input
-and output on the current process.
-
-It should work on any UNIX and also on Win32 (with some caveats: due to
-platform limitations, it will perform very poorly on Win32).
-
-Future Plans::
-
- support for stderr, perhaps
- Rewrite to use the reactor instead of an ad-hoc mechanism for connecting
- protocols to transport.
-
-
-Maintainer: U{James Y Knight <mailto:foom@fuhm.net>}
-"""
-
-from twisted.python.runtime import platform
-
-if platform.isWindows():
- from twisted.internet._win32stdio import StandardIO
-else:
- from twisted.internet._posixstdio import StandardIO
diff --git a/tools/buildbot/pylibs/twisted/internet/task.py b/tools/buildbot/pylibs/twisted/internet/task.py
deleted file mode 100644
index 526d555..0000000
--- a/tools/buildbot/pylibs/twisted/internet/task.py
+++ /dev/null
@@ -1,420 +0,0 @@
-# -*- test-case-name: twisted.test.test_task -*-
-# Copyright (c) 2001-2007 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Scheduling utility methods and classes.
-
-@author: U{Jp Calderone<mailto:exarkun@twistedmatrix.com>}
-"""
-
-__metaclass__ = type
-
-import time
-
-from zope.interface import implements
-
-from twisted.python import reflect
-
-from twisted.internet import base, defer
-from twisted.internet.interfaces import IReactorTime
-
-
-class LoopingCall:
- """Call a function repeatedly.
-
- If C{f} returns a deferred, rescheduling will not take place until the
- deferred has fired. The result value is ignored.
-
- @ivar f: The function to call.
- @ivar a: A tuple of arguments to pass the function.
- @ivar kw: A dictionary of keyword arguments to pass to the function.
- @ivar clock: A provider of
- L{twisted.internet.interfaces.IReactorTime}. The default is
- L{twisted.internet.reactor}. Feel free to set this to
- something else, but it probably ought to be set *before*
- calling L{start}.
-
- @type _lastTime: C{float}
- @ivar _lastTime: The time at which this instance most recently scheduled
- itself to run.
- """
-
- call = None
- running = False
- deferred = None
- interval = None
- _lastTime = 0.0
- starttime = None
-
- def __init__(self, f, *a, **kw):
- self.f = f
- self.a = a
- self.kw = kw
- from twisted.internet import reactor
- self.clock = reactor
-
-
- def start(self, interval, now=True):
- """Start running function every interval seconds.
-
- @param interval: The number of seconds between calls. May be
- less than one. Precision will depend on the underlying
- platform, the available hardware, and the load on the system.
-
- @param now: If True, run this call right now. Otherwise, wait
- until the interval has elapsed before beginning.
-
- @return: A Deferred whose callback will be invoked with
- C{self} when C{self.stop} is called, or whose errback will be
- invoked when the function raises an exception or returned a
- deferred that has its errback invoked.
- """
- assert not self.running, ("Tried to start an already running "
- "LoopingCall.")
- if interval < 0:
- raise ValueError, "interval must be >= 0"
- self.running = True
- d = self.deferred = defer.Deferred()
- self.starttime = self.clock.seconds()
- self._lastTime = self.starttime
- self.interval = interval
- if now:
- self()
- else:
- self._reschedule()
- return d
-
- def stop(self):
- """Stop running function.
- """
- assert self.running, ("Tried to stop a LoopingCall that was "
- "not running.")
- self.running = False
- if self.call is not None:
- self.call.cancel()
- self.call = None
- d, self.deferred = self.deferred, None
- d.callback(self)
-
- def __call__(self):
- def cb(result):
- if self.running:
- self._reschedule()
- else:
- d, self.deferred = self.deferred, None
- d.callback(self)
-
- def eb(failure):
- self.running = False
- d, self.deferred = self.deferred, None
- d.errback(failure)
-
- self.call = None
- d = defer.maybeDeferred(self.f, *self.a, **self.kw)
- d.addCallback(cb)
- d.addErrback(eb)
-
-
- def _reschedule(self):
- """
- Schedule the next iteration of this looping call.
- """
- if self.interval == 0:
- self.call = self.clock.callLater(0, self)
- return
-
- currentTime = self.clock.seconds()
- # Find how long is left until the interval comes around again.
- untilNextTime = (self._lastTime - currentTime) % self.interval
- # Make sure it is in the future, in case more than one interval worth
- # of time passed since the previous call was made.
- nextTime = max(
- self._lastTime + self.interval, currentTime + untilNextTime)
- # If the interval falls on the current time exactly, skip it and
- # schedule the call for the next interval.
- if nextTime == currentTime:
- nextTime += self.interval
- self._lastTime = nextTime
- self.call = self.clock.callLater(nextTime - currentTime, self)
-
-
- def __repr__(self):
- if hasattr(self.f, 'func_name'):
- func = self.f.func_name
- if hasattr(self.f, 'im_class'):
- func = self.f.im_class.__name__ + '.' + func
- else:
- func = reflect.safe_repr(self.f)
-
- return 'LoopingCall<%r>(%s, *%s, **%s)' % (
- self.interval, func, reflect.safe_repr(self.a),
- reflect.safe_repr(self.kw))
-
-
-
-class SchedulerStopped(Exception):
- """
- The operation could not complete because the scheduler was stopped in
- progress or was already stopped.
- """
-
-
-
-class _Timer(object):
- MAX_SLICE = 0.01
- def __init__(self):
- self.end = time.time() + self.MAX_SLICE
-
-
- def __call__(self):
- return time.time() >= self.end
-
-
-
-_EPSILON = 0.00000001
-def _defaultScheduler(x):
- from twisted.internet import reactor
- return reactor.callLater(_EPSILON, x)
-
-
-
-class Cooperator(object):
- """
- Cooperative task scheduler.
- """
-
- def __init__(self,
- terminationPredicateFactory=_Timer,
- scheduler=_defaultScheduler,
- started=True):
- """
- Create a scheduler-like object to which iterators may be added.
-
- @param terminationPredicateFactory: A no-argument callable which will
- be invoked at the beginning of each step and should return a
- no-argument callable which will return False when the step should be
- terminated. The default factory is time-based and allows iterators to
- run for 1/100th of a second at a time.
-
- @param scheduler: A one-argument callable which takes a no-argument
- callable and should invoke it at some future point. This will be used
- to schedule each step of this Cooperator.
-
- @param started: A boolean which indicates whether iterators should be
- stepped as soon as they are added, or if they will be queued up until
- L{Cooperator.start} is called.
- """
- self.iterators = []
- self._metarator = iter(())
- self._terminationPredicateFactory = terminationPredicateFactory
- self._scheduler = scheduler
- self._delayedCall = None
- self._stopped = False
- self._started = started
-
-
- def coiterate(self, iterator, doneDeferred=None):
- """
- Add an iterator to the list of iterators I am currently running.
-
- @return: a Deferred that will fire when the iterator finishes.
- """
- if doneDeferred is None:
- doneDeferred = defer.Deferred()
- if self._stopped:
- doneDeferred.errback(SchedulerStopped())
- return doneDeferred
- self.iterators.append((iterator, doneDeferred))
- self._reschedule()
- return doneDeferred
-
-
- def _tasks(self):
- terminator = self._terminationPredicateFactory()
- while self.iterators:
- for i in self._metarator:
- yield i
- if terminator():
- return
- self._metarator = iter(self.iterators)
-
-
- def _tick(self):
- """
- Run one scheduler tick.
- """
- self._delayedCall = None
- for taskObj in self._tasks():
- iterator, doneDeferred = taskObj
- try:
- result = iterator.next()
- except StopIteration:
- self.iterators.remove(taskObj)
- doneDeferred.callback(iterator)
- except:
- self.iterators.remove(taskObj)
- doneDeferred.errback()
- else:
- if isinstance(result, defer.Deferred):
- self.iterators.remove(taskObj)
- def cbContinue(result, taskObj=taskObj):
- self.coiterate(*taskObj)
- result.addCallbacks(cbContinue, doneDeferred.errback)
- self._reschedule()
-
-
- _mustScheduleOnStart = False
- def _reschedule(self):
- if not self._started:
- self._mustScheduleOnStart = True
- return
- if self._delayedCall is None and self.iterators:
- self._delayedCall = self._scheduler(self._tick)
-
-
- def start(self):
- """
- Begin scheduling steps.
- """
- self._stopped = False
- self._started = True
- if self._mustScheduleOnStart:
- del self._mustScheduleOnStart
- self._reschedule()
-
-
- def stop(self):
- """
- Stop scheduling steps. Errback the completion Deferreds of all
- iterators which have been added and forget about them.
- """
- self._stopped = True
- for iterator, doneDeferred in self.iterators:
- doneDeferred.errback(SchedulerStopped())
- self.iterators = []
- if self._delayedCall is not None:
- self._delayedCall.cancel()
- self._delayedCall = None
-
-
-
-_theCooperator = Cooperator()
-def coiterate(iterator):
- """
- Cooperatively iterate over the given iterator, dividing runtime between it
- and all other iterators which have been passed to this function and not yet
- exhausted.
- """
- return _theCooperator.coiterate(iterator)
-
-
-
-class Clock:
- """
- Provide a deterministic, easily-controlled implementation of
- L{IReactorTime.callLater}. This is commonly useful for writing
- deterministic unit tests for code which schedules events using this API.
- """
- implements(IReactorTime)
-
- rightNow = 0.0
-
- def __init__(self):
- self.calls = []
-
- def seconds(self):
- """
- Pretend to be time.time(). This is used internally when an operation
- such as L{IDelayedCall.reset} needs to determine a a time value
- relative to the current time.
-
- @rtype: C{float}
- @return: The time which should be considered the current time.
- """
- return self.rightNow
-
-
- def callLater(self, when, what, *a, **kw):
- """
- See L{twisted.internet.interfaces.IReactorTime.callLater}.
- """
- dc = base.DelayedCall(self.seconds() + when,
- what, a, kw,
- self.calls.remove,
- lambda c: None,
- self.seconds)
- self.calls.append(dc)
- self.calls.sort(lambda a, b: cmp(a.getTime(), b.getTime()))
- return dc
-
- def getDelayedCalls(self):
- """
- See L{twisted.internet.interfaces.IReactorTime.getDelayedCalls}
- """
- return self.calls
-
- def advance(self, amount):
- """
- Move time on this clock forward by the given amount and run whatever
- pending calls should be run.
-
- @type amount: C{float}
- @param amount: The number of seconds which to advance this clock's
- time.
- """
- self.rightNow += amount
- while self.calls and self.calls[0].getTime() <= self.seconds():
- call = self.calls.pop(0)
- call.called = 1
- call.func(*call.args, **call.kw)
-
-
- def pump(self, timings):
- """
- Advance incrementally by the given set of times.
-
- @type timings: iterable of C{float}
- """
- for amount in timings:
- self.advance(amount)
-
-
-def deferLater(clock, delay, callable, *args, **kw):
- """
- Call the given function after a certain period of time has passed.
-
- @type clock: L{IReactorTime} provider
- @param clock: The object which will be used to schedule the delayed
- call.
-
- @type delay: C{float} or C{int}
- @param delay: The number of seconds to wait before calling the function.
-
- @param callable: The object to call after the delay.
-
- @param *args: The positional arguments to pass to C{callable}.
-
- @param **kw: The keyword arguments to pass to C{callable}.
-
- @rtype: L{defer.Deferred}
-
- @return: A deferred that fires with the result of the callable when the
- specified time has elapsed.
- """
- d = defer.Deferred()
- d.addCallback(lambda ignored: callable(*args, **kw))
- clock.callLater(delay, d.callback, None)
- return d
-
-
-
-__all__ = [
- 'LoopingCall',
-
- 'Clock',
-
- 'SchedulerStopped', 'Cooperator', 'coiterate',
-
- 'deferLater',
- ]
diff --git a/tools/buildbot/pylibs/twisted/internet/tcp.py b/tools/buildbot/pylibs/twisted/internet/tcp.py
deleted file mode 100644
index 29852ae..0000000
--- a/tools/buildbot/pylibs/twisted/internet/tcp.py
+++ /dev/null
@@ -1,894 +0,0 @@
-# -*- test-case-name: twisted.test.test_tcp -*-
-# Copyright (c) 2001-2007 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Various asynchronous TCP/IP classes.
-
-End users shouldn't use this module directly - use the reactor APIs instead.
-
-Maintainer: U{Itamar Shtull-Trauring<mailto:twisted@itamarst.org>}
-"""
-
-
-# System Imports
-import os
-import types
-import socket
-import sys
-import operator
-import warnings
-
-try:
- import fcntl
-except ImportError:
- fcntl = None
-from zope.interface import implements, classImplements
-
-try:
- from OpenSSL import SSL
-except ImportError:
- SSL = None
-
-from twisted.python.runtime import platformType
-
-
-if platformType == 'win32':
- # no such thing as WSAEPERM or error code 10001 according to winsock.h or MSDN
- EPERM = object()
- from errno import WSAEINVAL as EINVAL
- from errno import WSAEWOULDBLOCK as EWOULDBLOCK
- from errno import WSAEINPROGRESS as EINPROGRESS
- from errno import WSAEALREADY as EALREADY
- from errno import WSAECONNRESET as ECONNRESET
- from errno import WSAEISCONN as EISCONN
- from errno import WSAENOTCONN as ENOTCONN
- from errno import WSAEINTR as EINTR
- from errno import WSAENOBUFS as ENOBUFS
- from errno import WSAEMFILE as EMFILE
- # No such thing as WSAENFILE, either.
- ENFILE = object()
- # Nor ENOMEM
- ENOMEM = object()
- EAGAIN = EWOULDBLOCK
- from errno import WSAECONNRESET as ECONNABORTED
-
- from twisted.python.win32 import formatError as strerror
-else:
- from errno import EPERM
- from errno import EINVAL
- from errno import EWOULDBLOCK
- from errno import EINPROGRESS
- from errno import EALREADY
- from errno import ECONNRESET
- from errno import EISCONN
- from errno import ENOTCONN
- from errno import EINTR
- from errno import ENOBUFS
- from errno import EMFILE
- from errno import ENFILE
- from errno import ENOMEM
- from errno import EAGAIN
- from errno import ECONNABORTED
-
- from os import strerror
-
-from errno import errorcode
-
-# Twisted Imports
-from twisted.internet import defer, base, address
-from twisted.python import log, failure, reflect
-from twisted.python.util import unsignedID
-from twisted.internet.error import CannotListenError
-from twisted.internet import abstract, main, interfaces, error
-
-
-
-class _SocketCloser:
- _socketShutdownMethod = 'shutdown'
-
- def _closeSocket(self):
- # socket.close() doesn't *really* close if there's another reference
- # to it in the TCP/IP stack, e.g. if it was was inherited by a
- # subprocess. And we really do want to close the connection. So we
- # use shutdown() instead, and then close() in order to release the
- # filedescriptor.
- skt = self.socket
- try:
- getattr(skt, self._socketShutdownMethod)(2)
- except socket.error:
- pass
- try:
- skt.close()
- except socket.error:
- pass
-
-class _TLSMixin:
- _socketShutdownMethod = 'sock_shutdown'
-
- writeBlockedOnRead = 0
- readBlockedOnWrite = 0
- _userWantRead = _userWantWrite = True
-
- def getPeerCertificate(self):
- return self.socket.get_peer_certificate()
-
- def doRead(self):
- if self.writeBlockedOnRead:
- self.writeBlockedOnRead = 0
- self._resetReadWrite()
- try:
- return Connection.doRead(self)
- except SSL.ZeroReturnError:
- return main.CONNECTION_DONE
- except SSL.WantReadError:
- return
- except SSL.WantWriteError:
- self.readBlockedOnWrite = 1
- Connection.startWriting(self)
- Connection.stopReading(self)
- return
- except SSL.SysCallError, (retval, desc):
- if ((retval == -1 and desc == 'Unexpected EOF')
- or retval > 0):
- return main.CONNECTION_LOST
- log.err()
- return main.CONNECTION_LOST
- except SSL.Error, e:
- return e
-
- def doWrite(self):
- # Retry disconnecting
- if self.disconnected:
- return self._postLoseConnection()
- if self._writeDisconnected:
- return self._closeWriteConnection()
-
- if self.readBlockedOnWrite:
- self.readBlockedOnWrite = 0
- self._resetReadWrite()
- return Connection.doWrite(self)
-
- def writeSomeData(self, data):
- try:
- return Connection.writeSomeData(self, data)
- except SSL.WantWriteError:
- return 0
- except SSL.WantReadError:
- self.writeBlockedOnRead = 1
- Connection.stopWriting(self)
- Connection.startReading(self)
- return 0
- except SSL.ZeroReturnError:
- return main.CONNECTION_LOST
- except SSL.SysCallError, e:
- if e[0] == -1 and data == "":
- # errors when writing empty strings are expected
- # and can be ignored
- return 0
- else:
- return main.CONNECTION_LOST
- except SSL.Error, e:
- return e
-
- def _postLoseConnection(self):
- """Gets called after loseConnection(), after buffered data is sent.
-
- We try to send an SSL shutdown alert, but if it doesn't work, retry
- when the socket is writable.
- """
- self.disconnected=1
- if hasattr(self.socket, 'set_shutdown'):
- self.socket.set_shutdown(SSL.RECEIVED_SHUTDOWN)
- return self._sendCloseAlert()
-
- _first=False
- def _sendCloseAlert(self):
- # Okay, *THIS* is a bit complicated.
-
- # Basically, the issue is, OpenSSL seems to not actually return
- # errors from SSL_shutdown. Therefore, the only way to
- # determine if the close notification has been sent is by
- # SSL_shutdown returning "done". However, it will not claim it's
- # done until it's both sent *and* received a shutdown notification.
-
- # I don't actually want to wait for a received shutdown
- # notification, though, so, I have to set RECEIVED_SHUTDOWN
- # before calling shutdown. Then, it'll return True once it's
- # *SENT* the shutdown.
-
- # However, RECEIVED_SHUTDOWN can't be left set, because then
- # reads will fail, breaking half close.
-
- # Also, since shutdown doesn't report errors, an empty write call is
- # done first, to try to detect if the connection has gone away.
- # (*NOT* an SSL_write call, because that fails once you've called
- # shutdown)
- try:
- os.write(self.socket.fileno(), '')
- except OSError, se:
- if se.args[0] in (EINTR, EWOULDBLOCK, ENOBUFS):
- return 0
- # Write error, socket gone
- return main.CONNECTION_LOST
-
- try:
- if hasattr(self.socket, 'set_shutdown'):
- laststate = self.socket.get_shutdown()
- self.socket.set_shutdown(laststate | SSL.RECEIVED_SHUTDOWN)
- done = self.socket.shutdown()
- if not (laststate & SSL.RECEIVED_SHUTDOWN):
- self.socket.set_shutdown(SSL.SENT_SHUTDOWN)
- else:
- #warnings.warn("SSL connection shutdown possibly unreliable, "
- # "please upgrade to ver 0.XX", category=UserWarning)
- self.socket.shutdown()
- done = True
- except SSL.Error, e:
- return e
-
- if done:
- self.stopWriting()
- # Note that this is tested for by identity below.
- return main.CONNECTION_DONE
- else:
- self.startWriting()
- return None
-
- def _closeWriteConnection(self):
- result = self._sendCloseAlert()
-
- if result is main.CONNECTION_DONE:
- return Connection._closeWriteConnection(self)
-
- return result
-
- def startReading(self):
- self._userWantRead = True
- if not self.readBlockedOnWrite:
- return Connection.startReading(self)
-
- def stopReading(self):
- self._userWantRead = False
- if not self.writeBlockedOnRead:
- return Connection.stopReading(self)
-
- def startWriting(self):
- self._userWantWrite = True
- if not self.writeBlockedOnRead:
- return Connection.startWriting(self)
-
- def stopWriting(self):
- self._userWantWrite = False
- if not self.readBlockedOnWrite:
- return Connection.stopWriting(self)
-
- def _resetReadWrite(self):
- # After changing readBlockedOnWrite or writeBlockedOnRead,
- # call this to reset the state to what the user requested.
- if self._userWantWrite:
- self.startWriting()
- else:
- self.stopWriting()
-
- if self._userWantRead:
- self.startReading()
- else:
- self.stopReading()
-
-def _getTLSClass(klass, _existing={}):
- if klass not in _existing:
- class TLSConnection(_TLSMixin, klass):
- implements(interfaces.ISSLTransport)
- _existing[klass] = TLSConnection
- return _existing[klass]
-
-class Connection(abstract.FileDescriptor, _SocketCloser):
- """
- Superclass of all socket-based FileDescriptors.
-
- This is an abstract superclass of all objects which represent a TCP/IP
- connection based socket.
-
- @ivar logstr: prefix used when logging events related to this connection.
- @type logstr: C{str}
- """
-
- implements(interfaces.ITCPTransport, interfaces.ISystemHandle)
-
- TLS = 0
-
- def __init__(self, skt, protocol, reactor=None):
- abstract.FileDescriptor.__init__(self, reactor=reactor)
- self.socket = skt
- self.socket.setblocking(0)
- self.fileno = skt.fileno
- self.protocol = protocol
-
- if SSL:
-
- def startTLS(self, ctx):
- assert not self.TLS
- error=False
- if self.dataBuffer or self._tempDataBuffer:
- self.dataBuffer += "".join(self._tempDataBuffer)
- self._tempDataBuffer = []
- self._tempDataLen = 0
- written = self.writeSomeData(buffer(self.dataBuffer, self.offset))
- offset = self.offset
- dataLen = len(self.dataBuffer)
- self.offset = 0
- self.dataBuffer = ""
- if isinstance(written, Exception) or (offset + written != dataLen):
- error=True
-
-
- self.stopReading()
- self.stopWriting()
- self._startTLS()
- self.socket = SSL.Connection(ctx.getContext(), self.socket)
- self.fileno = self.socket.fileno
- self.startReading()
- if error:
- warnings.warn("startTLS with unwritten buffered data currently doesn't work right. See issue #686. Closing connection.", category=RuntimeWarning, stacklevel=2)
- self.loseConnection()
- return
-
- def _startTLS(self):
- self.TLS = 1
- self.__class__ = _getTLSClass(self.__class__)
-
- def getHandle(self):
- """Return the socket for this connection."""
- return self.socket
-
- def doRead(self):
- """Calls self.protocol.dataReceived with all available data.
-
- This reads up to self.bufferSize bytes of data from its socket, then
- calls self.dataReceived(data) to process it. If the connection is not
- lost through an error in the physical recv(), this function will return
- the result of the dataReceived call.
- """
- try:
- data = self.socket.recv(self.bufferSize)
- except socket.error, se:
- if se.args[0] == EWOULDBLOCK:
- return
- else:
- return main.CONNECTION_LOST
- if not data:
- return main.CONNECTION_DONE
- return self.protocol.dataReceived(data)
-
- def writeSomeData(self, data):
- """Connection.writeSomeData(data) -> #of bytes written | CONNECTION_LOST
- This writes as much data as possible to the socket and returns either
- the number of bytes read (which is positive) or a connection error code
- (which is negative)
- """
- try:
- # Limit length of buffer to try to send, because some OSes are too
- # stupid to do so themselves (ahem windows)
- return self.socket.send(buffer(data, 0, self.SEND_LIMIT))
- except socket.error, se:
- if se.args[0] == EINTR:
- return self.writeSomeData(data)
- elif se.args[0] in (EWOULDBLOCK, ENOBUFS):
- return 0
- else:
- return main.CONNECTION_LOST
-
- def _closeWriteConnection(self):
- try:
- getattr(self.socket, self._socketShutdownMethod)(1)
- except socket.error:
- pass
- p = interfaces.IHalfCloseableProtocol(self.protocol, None)
- if p:
- try:
- p.writeConnectionLost()
- except:
- f = failure.Failure()
- log.err()
- self.connectionLost(f)
-
- def readConnectionLost(self, reason):
- p = interfaces.IHalfCloseableProtocol(self.protocol, None)
- if p:
- try:
- p.readConnectionLost()
- except:
- log.err()
- self.connectionLost(failure.Failure())
- else:
- self.connectionLost(reason)
-
- def connectionLost(self, reason):
- """See abstract.FileDescriptor.connectionLost().
- """
- abstract.FileDescriptor.connectionLost(self, reason)
- self._closeSocket()
- protocol = self.protocol
- del self.protocol
- del self.socket
- del self.fileno
- protocol.connectionLost(reason)
-
- logstr = "Uninitialized"
-
- def logPrefix(self):
- """Return the prefix to log with when I own the logging thread.
- """
- return self.logstr
-
- 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)
-
-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)
- else:
- reactor.callLater(0, self.failIfNotConnected, error)
-
- def startTLS(self, ctx, client=1):
- holder = Connection.startTLS(self, ctx)
- if client:
- self.socket.set_connect_state()
- else:
- self.socket.set_accept_state()
- return holder
-
- def stopConnecting(self):
- """Stop attempt to connect."""
- self.failIfNotConnected(error.UserError())
-
- def failIfNotConnected(self, err):
- """
- Generic method called when the attemps to connect failed. It basically
- cleans everything it can: call connectionFailed, stop read and write,
- delete socket related members.
- """
- if (self.connected or self.disconnected or
- not hasattr(self, "connector")):
- return
-
- self.connector.connectionFailed(failure.Failure(err))
- if hasattr(self, "reactor"):
- # this doesn't happen if we failed in __init__
- self.stopReading()
- self.stopWriting()
- del self.connector
-
- try:
- self._closeSocket()
- except AttributeError:
- pass
- else:
- del self.socket, self.fileno
-
- def createInternetSocket(self):
- """(internal) Create a non-blocking socket using
- self.addressFamily, self.socketType.
- """
- s = socket.socket(self.addressFamily, self.socketType)
- s.setblocking(0)
- if fcntl and hasattr(fcntl, 'FD_CLOEXEC'):
- old = fcntl.fcntl(s.fileno(), fcntl.F_GETFD)
- fcntl.fcntl(s.fileno(), fcntl.F_SETFD, old | fcntl.FD_CLOEXEC)
- return s
-
- def resolveAddress(self):
- if abstract.isIPAddress(self.addr[0]):
- self._setRealAddress(self.addr[0])
- else:
- d = self.reactor.resolve(self.addr[0])
- d.addCallbacks(self._setRealAddress, self.failIfNotConnected)
-
- def _setRealAddress(self, address):
- self.realAddress = (address, self.addr[1])
- self.doConnect()
-
- def doConnect(self):
- """I connect the socket.
-
- Then, call the protocol's makeConnection, and start waiting for data.
- """
- if not hasattr(self, "connector"):
- # this happens when connection failed but doConnect
- # was scheduled via a callLater in self._finishInit
- return
-
- err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
- if err:
- self.failIfNotConnected(error.getConnectError((err, strerror(err))))
- return
-
-
- # doConnect gets called twice. The first time we actually need to
- # start the connection attempt. The second time we don't really
- # want to (SO_ERROR above will have taken care of any errors, and if
- # it reported none, the mere fact that doConnect was called again is
- # sufficient to indicate that the connection has succeeded), but it
- # is not /particularly/ detrimental to do so. This should get
- # cleaned up some day, though.
- try:
- connectResult = self.socket.connect_ex(self.realAddress)
- except socket.error, se:
- connectResult = se.args[0]
- if connectResult:
- if connectResult == EISCONN:
- pass
- # on Windows EINVAL means sometimes that we should keep trying:
- # http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winsock/winsock/connect_2.asp
- elif ((connectResult in (EWOULDBLOCK, EINPROGRESS, EALREADY)) or
- (connectResult == EINVAL and platformType == "win32")):
- self.startReading()
- self.startWriting()
- return
- else:
- self.failIfNotConnected(error.getConnectError((connectResult, strerror(connectResult))))
- return
-
- # If I have reached this point without raising or returning, that means
- # that the socket is connected.
- del self.doWrite
- del self.doRead
- # we first stop and then start, to reset any references to the old doRead
- self.stopReading()
- self.stopWriting()
- self._connectDone()
-
- def _connectDone(self):
- self.protocol = self.connector.buildProtocol(self.getPeer())
- self.connected = 1
- self.logstr = self.protocol.__class__.__name__ + ",client"
- self.startReading()
- self.protocol.makeConnection(self)
-
- def connectionLost(self, reason):
- if not self.connected:
- self.failIfNotConnected(error.ConnectError(string=reason))
- else:
- Connection.connectionLost(self, reason)
- self.connector.connectionLost(reason)
-
-
-class Client(BaseClient):
- """A TCP client."""
-
- def __init__(self, host, port, bindAddress, connector, reactor=None):
- # BaseClient.__init__ is invoked later
- self.connector = connector
- self.addr = (host, port)
-
- whenDone = self.resolveAddress
- err = None
- skt = None
-
- try:
- skt = self.createInternetSocket()
- except socket.error, se:
- err = error.ConnectBindError(se[0], se[1])
- whenDone = None
- if whenDone and bindAddress is not None:
- try:
- skt.bind(bindAddress)
- except socket.error, se:
- err = error.ConnectBindError(se[0], se[1])
- whenDone = None
- self._finishInit(whenDone, skt, err, reactor)
-
- def getHost(self):
- """Returns an IPv4Address.
-
- This indicates the address from which I am connecting.
- """
- return address.IPv4Address('TCP', *(self.socket.getsockname() + ('INET',)))
-
- def getPeer(self):
- """Returns an IPv4Address.
-
- This indicates the address that I am connected to.
- """
- return address.IPv4Address('TCP', *(self.addr + ('INET',)))
-
- def __repr__(self):
- s = '<%s to %s at %x>' % (self.__class__, self.addr, unsignedID(self))
- return s
-
-
-class Server(Connection):
- """
- Serverside socket-stream connection class.
-
- This is a serverside network connection transport; a socket which came from
- an accept() on a server.
- """
-
- def __init__(self, sock, protocol, client, server, sessionno):
- """
- Server(sock, protocol, client, server, sessionno)
-
- Initialize it with a socket, a protocol, a descriptor for my peer (a
- tuple of host, port describing the other end of the connection), an
- instance of Port, and a session number.
- """
- Connection.__init__(self, sock, protocol)
- self.server = server
- self.client = client
- self.sessionno = sessionno
- self.hostname = client[0]
- self.logstr = "%s,%s,%s" % (self.protocol.__class__.__name__,
- sessionno,
- self.hostname)
- self.repstr = "<%s #%s on %s>" % (self.protocol.__class__.__name__,
- self.sessionno,
- self.server._realPortNumber)
- self.startReading()
- self.connected = 1
-
- def __repr__(self):
- """A string representation of this connection.
- """
- return self.repstr
-
- def startTLS(self, ctx, server=1):
- holder = Connection.startTLS(self, ctx)
- if server:
- self.socket.set_accept_state()
- else:
- self.socket.set_connect_state()
- return holder
-
- def getHost(self):
- """Returns an IPv4Address.
-
- This indicates the server's address.
- """
- return address.IPv4Address('TCP', *(self.socket.getsockname() + ('INET',)))
-
- def getPeer(self):
- """Returns an IPv4Address.
-
- This indicates the client's address.
- """
- return address.IPv4Address('TCP', *(self.client + ('INET',)))
-
-class Port(base.BasePort, _SocketCloser):
- """I am a TCP server port, listening for connections.
-
- When a connection is accepted, I will call my factory's buildProtocol with
- the incoming connection as an argument, according to the specification
- described in twisted.internet.interfaces.IProtocolFactory.
-
- If you wish to change the sort of transport that will be used, my
- `transport' attribute will be called with the signature expected for
- Server.__init__, so it can be replaced.
- """
-
- implements(interfaces.IListeningPort)
-
- addressFamily = socket.AF_INET
- socketType = socket.SOCK_STREAM
-
- transport = Server
- sessionno = 0
- interface = ''
- backlog = 50
-
- # 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):
- """Initialize with a numeric port to listen on.
- """
- base.BasePort.__init__(self, reactor=reactor)
- self.port = port
- self.factory = factory
- self.backlog = backlog
- self.interface = interface
-
- 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 createInternetSocket(self):
- s = base.BasePort.createInternetSocket(self)
- if platformType == "posix" and sys.platform != "cygwin":
- s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
- return s
-
- def startListening(self):
- """Create and bind my socket, and begin listening on it.
-
- This is called on unserialization, and must be called after creating a
- server to begin listening on the specified port.
- """
- try:
- skt = self.createInternetSocket()
- skt.bind((self.interface, self.port))
- except socket.error, le:
- raise CannotListenError, (self.interface, self.port, le)
-
- # 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))
-
- # The order of the next 6 lines is kind of bizarre. If no one
- # can explain it, perhaps we should re-arrange them.
- self.factory.doStart()
- skt.listen(self.backlog)
- self.connected = 1
- self.socket = skt
- self.fileno = self.socket.fileno
- self.numberAccepts = 100
-
- self.startReading()
-
- def _buildAddr(self, (host, port)):
- return address._ServerFactoryIPv4Address('TCP', host, port)
-
- def doRead(self):
- """Called when my socket is ready for reading.
-
- This accepts a connection and calls self.protocol() to handle the
- wire-level protocol.
- """
- try:
- if platformType == "posix":
- numAccepts = self.numberAccepts
- else:
- # win32 event loop breaks if we do more than one accept()
- # in an iteration of the event loop.
- numAccepts = 1
- for i in range(numAccepts):
- # we need this so we can deal with a factory's buildProtocol
- # calling our loseConnection
- if self.disconnecting:
- return
- try:
- skt, addr = self.socket.accept()
- except socket.error, e:
- if e.args[0] in (EWOULDBLOCK, EAGAIN):
- self.numberAccepts = i
- break
- elif e.args[0] == EPERM:
- # Netfilter on Linux may have rejected the
- # connection, but we get told to try to accept()
- # anyway.
- continue
- elif e.args[0] in (EMFILE, ENOBUFS, ENFILE, ENOMEM, ECONNABORTED):
-
- # Linux gives EMFILE when a process is not allowed
- # to allocate any more file descriptors. *BSD and
- # Win32 give (WSA)ENOBUFS. Linux can also give
- # ENFILE if the system is out of inodes, or ENOMEM
- # if there is insufficient memory to allocate a new
- # dentry. ECONNABORTED is documented as possible on
- # both Linux and Windows, but it is not clear
- # whether there are actually any circumstances under
- # which it can happen (one might expect it to be
- # possible if a client sends a FIN or RST after the
- # server sends a SYN|ACK but before application code
- # calls accept(2), however at least on Linux this
- # _seems_ to be short-circuited by syncookies.
-
- log.msg("Could not accept new connection (%s)" % (
- errorcode[e.args[0]],))
- break
- raise
-
- protocol = self.factory.buildProtocol(self._buildAddr(addr))
- if protocol is None:
- skt.close()
- continue
- s = self.sessionno
- self.sessionno = s+1
- transport = self.transport(skt, protocol, addr, self, s)
- transport = self._preMakeConnection(transport)
- protocol.makeConnection(transport)
- else:
- self.numberAccepts = self.numberAccepts+20
- except:
- # Note that in TLS mode, this will possibly catch SSL.Errors
- # raised by self.socket.accept()
- #
- # There is no "except SSL.Error:" above because SSL may be
- # None if there is no SSL support. In any case, all the
- # "except SSL.Error:" suite would probably do is log.deferr()
- # and return, so handling it here works just as well.
- log.deferr()
-
- def _preMakeConnection(self, transport):
- return transport
-
- def loseConnection(self, connDone=failure.Failure(main.CONNECTION_DONE)):
- """Stop accepting connections on this port.
-
- This will shut down my socket and call self.connectionLost().
- It returns a deferred which will fire successfully when the
- port is actually closed.
- """
- self.disconnecting = 1
- self.stopReading()
- if self.connected:
- self.deferred = defer.Deferred()
- self.reactor.callLater(0, self.connectionLost, connDone)
- return self.deferred
-
- stopListening = loseConnection
-
- def connectionLost(self, reason):
- """Cleans up my socket.
- """
- log.msg('(Port %s Closed)' % self._realPortNumber)
- self._realPortNumber = None
- base.BasePort.connectionLost(self, reason)
- self.connected = 0
- self._closeSocket()
- del self.socket
- del self.fileno
- self.factory.doStop()
- if hasattr(self, "deferred"):
- self.deferred.callback(None)
- del self.deferred
-
- def logPrefix(self):
- """Returns the name of my class, to prefix log entries with.
- """
- return reflect.qual(self.factory.__class__)
-
- def getHost(self):
- """Returns an IPv4Address.
-
- This indicates the server's address.
- """
- return address.IPv4Address('TCP', *(self.socket.getsockname() + ('INET',)))
-
-class Connector(base.BaseConnector):
- def __init__(self, host, port, factory, timeout, bindAddress, reactor=None):
- self.host = host
- if isinstance(port, types.StringTypes):
- try:
- port = socket.getservbyname(port, 'tcp')
- except socket.error, e:
- raise error.ServiceNameUnknownError(string="%s (%r)" % (e, port))
- self.port = port
- self.bindAddress = bindAddress
- base.BaseConnector.__init__(self, factory, timeout, reactor)
-
- def _makeTransport(self):
- return Client(self.host, self.port, self.bindAddress, self, self.reactor)
-
- def getDestination(self):
- return address.IPv4Address('TCP', self.host, self.port, 'INET')
diff --git a/tools/buildbot/pylibs/twisted/internet/test/__init__.py b/tools/buildbot/pylibs/twisted/internet/test/__init__.py
deleted file mode 100644
index 2c1f28e..0000000
--- a/tools/buildbot/pylibs/twisted/internet/test/__init__.py
+++ /dev/null
@@ -1,6 +0,0 @@
-# Copyright (c) 2008 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Tests for L{twisted.internet}.
-"""
diff --git a/tools/buildbot/pylibs/twisted/internet/test/test_gtk2reactor.py b/tools/buildbot/pylibs/twisted/internet/test/test_gtk2reactor.py
deleted file mode 100644
index 22daed8..0000000
--- a/tools/buildbot/pylibs/twisted/internet/test/test_gtk2reactor.py
+++ /dev/null
@@ -1,43 +0,0 @@
-# Copyright (c) 2008 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Tests for L{twisted.internet.gtk2reactor}.
-"""
-
-from twisted.trial.unittest import TestCase
-
-
-class Gtk2ReactorTests(TestCase):
- """
- Tests for L{twisted.internet.gtk2reactor.Gtk2Reactor}.
- """
- def test_stopWhenRunning(self):
- """
- When C{reactor.stop} is scheduled with C{callWhenRunning},
- C{reactor.run} will return immediately, and without processing any
- timed events.
- """
- # This test *should* be part of a general reactor test suite that runs
- # tests cases against all reactor implementations.
- missed = []
- def calledTooLate():
- missed.append(True)
- reactor.crash()
- reactor = Gtk2Reactor(useGtk=False)
- reactor.callWhenRunning(reactor.stop)
- reactor.callLater(0, calledTooLate)
- reactor.run(installSignalHandlers=False)
- # XXX This explicit calls to clean up the waker should become obsolete
- # when bug #3063 is fixed. -radix, 2008-02-29. Fortunately it should
- # probably cause an error when bug #3063 is fixed, so it should be
- # removed in the same branch that fixes it.
- reactor.removeReader(reactor.waker)
- reactor.waker.connectionLost(None)
- if missed == [True]:
- self.fail("callWhenRunning reactor.stop did not take effect")
-
-try:
- from twisted.internet.gtk2reactor import Gtk2Reactor
-except ImportError:
- Gtk2ReactorTests.skip = "gtk2reactor is unavailable"
diff --git a/tools/buildbot/pylibs/twisted/internet/test/test_iocp.py b/tools/buildbot/pylibs/twisted/internet/test/test_iocp.py
deleted file mode 100644
index ed72b9e..0000000
--- a/tools/buildbot/pylibs/twisted/internet/test/test_iocp.py
+++ /dev/null
@@ -1,105 +0,0 @@
-from twisted.internet.protocol import ServerFactory, Protocol, ClientCreator
-from twisted.internet.defer import DeferredList, maybeDeferred, Deferred
-from twisted.trial import unittest
-from twisted.internet import reactor
-from twisted.python import log
-
-from zope.interface.verify import verifyClass
-
-class StopStartReadingProtocol(Protocol):
- def connectionMade(self):
- self.transport.pauseProducing()
- self.transport.resumeProducing()
- reactor.callLater(0, self._beTerrible)
- self.data = ''
-
-
- def _beTerrible(self):
- self.transport.pauseProducing()
- self.transport.resumeProducing()
- reactor.callLater(0, self._beMoreTerrible)
-
-
- def _beMoreTerrible(self):
- self.transport.pauseProducing()
- self.transport.resumeProducing()
- reactor.callLater(0, self.factory.ready_d.callback, self)
-
-
- def dataReceived(self, data):
- log.msg('got data', len(data))
- self.data += data
- if len(self.data) == 4*self.transport.readBufferSize:
- self.factory.stop_d.callback(self.data)
-
-
-
-class IOCPReactorTestCase(unittest.TestCase):
- def test_noPendingTimerEvents(self):
- """
- Test reactor behavior (doIteration) when there are no pending time
- events.
- """
- from twisted.internet.iocpreactor.reactor import IOCPReactor
- ir = IOCPReactor()
- ir.wakeUp()
- self.failIf(ir.doIteration(None))
-
-
- def test_stopStartReading(self):
- """
- This test checks transport read state! There are three bits
- of it:
- 1) The transport producer is paused -- transport.reading
- is False)
- 2) The transport is about to schedule an OS read, on the next
- reactor iteration -- transport._readScheduled
- 3) The OS has a pending asynchronous read on our behalf --
- transport._readScheduledInOS
- if 3) is not implemented, it is possible to trick IOCPReactor into
- scheduling an OS read before the previous one finishes
- """
- sf = ServerFactory()
- sf.protocol = StopStartReadingProtocol
- sf.ready_d = Deferred()
- sf.stop_d = Deferred()
- p = reactor.listenTCP(0, sf)
- port = p.getHost().port
- cc = ClientCreator(reactor, Protocol)
- def proceed(protos, port):
- log.msg('PROCEEDING WITH THE TESTATHRON')
- self.assert_(protos[0])
- self.assert_(protos[1])
- protos = protos[0][1], protos[1][1]
- protos[0].transport.write(
- 'x' * (2 * protos[0].transport.readBufferSize) +
- 'y' * (2 * protos[0].transport.readBufferSize))
- return sf.stop_d.addCallback(cleanup, protos, port)
-
- def cleanup(data, protos, port):
- self.assert_(data == 'x'*(2*protos[0].transport.readBufferSize)+
- 'y'*(2*protos[0].transport.readBufferSize),
- 'did not get the right data')
- return DeferredList([
- maybeDeferred(protos[0].transport.loseConnection),
- maybeDeferred(protos[1].transport.loseConnection),
- maybeDeferred(port.stopListening)])
-
- return (DeferredList([cc.connectTCP('127.0.0.1', port), sf.ready_d])
- .addCallback(proceed, p))
-
-
- def test_reactorInterfaces(self):
- """
- Verify that IOCP socket-representing classes implement IReadWriteHandle
- """
- from twisted.internet.iocpreactor.interfaces import IReadWriteHandle
- from twisted.internet.iocpreactor import tcp, udp
- verifyClass(IReadWriteHandle, tcp.Connection)
- verifyClass(IReadWriteHandle, udp.Port)
-
-
-
-if reactor.__class__.__name__ != 'IOCPReactor':
- IOCPReactorTestCase.skip = 'This test only applies to IOCPReactor'
-
diff --git a/tools/buildbot/pylibs/twisted/internet/threads.py b/tools/buildbot/pylibs/twisted/internet/threads.py
deleted file mode 100644
index 415b66d..0000000
--- a/tools/buildbot/pylibs/twisted/internet/threads.py
+++ /dev/null
@@ -1,88 +0,0 @@
-# Copyright (c) 2001-2007 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Extended thread dispatching support.
-
-For basic support see reactor threading API docs.
-
-Maintainer: U{Itamar Shtull-Trauring<mailto:twisted@itamarst.org>}
-"""
-
-import Queue
-
-from twisted.python import failure
-from twisted.internet import defer
-
-
-def _putResultInDeferred(deferred, f, args, kwargs):
- """
- Run a function and give results to a Deferred.
- """
- from twisted.internet import reactor
- try:
- result = f(*args, **kwargs)
- except:
- f = failure.Failure()
- reactor.callFromThread(deferred.errback, f)
- else:
- reactor.callFromThread(deferred.callback, result)
-
-
-def deferToThread(f, *args, **kwargs):
- """
- Run function in thread and return result as Deferred.
- """
- d = defer.Deferred()
- from twisted.internet import reactor
- reactor.callInThread(_putResultInDeferred, d, f, args, kwargs)
- return d
-
-
-def _runMultiple(tupleList):
- """
- Run a list of functions.
- """
- for f, args, kwargs in tupleList:
- f(*args, **kwargs)
-
-
-def callMultipleInThread(tupleList):
- """
- Run a list of functions in the same thread.
-
- tupleList should be a list of (function, argsList, kwargsDict) tuples.
- """
- from twisted.internet import reactor
- reactor.callInThread(_runMultiple, tupleList)
-
-
-def blockingCallFromThread(reactor, f, *a, **kw):
- """
- Run a function in the reactor from a thread, and wait for the result
- synchronously, i.e. until the callback chain returned by the function
- get a result.
-
- @param reactor: The L{IReactorThreads} provider which will be used to
- schedule the function call.
- @param f: the callable to run in the reactor thread
- @type f: any callable.
- @param a: the arguments to pass to C{f}.
- @param kw: the keyword arguments to pass to C{f}.
-
- @return: the result of the callback chain.
- @raise: any error raised during the callback chain.
- """
- queue = Queue.Queue()
- def _callFromThread():
- result = defer.maybeDeferred(f, *a, **kw)
- result.addBoth(queue.put)
- reactor.callFromThread(_callFromThread)
- result = queue.get()
- if isinstance(result, failure.Failure):
- result.raiseException()
- return result
-
-
-__all__ = ["deferToThread", "callMultipleInThread", "blockingCallFromThread"]
-
diff --git a/tools/buildbot/pylibs/twisted/internet/tksupport.py b/tools/buildbot/pylibs/twisted/internet/tksupport.py
deleted file mode 100644
index 3248fa7..0000000
--- a/tools/buildbot/pylibs/twisted/internet/tksupport.py
+++ /dev/null
@@ -1,68 +0,0 @@
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-This module integrates Tkinter with twisted.internet's mainloop.
-
-Maintainer: U{Itamar Shtull-Trauring<mailto:twisted@itamarst.org>}
-
-To use, do::
-
- | tksupport.install(rootWidget)
-
-and then run your reactor as usual - do *not* call Tk's mainloop(),
-use Twisted's regular mechanism for running the event loop.
-
-Likewise, to stop your program you will need to stop Twisted's
-event loop. For example, if you want closing your root widget to
-stop Twisted::
-
- | root.protocol('WM_DELETE_WINDOW', reactor.stop)
-
-"""
-
-# system imports
-import Tkinter, tkSimpleDialog, tkMessageBox
-
-# twisted imports
-from twisted.python import log
-from twisted.internet import task
-
-
-_task = None
-
-def install(widget, ms=10, reactor=None):
- """Install a Tkinter.Tk() object into the reactor."""
- installTkFunctions()
- global _task
- _task = task.LoopingCall(widget.update)
- _task.start(ms / 1000.0, False)
-
-def uninstall():
- """Remove the root Tk widget from the reactor.
-
- Call this before destroy()ing the root widget.
- """
- global _task
- _task.stop()
- _task = None
-
-
-def installTkFunctions():
- import twisted.python.util
- twisted.python.util.getPassword = getPassword
-
-
-def getPassword(prompt = '', confirm = 0):
- while 1:
- try1 = tkSimpleDialog.askstring('Password Dialog', prompt, show='*')
- if not confirm:
- return try1
- try2 = tkSimpleDialog.askstring('Password Dialog', 'Confirm Password', show='*')
- if try1 == try2:
- return try1
- else:
- tkMessageBox.showerror('Password Mismatch', 'Passwords did not match, starting over')
-
-__all__ = ["install", "uninstall"]
diff --git a/tools/buildbot/pylibs/twisted/internet/udp.py b/tools/buildbot/pylibs/twisted/internet/udp.py
deleted file mode 100644
index 1597814..0000000
--- a/tools/buildbot/pylibs/twisted/internet/udp.py
+++ /dev/null
@@ -1,385 +0,0 @@
-# -*- test-case-name: twisted.test.test_udp -*-
-
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-Various asynchronous UDP classes.
-
-Please do not use this module directly.
-
-Maintainer: U{Itamar Shtull-Trauring<mailto:twisted@itamarst.org>}
-"""
-
-# System Imports
-import os
-import socket
-import operator
-import struct
-import warnings
-from zope.interface import implements
-
-from twisted.python.runtime import platformType
-if platformType == 'win32':
- from errno import WSAEWOULDBLOCK as EWOULDBLOCK
- from errno import WSAEINTR as EINTR
- from errno import WSAEMSGSIZE as EMSGSIZE
- from errno import WSAECONNREFUSED as ECONNREFUSED
- from errno import WSAECONNRESET
- EAGAIN=EWOULDBLOCK
-else:
- from errno import EWOULDBLOCK, EINTR, EMSGSIZE, ECONNREFUSED, EAGAIN
-
-# Twisted Imports
-from twisted.internet import protocol, base, defer, address
-from twisted.persisted import styles
-from twisted.python import log, reflect, failure
-
-# Sibling Imports
-import abstract, error, interfaces
-
-
-class Port(base.BasePort):
- """UDP port, listening for packets."""
-
- implements(interfaces.IUDPTransport, interfaces.ISystemHandle)
-
- addressFamily = socket.AF_INET
- socketType = socket.SOCK_DGRAM
- maxThroughput = 256 * 1024 # max bytes we read in one eventloop iteration
-
- # Actual port number being listened on, only set to a non-None
- # value when we are actually listening.
- _realPortNumber = None
-
- def __init__(self, port, proto, interface='', maxPacketSize=8192, reactor=None):
- """Initialize with a numeric port to listen on.
- """
- base.BasePort.__init__(self, reactor)
- self.port = port
- self.protocol = proto
- self.maxPacketSize = maxPacketSize
- self.interface = interface
- self.setLogStr()
- self._connectedAddr = None
-
- def __repr__(self):
- if self._realPortNumber is not None:
- return "<%s on %s>" % (self.protocol.__class__, self._realPortNumber)
- else:
- return "<%s not connected>" % (self.protocol.__class__,)
-
- def getHandle(self):
- """Return a socket object."""
- return self.socket
-
- def startListening(self):
- """Create and bind my socket, and begin listening on it.
-
- This is called on unserialization, and must be called after creating a
- server to begin listening on the specified port.
- """
- self._bindSocket()
- self._connectToProtocol()
-
- def _bindSocket(self):
- try:
- skt = self.createInternetSocket()
- skt.bind((self.interface, self.port))
- except socket.error, le:
- raise error.CannotListenError, (self.interface, self.port, le)
-
- # 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.protocol.__class__, self._realPortNumber))
-
- self.connected = 1
- self.socket = skt
- self.fileno = self.socket.fileno
-
- def _connectToProtocol(self):
- self.protocol.makeConnection(self)
- self.startReading()
-
-
- def doRead(self):
- """Called when my socket is ready for reading."""
- read = 0
- while read < self.maxThroughput:
- try:
- data, addr = self.socket.recvfrom(self.maxPacketSize)
- except socket.error, se:
- no = se.args[0]
- if no in (EAGAIN, EINTR, EWOULDBLOCK):
- return
- if (no == ECONNREFUSED) or (platformType == "win32" and no == WSAECONNRESET):
- if self._connectedAddr:
- self.protocol.connectionRefused()
- else:
- raise
- else:
- read += len(data)
- try:
- self.protocol.datagramReceived(data, addr)
- except:
- log.err()
-
-
- def write(self, datagram, addr=None):
- """Write a datagram.
-
- @param addr: should be a tuple (ip, port), can be None in connected mode.
- """
- if self._connectedAddr:
- assert addr in (None, self._connectedAddr)
- try:
- return self.socket.send(datagram)
- except socket.error, se:
- no = se.args[0]
- if no == EINTR:
- return self.write(datagram)
- elif no == EMSGSIZE:
- raise error.MessageLengthError, "message too long"
- elif no == ECONNREFUSED:
- self.protocol.connectionRefused()
- else:
- raise
- else:
- assert addr != None
- if not addr[0].replace(".", "").isdigit():
- warnings.warn("Please only pass IPs to write(), not hostnames", DeprecationWarning, stacklevel=2)
- try:
- return self.socket.sendto(datagram, addr)
- except socket.error, se:
- no = se.args[0]
- if no == EINTR:
- return self.write(datagram, addr)
- elif no == EMSGSIZE:
- raise error.MessageLengthError, "message too long"
- elif no == ECONNREFUSED:
- # in non-connected UDP ECONNREFUSED is platform dependent, I think
- # and the info is not necessarily useful. Nevertheless maybe we
- # should call connectionRefused? XXX
- return
- else:
- raise
-
- def writeSequence(self, seq, addr):
- self.write("".join(seq), addr)
-
- def connect(self, host, port):
- """'Connect' to remote server."""
- if self._connectedAddr:
- raise RuntimeError, "already connected, reconnecting is not currently supported (talk to itamar if you want this)"
- if not abstract.isIPAddress(host):
- raise ValueError, "please pass only IP addresses, not domain names"
- self._connectedAddr = (host, port)
- self.socket.connect((host, port))
-
- def _loseConnection(self):
- self.stopReading()
- if self.connected: # actually means if we are *listening*
- from twisted.internet import reactor
- reactor.callLater(0, self.connectionLost)
-
- def stopListening(self):
- if self.connected:
- result = self.d = defer.Deferred()
- else:
- result = None
- self._loseConnection()
- return result
-
- def loseConnection(self):
- warnings.warn("Please use stopListening() to disconnect port", DeprecationWarning, stacklevel=2)
- self.stopListening()
-
- def connectionLost(self, reason=None):
- """Cleans up my socket.
- """
- log.msg('(Port %s Closed)' % self._realPortNumber)
- self._realPortNumber = None
- base.BasePort.connectionLost(self, reason)
- if hasattr(self, "protocol"):
- # we won't have attribute in ConnectedPort, in cases
- # where there was an error in connection process
- 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 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',)))
-
-
-class ConnectedPort(Port):
- """DEPRECATED.
-
- A connected UDP socket."""
-
- implements(interfaces.IUDPConnectedTransport)
-
- def __init__(self, (remotehost, remoteport), port, proto, interface='', maxPacketSize=8192, reactor=None):
- Port.__init__(self, port, proto, interface, maxPacketSize, reactor)
- self.remotehost = remotehost
- self.remoteport = remoteport
-
- def startListening(self):
- self._bindSocket()
- if abstract.isIPAddress(self.remotehost):
- self.setRealAddress(self.remotehost)
- else:
- self.realAddress = None
- d = self.reactor.resolve(self.remotehost)
- d.addCallback(self.setRealAddress).addErrback(self.connectionFailed)
-
- def setRealAddress(self, addr):
- self.realAddress = addr
- self.socket.connect((addr, self.remoteport))
- self._connectToProtocol()
-
- def connectionFailed(self, reason):
- self._loseConnection()
- self.protocol.connectionFailed(reason)
- del self.protocol
-
- def doRead(self):
- """Called when my socket is ready for reading."""
- read = 0
- while read < self.maxThroughput:
- try:
- data, addr = self.socket.recvfrom(self.maxPacketSize)
- read += len(data)
- self.protocol.datagramReceived(data)
- except socket.error, se:
- no = se.args[0]
- if no in (EAGAIN, EINTR, EWOULDBLOCK):
- return
- if (no == ECONNREFUSED) or (platformType == "win32" and no == WSAECONNRESET):
- self.protocol.connectionRefused()
- else:
- raise
- except:
- log.deferr()
-
- def write(self, data):
- """Write a datagram."""
- try:
- return self.socket.send(data)
- except socket.error, se:
- no = se.args[0]
- if no == EINTR:
- return self.write(data)
- elif no == EMSGSIZE:
- raise error.MessageLengthError, "message too long"
- elif no == ECONNREFUSED:
- self.protocol.connectionRefused()
- else:
- raise
-
- def getPeer(self):
- """
- Returns a tuple of ('INET_UDP', hostname, port), indicating
- the remote address.
- """
- return address.IPv4Address('UDP', self.remotehost, self.remoteport, 'INET_UDP')
-
-
-class MulticastMixin:
- """Implement multicast functionality."""
-
- def getOutgoingInterface(self):
- i = self.socket.getsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF)
- return socket.inet_ntoa(struct.pack("@i", i))
-
- def setOutgoingInterface(self, addr):
- """Returns Deferred of success."""
- return self.reactor.resolve(addr).addCallback(self._setInterface)
-
- def _setInterface(self, addr):
- i = socket.inet_aton(addr)
- self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, i)
- return 1
-
- def getLoopbackMode(self):
- return self.socket.getsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP)
-
- def setLoopbackMode(self, mode):
- mode = struct.pack("b", operator.truth(mode))
- self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, mode)
-
- def getTTL(self):
- return self.socket.getsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL)
-
- def setTTL(self, ttl):
- ttl = struct.pack("B", ttl)
- self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
-
- def joinGroup(self, addr, interface=""):
- """Join a multicast group. Returns Deferred of success."""
- return self.reactor.resolve(addr).addCallback(self._joinAddr1, interface, 1)
-
- def _joinAddr1(self, addr, interface, join):
- return self.reactor.resolve(interface).addCallback(self._joinAddr2, addr, join)
-
- def _joinAddr2(self, interface, addr, join):
- addr = socket.inet_aton(addr)
- interface = socket.inet_aton(interface)
- if join:
- cmd = socket.IP_ADD_MEMBERSHIP
- else:
- cmd = socket.IP_DROP_MEMBERSHIP
- try:
- self.socket.setsockopt(socket.IPPROTO_IP, cmd, addr + interface)
- except socket.error, e:
- return failure.Failure(error.MulticastJoinError(addr, interface, *e.args))
-
- def leaveGroup(self, addr, interface=""):
- """Leave multicast group, return Deferred of success."""
- return self.reactor.resolve(addr).addCallback(self._joinAddr1, interface, 0)
-
-
-class MulticastPort(MulticastMixin, Port):
- """UDP Port that supports multicasting."""
-
- implements(interfaces.IMulticastTransport)
-
- def __init__(self, port, proto, interface='', maxPacketSize=8192, reactor=None, listenMultiple=False):
- 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 ConnectedMulticastPort(MulticastMixin, ConnectedPort):
- """DEPRECATED.
-
- Connected UDP Port that supports multicasting."""
-
- implements(interfaces.IMulticastTransport)
diff --git a/tools/buildbot/pylibs/twisted/internet/unix.py b/tools/buildbot/pylibs/twisted/internet/unix.py
deleted file mode 100644
index 0fc5ad8..0000000
--- a/tools/buildbot/pylibs/twisted/internet/unix.py
+++ /dev/null
@@ -1,297 +0,0 @@
-# -*- test-case-name: twisted.test.test_unix -*-
-
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""Various asynchronous TCP/IP classes.
-
-End users shouldn't use this module directly - use the reactor APIs instead.
-
-Maintainer: U{Itamar Shtull-Trauring<mailto:twisted@itamarst.org>}
-"""
-
-# System imports
-import os, stat, socket
-from errno import EINTR, EMSGSIZE, EAGAIN, EWOULDBLOCK, ECONNREFUSED
-
-from zope.interface import implements, implementsOnly, implementedBy
-
-if not hasattr(socket, 'AF_UNIX'):
- raise ImportError("UNIX sockets not supported on this platform")
-
-# Twisted imports
-from twisted.internet import base, tcp, udp, error, interfaces, protocol, address
-from twisted.internet.error import CannotListenError
-from twisted.python import lockfile, log, reflect, failure
-
-
-class Server(tcp.Server):
- def __init__(self, sock, protocol, client, server, sessionno):
- tcp.Server.__init__(self, sock, protocol, (client, None), server, sessionno)
-
- def getHost(self):
- return address.UNIXAddress(self.socket.getsockname())
-
- def getPeer(self):
- return address.UNIXAddress(self.hostname)
-
-
-class Port(tcp.Port):
- addressFamily = socket.AF_UNIX
- socketType = socket.SOCK_STREAM
-
- transport = Server
- lockFile = None
-
- def __init__(self, fileName, factory, backlog=50, mode=0666, reactor=None, wantPID = 0):
- tcp.Port.__init__(self, fileName, factory, backlog, reactor=reactor)
- self.mode = mode
- self.wantPID = wantPID
-
- def __repr__(self):
- factoryName = reflect.qual(self.factory.__class__)
- if hasattr(self, 'socket'):
- return '<%s on %r>' % (factoryName, self.port)
- else:
- return '<%s (not listening)>' % (factoryName,)
-
- def _buildAddr(self, name):
- return address.UNIXAddress(name)
-
- def startListening(self):
- """Create and bind my socket, and begin listening on it.
-
- This is called on unserialization, and must be called after creating a
- server to begin listening on the specified port.
- """
- log.msg("%s starting on %r" % (self.factory.__class__, repr(self.port)))
- if self.wantPID:
- self.lockFile = lockfile.FilesystemLock(self.port + ".lock")
- if not self.lockFile.lock():
- raise CannotListenError, (None, self.port, "Cannot acquire lock")
- else:
- if not self.lockFile.clean:
- try:
- # This is a best-attempt at cleaning up
- # left-over unix sockets on the filesystem.
- # If it fails, there's not much else we can
- # do. The bind() below will fail with an
- # exception that actually propegates.
- if stat.S_ISSOCK(os.stat(self.port).st_mode):
- os.remove(self.port)
- except:
- pass
-
- self.factory.doStart()
- try:
- skt = self.createInternetSocket()
- skt.bind(self.port)
- except socket.error, le:
- raise CannotListenError, (None, self.port, le)
- else:
- # Make the socket readable and writable to the world.
- try:
- os.chmod(self.port, self.mode)
- except: # probably not a visible filesystem name
- pass
- skt.listen(self.backlog)
- self.connected = True
- self.socket = skt
- self.fileno = self.socket.fileno
- self.numberAccepts = 100
- self.startReading()
-
- def connectionLost(self, reason):
- os.unlink(self.port)
- if self.lockFile is not None:
- self.lockFile.unlock()
- tcp.Port.connectionLost(self, reason)
-
- def getHost(self):
- """Returns a UNIXAddress.
-
- This indicates the server's address.
- """
- return address.UNIXAddress(self.socket.getsockname())
-
-
-class Client(tcp.BaseClient):
- """A client for Unix sockets."""
- addressFamily = socket.AF_UNIX
- socketType = socket.SOCK_STREAM
-
- def __init__(self, filename, connector, reactor=None, checkPID = 0):
- self.connector = connector
- self.realAddress = self.addr = filename
- if checkPID and not lockfile.isLocked(filename + ".lock"):
- self._finishInit(None, None, error.BadFileError(filename), reactor)
- self._finishInit(self.doConnect, self.createInternetSocket(),
- None, reactor)
-
- def getPeer(self):
- return address.UNIXAddress(self.addr)
-
- def getHost(self):
- return address.UNIXAddress(None)
-
-
-class Connector(base.BaseConnector):
- def __init__(self, address, factory, timeout, reactor, checkPID):
- base.BaseConnector.__init__(self, factory, timeout, reactor)
- self.address = address
- self.checkPID = checkPID
-
- def _makeTransport(self):
- return Client(self.address, self, self.reactor, self.checkPID)
-
- def getDestination(self):
- return address.UNIXAddress(self.address)
-
-
-class DatagramPort(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):
- """Initialize with address to listen on.
- """
- udp.Port.__init__(self, addr, proto, maxPacketSize=maxPacketSize, reactor=reactor)
- self.mode = mode
-
-
- def __repr__(self):
- protocolName = reflect.qual(self.protocol.__class__,)
- if hasattr(self, 'socket'):
- return '<%s on %r>' % (protocolName, self.port)
- else:
- return '<%s (not listening)>' % (protocolName,)
-
-
- def _bindSocket(self):
- log.msg("%s starting on %s"%(self.protocol.__class__, repr(self.port)))
- try:
- skt = self.createInternetSocket() # XXX: haha misnamed method
- if self.port:
- skt.bind(self.port)
- except socket.error, le:
- raise error.CannotListenError, (None, self.port, le)
- if self.port:
- try:
- os.chmod(self.port, self.mode)
- except: # probably not a visible filesystem name
- pass
- self.connected = 1
- self.socket = skt
- self.fileno = self.socket.fileno
-
- def write(self, datagram, address):
- """Write a datagram."""
- try:
- return self.socket.sendto(datagram, address)
- except socket.error, se:
- no = se.args[0]
- if no == EINTR:
- return self.write(datagram, address)
- elif no == EMSGSIZE:
- raise error.MessageLengthError, "message too long"
- elif no == EAGAIN:
- # oh, well, drop the data. The only difference from UDP
- # is that UDP won't ever notice.
- # TODO: add TCP-like buffering
- pass
- else:
- raise
-
- def connectionLost(self, reason=None):
- """Cleans up my socket.
- """
- log.msg('(Port %s Closed)' % repr(self.port))
- base.BasePort.connectionLost(self, reason)
- if hasattr(self, "protocol"):
- # we won't have attribute in ConnectedPort, in cases
- # where there was an error in connection process
- 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())
-
-
-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:
- self._bindSocket()
- self.socket.connect(self.remoteaddr)
- self._connectToProtocol()
- except:
- self.connectionFailed(failure.Failure())
-
- def connectionFailed(self, reason):
- self.loseConnection()
- self.protocol.connectionFailed(reason)
- del self.protocol
-
- def doRead(self):
- """Called when my socket is ready for reading."""
- read = 0
- while read < self.maxThroughput:
- try:
- data, addr = self.socket.recvfrom(self.maxPacketSize)
- read += len(data)
- self.protocol.datagramReceived(data)
- except socket.error, se:
- no = se.args[0]
- if no in (EAGAIN, EINTR, EWOULDBLOCK):
- return
- if no == ECONNREFUSED:
- self.protocol.connectionRefused()
- else:
- raise
- except:
- log.deferr()
-
- def write(self, data):
- """Write a datagram."""
- try:
- return self.socket.send(data)
- except socket.error, se:
- no = se.args[0]
- if no == EINTR:
- return self.write(data)
- elif no == EMSGSIZE:
- raise error.MessageLengthError, "message too long"
- elif no == ECONNREFUSED:
- self.protocol.connectionRefused()
- elif no == EAGAIN:
- # oh, well, drop the data. The only difference from UDP
- # is that UDP won't ever notice.
- # TODO: add TCP-like buffering
- pass
- else:
- raise
-
- def getPeer(self):
- return address.UNIXAddress(self.remoteaddr)
diff --git a/tools/buildbot/pylibs/twisted/internet/utils.py b/tools/buildbot/pylibs/twisted/internet/utils.py
deleted file mode 100644
index 47ae379..0000000
--- a/tools/buildbot/pylibs/twisted/internet/utils.py
+++ /dev/null
@@ -1,172 +0,0 @@
-# -*- test-case-name: twisted.test.test_iutils -*-
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""Utility methods."""
-
-import sys, warnings
-
-from twisted.internet import protocol, defer
-from twisted.python import failure, util as tputil
-
-try:
- import cStringIO as StringIO
-except ImportError:
- import StringIO
-
-def _callProtocolWithDeferred(protocol, executable, args, env, path, reactor=None):
- if reactor is None:
- from twisted.internet import reactor
-
- d = defer.Deferred()
- p = protocol(d)
- reactor.spawnProcess(p, executable, (executable,)+tuple(args), env, path)
- return d
-
-
-class _BackRelay(protocol.ProcessProtocol):
-
- def __init__(self, deferred, errortoo=0):
- self.deferred = deferred
- self.s = StringIO.StringIO()
- if errortoo:
- self.errReceived = self.errReceivedIsGood
- else:
- self.errReceived = self.errReceivedIsBad
-
- def errReceivedIsBad(self, text):
- if self.deferred is not None:
- self.deferred.errback(failure.Failure(IOError("got stderr: %r" % text)))
- self.deferred = None
- self.transport.loseConnection()
-
- def errReceivedIsGood(self, text):
- self.s.write(text)
-
- def outReceived(self, text):
- self.s.write(text)
-
- def processEnded(self, reason):
- if self.deferred is not None:
- self.deferred.callback(self.s.getvalue())
-
-
-def getProcessOutput(executable, args=(), env={}, path='.', reactor=None,
- errortoo=0):
- """Spawn a process and return its output as a deferred returning a string.
-
- @param executable: The file name to run and get the output of - the
- full path should be used.
-
- @param args: the command line arguments to pass to the process; a
- sequence of strings. The first string should *NOT* be the
- executable's name.
-
- @param env: the environment variables to pass to the processs; a
- dictionary of strings.
-
- @param path: the path to run the subprocess in - defaults to the
- current directory.
-
- @param reactor: the reactor to use - defaults to the default reactor
- @param errortoo: if 1, capture stderr too
- """
- return _callProtocolWithDeferred(lambda d:
- _BackRelay(d, errortoo=errortoo),
- executable, args, env, path,
- reactor)
-
-
-class _ValueGetter(protocol.ProcessProtocol):
-
- def __init__(self, deferred):
- self.deferred = deferred
-
- def processEnded(self, reason):
- self.deferred.callback(reason.value.exitCode)
-
-
-def getProcessValue(executable, args=(), env={}, path='.', reactor=None):
- """Spawn a process and return its exit code as a Deferred."""
- return _callProtocolWithDeferred(_ValueGetter, executable, args, env, path,
- reactor)
-
-
-class _EverythingGetter(protocol.ProcessProtocol):
-
- def __init__(self, deferred):
- self.deferred = deferred
- self.outBuf = StringIO.StringIO()
- self.errBuf = StringIO.StringIO()
- self.outReceived = self.outBuf.write
- self.errReceived = self.errBuf.write
-
- def processEnded(self, reason):
- out = self.outBuf.getvalue()
- err = self.errBuf.getvalue()
- e = reason.value
- code = e.exitCode
- if e.signal:
- self.deferred.errback((out, err, e.signal))
- else:
- self.deferred.callback((out, err, code))
-
-def getProcessOutputAndValue(executable, args=(), env={}, path='.',
- reactor=None):
- """Spawn a process and returns a Deferred that will be called back with
- its output (from stdout and stderr) and it's exit code as (out, err, code)
- If a signal is raised, the Deferred will errback with the stdout and
- stderr up to that point, along with the signal, as (out, err, signalNum)
- """
- return _callProtocolWithDeferred(_EverythingGetter, executable, args, env, path,
- reactor)
-
-def _resetWarningFilters(passthrough, addedFilters):
- for f in addedFilters:
- try:
- warnings.filters.remove(f)
- except ValueError:
- pass
- return passthrough
-
-
-def runWithWarningsSuppressed(suppressedWarnings, f, *a, **kw):
- """Run the function C{f}, but with some warnings suppressed.
-
- @param suppressedWarnings: A list of arguments to pass to filterwarnings.
- Must be a sequence of 2-tuples (args, kwargs).
- @param f: A callable, followed by its arguments and keyword arguments
- """
- for args, kwargs in suppressedWarnings:
- warnings.filterwarnings(*args, **kwargs)
- addedFilters = warnings.filters[:len(suppressedWarnings)]
- try:
- result = f(*a, **kw)
- except:
- exc_info = sys.exc_info()
- _resetWarningFilters(None, addedFilters)
- raise exc_info[0], exc_info[1], exc_info[2]
- else:
- if isinstance(result, defer.Deferred):
- result.addBoth(_resetWarningFilters, addedFilters)
- else:
- _resetWarningFilters(None, addedFilters)
- return result
-
-
-def suppressWarnings(f, *suppressedWarnings):
- """
- Wrap C{f} in a callable which suppresses the indicated warnings before
- invoking C{f} and unsuppresses them afterwards. If f returns a Deferred,
- warnings will remain suppressed until the Deferred fires.
- """
- def warningSuppressingWrapper(*a, **kw):
- return runWithWarningsSuppressed(suppressedWarnings, f, *a, **kw)
- return tputil.mergeFunctionMetadata(f, warningSuppressingWrapper)
-
-
-__all__ = [
- "runWithWarningsSuppressed", "suppressWarnings",
-
- "getProcessOutput", "getProcessValue", "getProcessOutputAndValue",
- ]
diff --git a/tools/buildbot/pylibs/twisted/internet/win32eventreactor.py b/tools/buildbot/pylibs/twisted/internet/win32eventreactor.py
deleted file mode 100644
index a6e0991..0000000
--- a/tools/buildbot/pylibs/twisted/internet/win32eventreactor.py
+++ /dev/null
@@ -1,244 +0,0 @@
-# Copyright (c) 2001-2007 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-A win32event based implementation of the Twisted main loop.
-
-This requires win32all or ActivePython to be installed.
-
-Maintainer: U{Itamar Shtull-Trauring<mailto:twisted@itamarst.org>}
-
-
-LIMITATIONS:
- 1. WaitForMultipleObjects and thus the event loop can only handle 64 objects.
- 2. Process running has some problems (see Process docstring).
-
-
-TODO:
- 1. Event loop handling of writes is *very* problematic (this is causing failed tests).
- Switch to doing it the correct way, whatever that means (see below).
- 2. Replace icky socket loopback waker with event based waker (use dummyEvent object)
- 3. Switch everyone to using Free Software so we don't have to deal with proprietary APIs.
-
-
-ALTERNATIVE SOLUTIONS:
- - IIRC, sockets can only be registered once. So we switch to a structure
- like the poll() reactor, thus allowing us to deal with write events in
- a decent fashion. This should allow us to pass tests, but we're still
- limited to 64 events.
-
-Or:
-
- - Instead of doing a reactor, we make this an addon to the select reactor.
- The WFMO event loop runs in a separate thread. This means no need to maintain
- separate code for networking, 64 event limit doesn't apply to sockets,
- we can run processes and other win32 stuff in default event loop. The
- only problem is that we're stuck with the icky socket based waker.
- Another benefit is that this could be extended to support >64 events
- in a simpler manner than the previous solution.
-
-The 2nd solution is probably what will get implemented.
-"""
-
-# System imports
-import time
-import sys
-
-from zope.interface import implements
-
-# Win32 imports
-from win32file import WSAEventSelect, FD_READ, FD_CLOSE, FD_ACCEPT, FD_CONNECT
-from win32event import CreateEvent, MsgWaitForMultipleObjects
-from win32event import WAIT_OBJECT_0, WAIT_TIMEOUT, QS_ALLINPUT, QS_ALLEVENTS
-
-import win32gui
-
-# Twisted imports
-from twisted.internet import posixbase
-from twisted.python import log, threadable, failure
-from twisted.internet.interfaces import IReactorFDSet, IReactorProcess
-
-from twisted.internet._dumbwin32proc import Process
-
-
-class Win32Reactor(posixbase.PosixReactorBase):
- """
- Reactor that uses Win32 event APIs.
-
- @ivar _reads: A dictionary mapping L{FileDescriptor} instances to a
- win32 event object used to check for read events for that descriptor.
-
- @ivar _writes: A dictionary mapping L{FileDescriptor} instances to a
- arbitrary value. Keys in this dictionary will be given a chance to
- write out their data.
-
- @ivar _events: A dictionary mapping win32 event object to tuples of
- L{FileDescriptor} instances and event masks.
- """
- implements(IReactorFDSet, IReactorProcess)
-
- dummyEvent = CreateEvent(None, 0, 0, None)
-
- def __init__(self):
- self._reads = {}
- self._writes = {}
- self._events = {}
- posixbase.PosixReactorBase.__init__(self)
-
-
- def _makeSocketEvent(self, fd, action, why):
- """
- Make a win32 event object for a socket.
- """
- event = CreateEvent(None, 0, 0, None)
- WSAEventSelect(fd, event, why)
- self._events[event] = (fd, action)
- return event
-
-
- def addEvent(self, event, fd, action):
- """
- Add a new win32 event to the event loop.
- """
- self._events[event] = (fd, action)
-
-
- def removeEvent(self, event):
- """
- Remove an event.
- """
- del self._events[event]
-
-
- def addReader(self, reader):
- """
- Add a socket FileDescriptor for notification of data available to read.
- """
- if reader not in self._reads:
- self._reads[reader] = self._makeSocketEvent(
- reader, 'doRead', FD_READ | FD_ACCEPT | FD_CONNECT | FD_CLOSE)
-
- def addWriter(self, writer):
- """
- Add a socket FileDescriptor for notification of data available to write.
- """
- if writer not in self._writes:
- self._writes[writer] = 1
-
- def removeReader(self, reader):
- """Remove a Selectable for notification of data available to read.
- """
- if reader in self._reads:
- del self._events[self._reads[reader]]
- del self._reads[reader]
-
- def removeWriter(self, writer):
- """Remove a Selectable for notification of data available to write.
- """
- if writer in self._writes:
- del self._writes[writer]
-
- def removeAll(self):
- """
- Remove all selectables, and return a list of them.
- """
- return self._removeAll(self._reads, self._writes)
-
-
- def getReaders(self):
- return self._reads.keys()
-
-
- def getWriters(self):
- return self._writes.keys()
-
-
- def doWaitForMultipleEvents(self, timeout):
- log.msg(channel='system', event='iteration', reactor=self)
- if timeout is None:
- #timeout = INFINITE
- timeout = 100
- else:
- timeout = int(timeout * 1000)
-
- if not (self._events or self._writes):
- # sleep so we don't suck up CPU time
- time.sleep(timeout / 1000.0)
- return
-
- canDoMoreWrites = 0
- for fd in self._writes.keys():
- if log.callWithLogger(fd, self._runWrite, fd):
- canDoMoreWrites = 1
-
- if canDoMoreWrites:
- timeout = 0
-
- handles = self._events.keys() or [self.dummyEvent]
- val = MsgWaitForMultipleObjects(handles, 0, timeout, QS_ALLINPUT | QS_ALLEVENTS)
- if val == WAIT_TIMEOUT:
- return
- elif val == WAIT_OBJECT_0 + len(handles):
- exit = win32gui.PumpWaitingMessages()
- if exit:
- self.callLater(0, self.stop)
- return
- elif val >= WAIT_OBJECT_0 and val < WAIT_OBJECT_0 + len(handles):
- fd, action = self._events[handles[val - WAIT_OBJECT_0]]
- log.callWithLogger(fd, self._runAction, action, fd)
-
- def _runWrite(self, fd):
- closed = 0
- try:
- closed = fd.doWrite()
- except:
- closed = sys.exc_info()[1]
- log.deferr()
-
- if closed:
- self.removeReader(fd)
- self.removeWriter(fd)
- try:
- fd.connectionLost(failure.Failure(closed))
- except:
- log.deferr()
- elif closed is None:
- return 1
-
- def _runAction(self, action, fd):
- try:
- closed = getattr(fd, action)()
- except:
- closed = sys.exc_info()[1]
- 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, childFDs=None):
- """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.")
- if childFDs is not None:
- raise ValueError(
- "Custom child file descriptor mappings are unsupported on "
- "this platform.")
- args, env = self._checkProcessArgs(args, env)
- return Process(self, processProtocol, executable, args, env, path)
-
-
-def install():
- threadable.init(1)
- r = Win32Reactor()
- import main
- main.installReactor(r)
-
-
-__all__ = ["Win32Reactor", "install"]
diff --git a/tools/buildbot/pylibs/twisted/internet/wxreactor.py b/tools/buildbot/pylibs/twisted/internet/wxreactor.py
deleted file mode 100644
index b0708bd..0000000
--- a/tools/buildbot/pylibs/twisted/internet/wxreactor.py
+++ /dev/null
@@ -1,181 +0,0 @@
-# Copyright (c) 2001-2006 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-This module provides wxPython event loop support for Twisted.
-
-In order to use this support, simply do the following::
-
- | from twisted.internet import wxreactor
- | wxreactor.install()
-
-Then, when your root wxApp has been created::
-
- | from twisted.internet import reactor
- | reactor.registerWxApp(yourApp)
- | reactor.run()
-
-Then use twisted.internet APIs as usual. Stop the event loop using
-reactor.stop(), not yourApp.ExitMainLoop().
-
-IMPORTANT: tests will fail when run under this reactor. This is
-expected and probably does not reflect on the reactor's ability to run
-real applications.
-
-Maintainer: U{Itamar Shtull-Trauring<mailto:twisted@itamarst.org>}
-"""
-
-import Queue
-try:
- from wx import PySimpleApp as wxPySimpleApp, CallAfter as wxCallAfter, \
- Timer as wxTimer
-except ImportError:
- # older version of wxPython:
- from wxPython.wx import wxPySimpleApp, wxCallAfter, wxTimer
-
-from twisted.python import log, runtime
-from twisted.internet import _threadedselect
-
-
-class ProcessEventsTimer(wxTimer):
- """
- Timer that tells wx to process pending events.
-
- This is necessary on OS X, probably due to a bug in wx, if we want
- wxCallAfters to be handled when modal dialogs, menus, etc. are open.
- """
- def __init__(self, wxapp):
- wxTimer.__init__(self)
- self.wxapp = wxapp
-
-
- def Notify(self):
- """
- Called repeatedly by wx event loop.
- """
- self.wxapp.ProcessPendingEvents()
-
-
-
-class WxReactor(_threadedselect.ThreadedSelectReactor):
- """
- wxPython reactor.
-
- wxPython drives the event loop, select() runs in a thread.
- """
-
- _stopping = False
-
- def registerWxApp(self, wxapp):
- """
- Register wxApp instance with the reactor.
- """
- self.wxapp = wxapp
-
- def _installSignalHandlersAgain(self):
- """
- wx sometimes removes our own signal handlers, so re-add them.
- """
- try:
- # make _handleSignals happy:
- import signal
- signal.signal(signal.SIGINT, signal.default_int_handler)
- except ImportError:
- return
- self._handleSignals()
-
- def stop(self):
- """
- Stop the reactor.
- """
- if self._stopping:
- return
- self._stopping = True
- _threadedselect.ThreadedSelectReactor.stop(self)
-
- def _runInMainThread(self, f):
- """
- Schedule function to run in main wx/Twisted thread.
-
- Called by the select() thread.
- """
- if hasattr(self, "wxapp"):
- wxCallAfter(f)
- else:
- # wx shutdown but twisted hasn't
- self._postQueue.put(f)
-
- def _stopWx(self):
- """
- Stop the wx event loop if it hasn't already been stopped.
-
- Called during Twisted event loop shutdown.
- """
- if hasattr(self, "wxapp"):
- self.wxapp.ExitMainLoop()
-
- def run(self, installSignalHandlers=True):
- """
- Start the reactor.
- """
- self._postQueue = Queue.Queue()
- if not hasattr(self, "wxapp"):
- log.msg("registerWxApp() was not called on reactor, "
- "registering my own wxApp instance.")
- self.registerWxApp(wxPySimpleApp())
-
- # start select() thread:
- self.interleave(self._runInMainThread,
- installSignalHandlers=installSignalHandlers)
- if installSignalHandlers:
- self.callLater(0, self._installSignalHandlersAgain)
-
- # add cleanup events:
- self.addSystemEventTrigger("after", "shutdown", self._stopWx)
- self.addSystemEventTrigger("after", "shutdown",
- lambda: self._postQueue.put(None))
-
- # On Mac OS X, work around wx bug by starting timer to ensure
- # wxCallAfter calls are always processed. We don't wake up as
- # often as we could since that uses too much CPU.
- if runtime.platform.isMacOSX():
- t = ProcessEventsTimer(self.wxapp)
- t.Start(2) # wake up every 2ms
-
- self.wxapp.MainLoop()
- wxapp = self.wxapp
- del self.wxapp
-
- if not self._stopping:
- # wx event loop exited without reactor.stop() being
- # called. At this point events from select() thread will
- # be added to _postQueue, but some may still be waiting
- # unprocessed in wx, thus the ProcessPendingEvents()
- # below.
- self.stop()
- wxapp.ProcessPendingEvents() # deal with any queued wxCallAfters
- while 1:
- try:
- f = self._postQueue.get(timeout=0.01)
- except Queue.Empty:
- continue
- else:
- if f is None:
- break
- try:
- f()
- except:
- log.err()
-
-
-def install():
- """
- Configure the twisted mainloop to be run inside the wxPython mainloop.
- """
- reactor = WxReactor()
- from twisted.internet.main import installReactor
- installReactor(reactor)
- return reactor
-
-
-__all__ = ['install']
diff --git a/tools/buildbot/pylibs/twisted/internet/wxsupport.py b/tools/buildbot/pylibs/twisted/internet/wxsupport.py
deleted file mode 100644
index eec84ac..0000000
--- a/tools/buildbot/pylibs/twisted/internet/wxsupport.py
+++ /dev/null
@@ -1,61 +0,0 @@
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-#
-"""Old method of wxPython support for Twisted.
-
-twisted.internet.wxreactor is probably a better choice.
-
-To use::
-
- | # given a wxApp instance called myWxAppInstance:
- | from twisted.internet import wxsupport
- | wxsupport.install(myWxAppInstance)
-
-Use Twisted's APIs for running and stopping the event loop, don't use
-wxPython's methods.
-
-On Windows the Twisted event loop might block when dialogs are open
-or menus are selected.
-
-Maintainer: U{Itamar Shtull-Trauring<mailto:twisted@itamarst.org>}
-"""
-
-import warnings
-warnings.warn("wxsupport is not fully functional on Windows, wxreactor is better.")
-
-# wxPython imports
-from wxPython.wx import wxApp
-
-# twisted imports
-from twisted.internet import reactor
-from twisted.python.runtime import platformType
-
-
-class wxRunner:
- """Make sure GUI events are handled."""
-
- def __init__(self, app):
- self.app = app
-
- def run(self):
- """
- Execute pending WX events followed by WX idle events and
- reschedule.
- """
- # run wx events
- while self.app.Pending():
- self.app.Dispatch()
-
- # run wx idle events
- self.app.ProcessIdle()
- reactor.callLater(0.02, self.run)
-
-
-def install(app):
- """Install the wxPython support, given a wxApp instance"""
- runner = wxRunner(app)
- reactor.callLater(0.02, runner.run)
-
-
-__all__ = ["install"]