code
stringlengths 501
5.19M
| package
stringlengths 2
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
#
"""Twisted inetd TAP support
Stability: semi-stable
Maintainer: U{Andrew Bennetts<mailto:[email protected]>}
Future Plans: more configurability.
"""
import os, pwd, grp, socket
from twisted.runner import inetd, inetdconf
from twisted.python import log, usage
from twisted.internet.protocol import ServerFactory
from twisted.application import internet, service as appservice
try:
import portmap
rpcOk = 1
except ImportError:
rpcOk = 0
# Protocol map
protocolDict = {'tcp': socket.IPPROTO_TCP, 'udp': socket.IPPROTO_UDP}
class Options(usage.Options):
optParameters = [
['rpc', 'r', '/etc/rpc', 'RPC procedure table file'],
['file', 'f', '/etc/inetd.conf', 'Service configuration file']
]
optFlags = [['nointernal', 'i', "Don't run internal services"]]
zsh_actions = {"file" : "_files -g '*.conf'"}
class RPCServer(internet.TCPServer):
def __init__(self, rpcVersions, rpcConf, proto, service):
internet.TCPServer.__init__(0, ServerFactory())
self.rpcConf = rpcConf
self.proto = proto
self.service = service
def startService(self):
internet.TCPServer.startService(self)
import portmap
portNo = self._port.getHost()[2]
service = self.service
for version in rpcVersions:
portmap.set(self.rpcConf.services[name], version, self.proto,
portNo)
inetd.forkPassingFD(service.program, service.programArgs,
os.environ, service.user, service.group, p)
def makeService(config):
s = appservice.MultiService()
conf = inetdconf.InetdConf()
conf.parseFile(open(config['file']))
rpcConf = inetdconf.RPCServicesConf()
try:
rpcConf.parseFile(open(config['rpc']))
except:
# We'll survive even if we can't read /etc/rpc
log.deferr()
for service in conf.services:
rpc = service.protocol.startswith('rpc/')
protocol = service.protocol
if rpc and not rpcOk:
log.msg('Skipping rpc service due to lack of rpc support')
continue
if rpc:
# RPC has extra options, so extract that
protocol = protocol[4:] # trim 'rpc/'
if not protocolDict.has_key(protocol):
log.msg('Bad protocol: ' + protocol)
continue
try:
name, rpcVersions = service.name.split('/')
except ValueError:
log.msg('Bad RPC service/version: ' + service.name)
continue
if not rpcConf.services.has_key(name):
log.msg('Unknown RPC service: ' + repr(service.name))
continue
try:
if '-' in rpcVersions:
start, end = map(int, rpcVersions.split('-'))
rpcVersions = range(start, end+1)
else:
rpcVersions = [int(rpcVersions)]
except ValueError:
log.msg('Bad RPC versions: ' + str(rpcVersions))
continue
if (protocol, service.socketType) not in [('tcp', 'stream'),
('udp', 'dgram')]:
log.msg('Skipping unsupported type/protocol: %s/%s'
% (service.socketType, service.protocol))
continue
# Convert the username into a uid (if necessary)
try:
service.user = int(service.user)
except ValueError:
try:
service.user = pwd.getpwnam(service.user)[2]
except KeyError:
log.msg('Unknown user: ' + service.user)
continue
# Convert the group name into a gid (if necessary)
if service.group is None:
# If no group was specified, use the user's primary group
service.group = pwd.getpwuid(service.user)[3]
else:
try:
service.group = int(service.group)
except ValueError:
try:
service.group = grp.getgrnam(service.group)[2]
except KeyError:
log.msg('Unknown group: ' + service.group)
continue
if service.program == 'internal':
if config['nointernal']:
continue
# Internal services can use a standard ServerFactory
if not inetd.internalProtocols.has_key(service.name):
log.msg('Unknown internal service: ' + service.name)
continue
factory = ServerFactory()
factory.protocol = inetd.internalProtocols[service.name]
elif rpc:
i = RPCServer(rpcVersions, rpcConf, proto, service)
i.setServiceParent(s)
continue
else:
# Non-internal non-rpc services use InetdFactory
factory = inetd.InetdFactory(service)
if protocol == 'tcp':
internet.TCPServer(service.port, factory).setServiceParent(s)
elif protocol == 'udp':
raise RuntimeError("not supporting UDP")
return s | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/runner/inetdtap.py | inetdtap.py |
#
"""Parser for inetd.conf files
Stability: stable
Maintainer: U{Andrew Bennetts<mailto:[email protected]>}
Future Plans: xinetd configuration file support?
"""
# Various exceptions
class InvalidConfError(Exception):
"""Invalid configuration file"""
class InvalidInetdConfError(InvalidConfError):
"""Invalid inetd.conf file"""
class InvalidServicesConfError(InvalidConfError):
"""Invalid services file"""
class InvalidRPCServicesConfError(InvalidConfError):
"""Invalid rpc services file"""
class UnknownService(Exception):
"""Unknown service name"""
class SimpleConfFile:
"""Simple configuration file parser superclass.
Filters out comments and empty lines (which includes lines that only
contain comments).
To use this class, override parseLine or parseFields.
"""
commentChar = '#'
defaultFilename = None
def parseFile(self, file=None):
"""Parse a configuration file
If file is None and self.defaultFilename is set, it will open
defaultFilename and use it.
"""
if file is None and self.defaultFilename:
file = open(self.defaultFilename,'r')
for line in file.readlines():
# Strip out comments
comment = line.find(self.commentChar)
if comment != -1:
line = line[:comment]
# Strip whitespace
line = line.strip()
# Skip empty lines (and lines which only contain comments)
if not line:
continue
self.parseLine(line)
def parseLine(self, line):
"""Override this.
By default, this will split the line on whitespace and call
self.parseFields (catching any errors).
"""
try:
self.parseFields(*line.split())
except ValueError:
raise InvalidInetdConfError, 'Invalid line: ' + repr(line)
def parseFields(self, *fields):
"""Override this."""
class InetdService:
"""A simple description of an inetd service."""
name = None
port = None
socketType = None
protocol = None
wait = None
user = None
group = None
program = None
programArgs = None
def __init__(self, name, port, socketType, protocol, wait, user, group,
program, programArgs):
self.name = name
self.port = port
self.socketType = socketType
self.protocol = protocol
self.wait = wait
self.user = user
self.group = group
self.program = program
self.programArgs = programArgs
class InetdConf(SimpleConfFile):
"""Configuration parser for a traditional UNIX inetd(8)"""
defaultFilename = '/etc/inetd.conf'
def __init__(self, knownServices=None):
self.services = []
if knownServices is None:
knownServices = ServicesConf()
knownServices.parseFile()
self.knownServices = knownServices
def parseFields(self, serviceName, socketType, protocol, wait, user,
program, *programArgs):
"""Parse an inetd.conf file.
Implemented from the description in the Debian inetd.conf man page.
"""
# Extract user (and optional group)
user, group = (user.split('.') + [None])[:2]
# Find the port for a service
port = self.knownServices.services.get((serviceName, protocol), None)
if not port and not protocol.startswith('rpc/'):
# FIXME: Should this be discarded/ignored, rather than throwing
# an exception?
try:
port = int(serviceName)
serviceName = 'unknown'
except:
raise UnknownService, "Unknown service: %s (%s)" \
% (serviceName, protocol)
self.services.append(InetdService(serviceName, port, socketType,
protocol, wait, user, group, program,
programArgs))
class ServicesConf(SimpleConfFile):
"""/etc/services parser
@ivar services: dict mapping service names to (port, protocol) tuples.
"""
defaultFilename = '/etc/services'
def __init__(self):
self.services = {}
def parseFields(self, name, portAndProtocol, *aliases):
try:
port, protocol = portAndProtocol.split('/')
port = long(port)
except:
raise InvalidServicesConfError, 'Invalid port/protocol:' + \
repr(portAndProtocol)
self.services[(name, protocol)] = port
for alias in aliases:
self.services[(alias, protocol)] = port
class RPCServicesConf(SimpleConfFile):
"""/etc/rpc parser
@ivar self.services: dict mapping rpc service names to rpc ports.
"""
defaultFilename = '/etc/rpc'
def __init__(self):
self.services = {}
def parseFields(self, name, port, *aliases):
try:
port = long(port)
except:
raise InvalidRPCServicesConfError, 'Invalid port:' + repr(port)
self.services[name] = port
for alias in aliases:
self.services[alias] = port | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/runner/inetdconf.py | inetdconf.py |
import code, sys, StringIO, tokenize
from twisted.conch import recvline
from twisted.internet import defer
from twisted.python.htmlizer import TokenPrinter
class FileWrapper:
"""Minimal write-file-like object.
Writes are translated into addOutput calls on an object passed to
__init__. Newlines are also converted from network to local style.
"""
softspace = 0
state = 'normal'
def __init__(self, o):
self.o = o
def flush(self):
pass
def write(self, data):
self.o.addOutput(data.replace('\r\n', '\n'))
def writelines(self, lines):
self.write(''.join(lines))
class ManholeInterpreter(code.InteractiveInterpreter):
"""Interactive Interpreter with special output and Deferred support.
Aside from the features provided by L{code.InteractiveInterpreter}, this
class captures sys.stdout output and redirects it to the appropriate
location (the Manhole protocol instance). It also treats Deferreds
which reach the top-level specially: each is formatted to the user with
a unique identifier and a new callback and errback added to it, each of
which will format the unique identifier and the result with which the
Deferred fires and then pass it on to the next participant in the
callback chain.
"""
numDeferreds = 0
def __init__(self, handler, locals=None, filename="<console>"):
code.InteractiveInterpreter.__init__(self, locals)
self._pendingDeferreds = {}
self.handler = handler
self.filename = filename
self.resetBuffer()
def resetBuffer(self):
"""Reset the input buffer."""
self.buffer = []
def push(self, line):
"""Push a line to the interpreter.
The line should not have a trailing newline; it may have
internal newlines. The line is appended to a buffer and the
interpreter's runsource() method is called with the
concatenated contents of the buffer as source. If this
indicates that the command was executed or invalid, the buffer
is reset; otherwise, the command is incomplete, and the buffer
is left as it was after the line was appended. The return
value is 1 if more input is required, 0 if the line was dealt
with in some way (this is the same as runsource()).
"""
self.buffer.append(line)
source = "\n".join(self.buffer)
more = self.runsource(source, self.filename)
if not more:
self.resetBuffer()
return more
def runcode(self, *a, **kw):
orighook, sys.displayhook = sys.displayhook, self.displayhook
try:
origout, sys.stdout = sys.stdout, FileWrapper(self.handler)
try:
code.InteractiveInterpreter.runcode(self, *a, **kw)
finally:
sys.stdout = origout
finally:
sys.displayhook = orighook
def displayhook(self, obj):
self.locals['_'] = obj
if isinstance(obj, defer.Deferred):
# XXX Ick, where is my "hasFired()" interface?
if hasattr(obj, "result"):
self.write(repr(obj))
elif id(obj) in self._pendingDeferreds:
self.write("<Deferred #%d>" % (self._pendingDeferreds[id(obj)][0],))
else:
d = self._pendingDeferreds
k = self.numDeferreds
d[id(obj)] = (k, obj)
self.numDeferreds += 1
obj.addCallbacks(self._cbDisplayDeferred, self._ebDisplayDeferred,
callbackArgs=(k, obj), errbackArgs=(k, obj))
self.write("<Deferred #%d>" % (k,))
elif obj is not None:
self.write(repr(obj))
def _cbDisplayDeferred(self, result, k, obj):
self.write("Deferred #%d called back: %r" % (k, result), True)
del self._pendingDeferreds[id(obj)]
return result
def _ebDisplayDeferred(self, failure, k, obj):
self.write("Deferred #%d failed: %r" % (k, failure.getErrorMessage()), True)
del self._pendingDeferreds[id(obj)]
return failure
def write(self, data, async=False):
self.handler.addOutput(data, async)
CTRL_C = '\x03'
CTRL_D = '\x04'
CTRL_BACKSLASH = '\x1c'
CTRL_L = '\x0c'
class Manhole(recvline.HistoricRecvLine):
"""Mediator between a fancy line source and an interactive interpreter.
This accepts lines from its transport and passes them on to a
L{ManholeInterpreter}. Control commands (^C, ^D, ^\) are also handled
with something approximating their normal terminal-mode behavior. It
can optionally be constructed with a dict which will be used as the
local namespace for any code executed.
"""
namespace = None
def __init__(self, namespace=None):
recvline.HistoricRecvLine.__init__(self, namespace)
if namespace is not None:
self.namespace = namespace.copy()
def connectionMade(self):
recvline.HistoricRecvLine.connectionMade(self)
self.interpreter = ManholeInterpreter(self, self.namespace)
self.keyHandlers[CTRL_C] = self.handle_INT
self.keyHandlers[CTRL_D] = self.handle_EOF
self.keyHandlers[CTRL_L] = self.handle_FF
self.keyHandlers[CTRL_BACKSLASH] = self.handle_QUIT
def handle_INT(self):
self.terminal.nextLine()
self.terminal.write("KeyboardInterrupt")
self.terminal.nextLine()
self.terminal.write(self.ps[self.pn])
self.lineBuffer = []
self.lineBufferIndex = 0
def handle_EOF(self):
if self.lineBuffer:
self.terminal.write('\a')
else:
self.handle_QUIT()
def handle_FF(self):
"""
Handle a 'form feed' byte - generally used to request a screen
refresh/redraw.
"""
self.terminal.eraseDisplay()
self.terminal.cursorHome()
self.drawInputLine()
def handle_QUIT(self):
self.terminal.loseConnection()
def _needsNewline(self):
w = self.terminal.lastWrite
return not w.endswith('\n') and not w.endswith('\x1bE')
def addOutput(self, bytes, async=False):
if async:
self.terminal.eraseLine()
self.terminal.cursorBackward(len(self.lineBuffer) + len(self.ps[self.pn]))
self.terminal.write(bytes)
if async:
if self._needsNewline():
self.terminal.nextLine()
self.terminal.write(self.ps[self.pn])
if self.lineBuffer:
oldBuffer = self.lineBuffer
self.lineBuffer = []
self.lineBufferIndex = 0
self._deliverBuffer(oldBuffer)
def lineReceived(self, line):
more = self.interpreter.push(line)
self.pn = bool(more)
if self._needsNewline():
self.terminal.nextLine()
self.terminal.write(self.ps[self.pn])
class VT102Writer:
"""Colorizer for Python tokens.
A series of tokens are written to instances of this object. Each is
colored in a particular way. The final line of the result of this is
generally added to the output.
"""
typeToColor = {
'identifier': '\x1b[31m',
'keyword': '\x1b[32m',
'parameter': '\x1b[33m',
'variable': '\x1b[1;33m',
'string': '\x1b[35m',
'number': '\x1b[36m',
'op': '\x1b[37m'}
normalColor = '\x1b[0m'
def __init__(self):
self.written = []
def color(self, type):
r = self.typeToColor.get(type, '')
return r
def write(self, token, type=None):
if token and token != '\r':
c = self.color(type)
if c:
self.written.append(c)
self.written.append(token)
if c:
self.written.append(self.normalColor)
def __str__(self):
s = ''.join(self.written)
return s.strip('\n').splitlines()[-1]
def lastColorizedLine(source):
"""Tokenize and colorize the given Python source.
Returns a VT102-format colorized version of the last line of C{source}.
"""
w = VT102Writer()
p = TokenPrinter(w.write).printtoken
s = StringIO.StringIO(source)
tokenize.tokenize(s.readline, p)
return str(w)
class ColoredManhole(Manhole):
"""A REPL which syntax colors input as users type it.
"""
def getSource(self):
"""Return a string containing the currently entered source.
This is only the code which will be considered for execution
next.
"""
return ('\n'.join(self.interpreter.buffer) +
'\n' +
''.join(self.lineBuffer))
def characterReceived(self, ch, moreCharactersComing):
if self.mode == 'insert':
self.lineBuffer.insert(self.lineBufferIndex, ch)
else:
self.lineBuffer[self.lineBufferIndex:self.lineBufferIndex+1] = [ch]
self.lineBufferIndex += 1
if moreCharactersComing:
# Skip it all, we'll get called with another character in
# like 2 femtoseconds.
return
if ch == ' ':
# Don't bother to try to color whitespace
self.terminal.write(ch)
return
source = self.getSource()
# Try to write some junk
try:
coloredLine = lastColorizedLine(source)
except tokenize.TokenError:
# We couldn't do it. Strange. Oh well, just add the character.
self.terminal.write(ch)
else:
# Success! Clear the source on this line.
self.terminal.eraseLine()
self.terminal.cursorBackward(len(self.lineBuffer) + len(self.ps[self.pn]) - 1)
# And write a new, colorized one.
self.terminal.write(self.ps[self.pn] + coloredLine)
# And move the cursor to where it belongs
n = len(self.lineBuffer) - self.lineBufferIndex
if n:
self.terminal.cursorBackward(n) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/manhole.py | manhole.py |
import struct
from zope.interface import implements
from twisted.application import internet
from twisted.internet import protocol, interfaces as iinternet, defer
from twisted.python import log
MODE = chr(1)
EDIT = 1
TRAPSIG = 2
MODE_ACK = 4
SOFT_TAB = 8
LIT_ECHO = 16
# Characters gleaned from the various (and conflicting) RFCs. Not all of these are correct.
NULL = chr(0) # No operation.
BEL = chr(7) # Produces an audible or
# visible signal (which does
# NOT move the print head).
BS = chr(8) # Moves the print head one
# character position towards
# the left margin.
HT = chr(9) # Moves the printer to the
# next horizontal tab stop.
# It remains unspecified how
# either party determines or
# establishes where such tab
# stops are located.
LF = chr(10) # Moves the printer to the
# next print line, keeping the
# same horizontal position.
VT = chr(11) # Moves the printer to the
# next vertical tab stop. It
# remains unspecified how
# either party determines or
# establishes where such tab
# stops are located.
FF = chr(12) # Moves the printer to the top
# of the next page, keeping
# the same horizontal position.
CR = chr(13) # Moves the printer to the left
# margin of the current line.
ECHO = chr(1) # User-to-Server: Asks the server to send
# Echos of the transmitted data.
SGA = chr(3) # Suppress Go Ahead. Go Ahead is silly
# and most modern servers should suppress
# it.
NAWS = chr(31) # Negotiate About Window Size. Indicate that
# information about the size of the terminal
# can be communicated.
LINEMODE = chr(34) # Allow line buffering to be
# negotiated about.
SE = chr(240) # End of subnegotiation parameters.
NOP = chr(241) # No operation.
DM = chr(242) # "Data Mark": The data stream portion
# of a Synch. This should always be
# accompanied by a TCP Urgent
# notification.
BRK = chr(243) # NVT character Break.
IP = chr(244) # The function Interrupt Process.
AO = chr(245) # The function Abort Output
AYT = chr(246) # The function Are You There.
EC = chr(247) # The function Erase Character.
EL = chr(248) # The function Erase Line
GA = chr(249) # The Go Ahead signal.
SB = chr(250) # Indicates that what follows is
# subnegotiation of the indicated
# option.
WILL = chr(251) # Indicates the desire to begin
# performing, or confirmation that
# you are now performing, the
# indicated option.
WONT = chr(252) # Indicates the refusal to perform,
# or continue performing, the
# indicated option.
DO = chr(253) # Indicates the request that the
# other party perform, or
# confirmation that you are expecting
# the other party to perform, the
# indicated option.
DONT = chr(254) # Indicates the demand that the
# other party stop performing,
# or confirmation that you are no
# longer expecting the other party
# to perform, the indicated option.
IAC = chr(255) # Data Byte 255. Introduces a
# telnet command.
LINEMODE_MODE = chr(1)
LINEMODE_EDIT = chr(1)
LINEMODE_TRAPSIG = chr(2)
LINEMODE_MODE_ACK = chr(4)
LINEMODE_SOFT_TAB = chr(8)
LINEMODE_LIT_ECHO = chr(16)
LINEMODE_FORWARDMASK = chr(2)
LINEMODE_SLC = chr(3)
LINEMODE_SLC_SYNCH = chr(1)
LINEMODE_SLC_BRK = chr(2)
LINEMODE_SLC_IP = chr(3)
LINEMODE_SLC_AO = chr(4)
LINEMODE_SLC_AYT = chr(5)
LINEMODE_SLC_EOR = chr(6)
LINEMODE_SLC_ABORT = chr(7)
LINEMODE_SLC_EOF = chr(8)
LINEMODE_SLC_SUSP = chr(9)
LINEMODE_SLC_EC = chr(10)
LINEMODE_SLC_EL = chr(11)
LINEMODE_SLC_EW = chr(12)
LINEMODE_SLC_RP = chr(13)
LINEMODE_SLC_LNEXT = chr(14)
LINEMODE_SLC_XON = chr(15)
LINEMODE_SLC_XOFF = chr(16)
LINEMODE_SLC_FORW1 = chr(17)
LINEMODE_SLC_FORW2 = chr(18)
LINEMODE_SLC_MCL = chr(19)
LINEMODE_SLC_MCR = chr(20)
LINEMODE_SLC_MCWL = chr(21)
LINEMODE_SLC_MCWR = chr(22)
LINEMODE_SLC_MCBOL = chr(23)
LINEMODE_SLC_MCEOL = chr(24)
LINEMODE_SLC_INSRT = chr(25)
LINEMODE_SLC_OVER = chr(26)
LINEMODE_SLC_ECR = chr(27)
LINEMODE_SLC_EWR = chr(28)
LINEMODE_SLC_EBOL = chr(29)
LINEMODE_SLC_EEOL = chr(30)
LINEMODE_SLC_DEFAULT = chr(3)
LINEMODE_SLC_VALUE = chr(2)
LINEMODE_SLC_CANTCHANGE = chr(1)
LINEMODE_SLC_NOSUPPORT = chr(0)
LINEMODE_SLC_LEVELBITS = chr(3)
LINEMODE_SLC_ACK = chr(128)
LINEMODE_SLC_FLUSHIN = chr(64)
LINEMODE_SLC_FLUSHOUT = chr(32)
LINEMODE_EOF = chr(236)
LINEMODE_SUSP = chr(237)
LINEMODE_ABORT = chr(238)
class ITelnetProtocol(iinternet.IProtocol):
def unhandledCommand(command, argument):
"""A command was received but not understood.
"""
def unhandledSubnegotiation(bytes):
"""A subnegotiation command was received but not understood.
"""
def enableLocal(option):
"""Enable the given option locally.
This should enable the given option on this side of the
telnet connection and return True. If False is returned,
the option will be treated as still disabled and the peer
will be notified.
"""
def enableRemote(option):
"""Indicate whether the peer should be allowed to enable this option.
Returns True if the peer should be allowed to enable this option,
False otherwise.
"""
def disableLocal(option):
"""Disable the given option locally.
Unlike enableLocal, this method cannot fail. The option must be
disabled.
"""
def disableRemote(option):
"""Indicate that the peer has disabled this option.
"""
class ITelnetTransport(iinternet.ITransport):
def do(option):
"""Indicate a desire for the peer to begin performing the given option.
Returns a Deferred that fires with True when the peer begins performing
the option, or False when the peer refuses to perform it. If the peer
is already performing the given option, the Deferred will fail with
L{AlreadyEnabled}. If a negotiation regarding this option is already
in progress, the Deferred will fail with L{AlreadyNegotiating}.
Note: It is currently possible that this Deferred will never fire,
if the peer never responds, or if the peer believes the option to
already be enabled.
"""
def dont(option):
"""Indicate a desire for the peer to cease performing the given option.
Returns a Deferred that fires with True when the peer ceases performing
the option. If the peer is not performing the given option, the
Deferred will fail with L{AlreadyDisabled}. If negotiation regarding
this option is already in progress, the Deferred will fail with
L{AlreadyNegotiating}.
Note: It is currently possible that this Deferred will never fire,
if the peer never responds, or if the peer believes the option to
already be disabled.
"""
def will(option):
"""Indicate our willingness to begin performing this option locally.
Returns a Deferred that fires with True when the peer agrees to allow
us to begin performing this option, or False if the peer refuses to
allow us to begin performing it. If the option is already enabled
locally, the Deferred will fail with L{AlreadyEnabled}. If negotiation
regarding this option is already in progress, the Deferred will fail with
L{AlreadyNegotiating}.
Note: It is currently possible that this Deferred will never fire,
if the peer never responds, or if the peer believes the option to
already be enabled.
"""
def wont(option):
"""Indicate that we will stop performing the given option.
Returns a Deferred that fires with True when the peer acknowledges
we have stopped performing this option. If the option is already
disabled locally, the Deferred will fail with L{AlreadyDisabled}.
If negotiation regarding this option is already in progress,
the Deferred will fail with L{AlreadyNegotiating}.
Note: It is currently possible that this Deferred will never fire,
if the peer never responds, or if the peer believes the option to
already be disabled.
"""
def requestNegotiation(about, bytes):
"""Send a subnegotiation request.
@param about: A byte indicating the feature being negotiated.
@param bytes: Any number of bytes containing specific information
about the negotiation being requested. No values in this string
need to be escaped, as this function will escape any value which
requires it.
"""
class TelnetError(Exception):
pass
class NegotiationError(TelnetError):
def __str__(self):
return self.__class__.__module__ + '.' + self.__class__.__name__ + ':' + repr(self.args[0])
class OptionRefused(NegotiationError):
pass
class AlreadyEnabled(NegotiationError):
pass
class AlreadyDisabled(NegotiationError):
pass
class AlreadyNegotiating(NegotiationError):
pass
class TelnetProtocol(protocol.Protocol):
implements(ITelnetProtocol)
def unhandledCommand(self, command, argument):
pass
def unhandledSubnegotiation(self, command, bytes):
pass
def enableLocal(self, option):
pass
def enableRemote(self, option):
pass
def disableLocal(self, option):
pass
def disableRemote(self, option):
pass
class Telnet(protocol.Protocol):
"""
@ivar commandMap: A mapping of bytes to callables. When a
telnet command is received, the command byte (the first byte
after IAC) is looked up in this dictionary. If a callable is
found, it is invoked with the argument of the command, or None
if the command takes no argument. Values should be added to
this dictionary if commands wish to be handled. By default,
only WILL, WONT, DO, and DONT are handled. These should not
be overridden, as this class handles them correctly and
provides an API for interacting with them.
@ivar negotiationMap: A mapping of bytes to callables. When
a subnegotiation command is received, the command byte (the
first byte after SB) is looked up in this dictionary. If
a callable is found, it is invoked with the argument of the
subnegotiation. Values should be added to this dictionary if
subnegotiations are to be handled. By default, no values are
handled.
@ivar options: A mapping of option bytes to their current
state. This state is likely of little use to user code.
Changes should not be made to it.
@ivar state: A string indicating the current parse state. It
can take on the values "data", "escaped", "command", "newline",
"subnegotiation", and "subnegotiation-escaped". Changes
should not be made to it.
@ivar transport: This protocol's transport object.
"""
# One of a lot of things
state = 'data'
def __init__(self):
self.options = {}
self.negotiationMap = {}
self.commandMap = {
WILL: self.telnet_WILL,
WONT: self.telnet_WONT,
DO: self.telnet_DO,
DONT: self.telnet_DONT}
def _write(self, bytes):
self.transport.write(bytes)
class _OptionState:
class _Perspective:
state = 'no'
negotiating = False
onResult = None
def __str__(self):
return self.state + ('*' * self.negotiating)
def __init__(self):
self.us = self._Perspective()
self.him = self._Perspective()
def __repr__(self):
return '<_OptionState us=%s him=%s>' % (self.us, self.him)
def getOptionState(self, opt):
return self.options.setdefault(opt, self._OptionState())
def _do(self, option):
self._write(IAC + DO + option)
def _dont(self, option):
self._write(IAC + DONT + option)
def _will(self, option):
self._write(IAC + WILL + option)
def _wont(self, option):
self._write(IAC + WONT + option)
def will(self, option):
"""Indicate our willingness to enable an option.
"""
s = self.getOptionState(option)
if s.us.negotiating or s.him.negotiating:
return defer.fail(AlreadyNegotiating(option))
elif s.us.state == 'yes':
return defer.fail(AlreadyEnabled(option))
else:
s.us.negotiating = True
s.us.onResult = d = defer.Deferred()
self._will(option)
return d
def wont(self, option):
"""Indicate we are not willing to enable an option.
"""
s = self.getOptionState(option)
if s.us.negotiating or s.him.negotiating:
return defer.fail(AlreadyNegotiating(option))
elif s.us.state == 'no':
return defer.fail(AlreadyDisabled(option))
else:
s.us.negotiating = True
s.us.onResult = d = defer.Deferred()
self._wont(option)
return d
def do(self, option):
s = self.getOptionState(option)
if s.us.negotiating or s.him.negotiating:
return defer.fail(AlreadyNegotiating(option))
elif s.him.state == 'yes':
return defer.fail(AlreadyEnabled(option))
else:
s.him.negotiating = True
s.him.onResult = d = defer.Deferred()
self._do(option)
return d
def dont(self, option):
s = self.getOptionState(option)
if s.us.negotiating or s.him.negotiating:
return defer.fail(AlreadyNegotiating(option))
elif s.him.state == 'no':
return defer.fail(AlreadyDisabled(option))
else:
s.him.negotiating = True
s.him.onResult = d = defer.Deferred()
self._dont(option)
return d
def requestNegotiation(self, about, bytes):
bytes = bytes.replace(IAC, IAC * 2)
self._write(IAC + SB + bytes + IAC + SE)
def dataReceived(self, data):
# Most grossly inefficient implementation ever
for b in data:
if self.state == 'data':
if b == IAC:
self.state = 'escaped'
elif b == '\r':
self.state = 'newline'
else:
self.applicationDataReceived(b)
elif self.state == 'escaped':
if b == IAC:
self.applicationDataReceived(b)
self.state = 'data'
elif b == SB:
self.state = 'subnegotiation'
self.commands = []
elif b in (NOP, DM, BRK, IP, AO, AYT, EC, EL, GA):
self.state = 'data'
self.commandReceived(b, None)
elif b in (WILL, WONT, DO, DONT):
self.state = 'command'
self.command = b
else:
raise ValueError("Stumped", b)
elif self.state == 'command':
self.state = 'data'
command = self.command
del self.command
self.commandReceived(command, b)
elif self.state == 'newline':
if b == '\n':
self.applicationDataReceived('\n')
elif b == '\0':
self.applicationDataReceived('\r')
else:
self.applicationDataReceived('\r' + b)
self.state = 'data'
elif self.state == 'subnegotiation':
if b == IAC:
self.state = 'subnegotiation-escaped'
else:
self.commands.append(b)
elif self.state == 'subnegotiation-escaped':
if b == SE:
self.state = 'data'
commands = self.commands
del self.commands
self.negotiate(commands)
else:
self.state = 'subnegotiation'
self.commands.append(b)
else:
raise ValueError("How'd you do this?")
def connectionLost(self, reason):
for state in self.options.values():
if state.us.onResult is not None:
d = state.us.onResult
state.us.onResult = None
d.errback(reason)
if state.him.onResult is not None:
d = state.him.onResult
state.him.onResult = None
d.errback(reason)
def applicationDataReceived(self, bytes):
"""Called with application-level data.
"""
def unhandledCommand(self, command, argument):
"""Called for commands for which no handler is installed.
"""
def commandReceived(self, command, argument):
cmdFunc = self.commandMap.get(command)
if cmdFunc is None:
self.unhandledCommand(command, argument)
else:
cmdFunc(argument)
def unhandledSubnegotiation(self, command, bytes):
"""Called for subnegotiations for which no handler is installed.
"""
def negotiate(self, bytes):
command, bytes = bytes[0], bytes[1:]
cmdFunc = self.negotiationMap.get(command)
if cmdFunc is None:
self.unhandledSubnegotiation(command, bytes)
else:
cmdFunc(bytes)
def telnet_WILL(self, option):
s = self.getOptionState(option)
self.willMap[s.him.state, s.him.negotiating](self, s, option)
def will_no_false(self, state, option):
# He is unilaterally offering to enable an option.
if self.enableRemote(option):
state.him.state = 'yes'
self._do(option)
else:
self._dont(option)
def will_no_true(self, state, option):
# Peer agreed to enable an option in response to our request.
state.him.state = 'yes'
state.him.negotiating = False
d = state.him.onResult
state.him.onResult = None
d.callback(True)
assert self.enableRemote(option), "enableRemote must return True in this context (for option %r)" % (option,)
def will_yes_false(self, state, option):
# He is unilaterally offering to enable an already-enabled option.
# Ignore this.
pass
def will_yes_true(self, state, option):
# This is a bogus state. It is here for completeness. It will
# never be entered.
assert False, "will_yes_true can never be entered, but was called with %r, %r" % (state, option)
willMap = {('no', False): will_no_false, ('no', True): will_no_true,
('yes', False): will_yes_false, ('yes', True): will_yes_true}
def telnet_WONT(self, option):
s = self.getOptionState(option)
self.wontMap[s.him.state, s.him.negotiating](self, s, option)
def wont_no_false(self, state, option):
# He is unilaterally demanding that an already-disabled option be/remain disabled.
# Ignore this (although we could record it and refuse subsequent enable attempts
# from our side - he can always refuse them again though, so we won't)
pass
def wont_no_true(self, state, option):
# Peer refused to enable an option in response to our request.
state.him.negotiating = False
d = state.him.onResult
state.him.onResult = None
d.errback(OptionRefused(option))
def wont_yes_false(self, state, option):
# Peer is unilaterally demanding that an option be disabled.
state.him.state = 'no'
self.disableRemote(option)
self._dont(option)
def wont_yes_true(self, state, option):
# Peer agreed to disable an option at our request.
state.him.state = 'no'
state.him.negotiating = False
d = state.him.onResult
state.him.onResult = None
d.callback(True)
self.disableRemote(option)
wontMap = {('no', False): wont_no_false, ('no', True): wont_no_true,
('yes', False): wont_yes_false, ('yes', True): wont_yes_true}
def telnet_DO(self, option):
s = self.getOptionState(option)
self.doMap[s.us.state, s.us.negotiating](self, s, option)
def do_no_false(self, state, option):
# Peer is unilaterally requesting that we enable an option.
if self.enableLocal(option):
state.us.state = 'yes'
self._will(option)
else:
self._wont(option)
def do_no_true(self, state, option):
# Peer agreed to allow us to enable an option at our request.
state.us.state = 'yes'
state.us.negotiating = False
d = state.us.onResult
state.us.onResult = None
d.callback(True)
self.enableLocal(option)
def do_yes_false(self, state, option):
# Peer is unilaterally requesting us to enable an already-enabled option.
# Ignore this.
pass
def do_yes_true(self, state, option):
# This is a bogus state. It is here for completeness. It will never be
# entered.
assert False, "do_yes_true can never be entered, but was called with %r, %r" % (state, option)
doMap = {('no', False): do_no_false, ('no', True): do_no_true,
('yes', False): do_yes_false, ('yes', True): do_yes_true}
def telnet_DONT(self, option):
s = self.getOptionState(option)
self.dontMap[s.us.state, s.us.negotiating](self, s, option)
def dont_no_false(self, state, option):
# Peer is unilaterally demanding us to disable an already-disabled option.
# Ignore this.
pass
def dont_no_true(self, state, option):
# This is a bogus state. It is here for completeness. It will never be
# entered.
assert False, "dont_no_true can never be entered, but was called with %r, %r" % (state, option)
def dont_yes_false(self, state, option):
# Peer is unilaterally demanding we disable an option.
state.us.state = 'no'
self.disableLocal(option)
self._wont(option)
def dont_yes_true(self, state, option):
# Peer acknowledged our notice that we will disable an option.
state.us.state = 'no'
state.us.negotiating = False
d = state.us.onResult
state.us.onResult = None
d.callback(True)
self.disableLocal(option)
dontMap = {('no', False): dont_no_false, ('no', True): dont_no_true,
('yes', False): dont_yes_false, ('yes', True): dont_yes_true}
def enableLocal(self, option):
return self.protocol.enableLocal(option)
def enableRemote(self, option):
return self.protocol.enableRemote(option)
def disableLocal(self, option):
return self.protocol.disableLocal(option)
def disableRemote(self, option):
return self.protocol.disableRemote(option)
class ProtocolTransportMixin:
def write(self, bytes):
self.transport.write(bytes.replace('\n', '\r\n'))
def writeSequence(self, seq):
self.transport.writeSequence(seq)
def loseConnection(self):
self.transport.loseConnection()
def getHost(self):
return self.transport.getHost()
def getPeer(self):
return self.transport.getPeer()
class TelnetTransport(Telnet, ProtocolTransportMixin):
"""
@ivar protocol: An instance of the protocol to which this
transport is connected, or None before the connection is
established and after it is lost.
@ivar protocolFactory: A callable which returns protocol instances
which provide L{ITelnetProtocol}. This will be invoked when a
connection is established. It is passed *protocolArgs and
**protocolKwArgs.
@ivar protocolArgs: A tuple of additional arguments to
pass to protocolFactory.
@ivar protocolKwArgs: A dictionary of additional arguments
to pass to protocolFactory.
"""
disconnecting = False
protocolFactory = None
protocol = None
def __init__(self, protocolFactory=None, *a, **kw):
Telnet.__init__(self)
if protocolFactory is not None:
self.protocolFactory = protocolFactory
self.protocolArgs = a
self.protocolKwArgs = kw
def connectionMade(self):
if self.protocolFactory is not None:
self.protocol = self.protocolFactory(*self.protocolArgs, **self.protocolKwArgs)
assert ITelnetProtocol.providedBy(self.protocol)
try:
factory = self.factory
except AttributeError:
pass
else:
self.protocol.factory = factory
self.protocol.makeConnection(self)
def connectionLost(self, reason):
Telnet.connectionLost(self, reason)
if self.protocol is not None:
try:
self.protocol.connectionLost(reason)
finally:
del self.protocol
def enableLocal(self, option):
return self.protocol.enableLocal(option)
def enableRemote(self, option):
return self.protocol.enableRemote(option)
def disableLocal(self, option):
return self.protocol.disableLocal(option)
def disableRemote(self, option):
return self.protocol.disableRemote(option)
def unhandledSubnegotiation(self, command, bytes):
self.protocol.unhandledSubnegotiation(command, bytes)
def unhandledCommand(self, command, argument):
self.protocol.unhandledCommand(command, argument)
def applicationDataReceived(self, bytes):
self.protocol.dataReceived(bytes)
def write(self, data):
ProtocolTransportMixin.write(self, data.replace('\xff','\xff\xff'))
class TelnetBootstrapProtocol(TelnetProtocol, ProtocolTransportMixin):
implements()
protocol = None
def __init__(self, protocolFactory, *args, **kw):
self.protocolFactory = protocolFactory
self.protocolArgs = args
self.protocolKwArgs = kw
def connectionMade(self):
self.transport.negotiationMap[NAWS] = self.telnet_NAWS
self.transport.negotiationMap[LINEMODE] = self.telnet_LINEMODE
for opt in (LINEMODE, NAWS, SGA):
self.transport.do(opt).addErrback(log.err)
for opt in (ECHO,):
self.transport.will(opt).addErrback(log.err)
self.protocol = self.protocolFactory(*self.protocolArgs, **self.protocolKwArgs)
try:
factory = self.factory
except AttributeError:
pass
else:
self.protocol.factory = factory
self.protocol.makeConnection(self)
def connectionLost(self, reason):
if self.protocol is not None:
try:
self.protocol.connectionLost(reason)
finally:
del self.protocol
def dataReceived(self, data):
self.protocol.dataReceived(data)
def enableLocal(self, opt):
if opt == ECHO:
return True
elif opt == SGA:
return True
else:
return False
def enableRemote(self, opt):
if opt == LINEMODE:
self.transport.requestNegotiation(LINEMODE, MODE + chr(TRAPSIG))
return True
elif opt == NAWS:
return True
elif opt == SGA:
return True
else:
return False
def telnet_NAWS(self, bytes):
# NAWS is client -> server *only*. self.protocol will
# therefore be an ITerminalTransport, the `.protocol'
# attribute of which will be an ITerminalProtocol. Maybe.
# You know what, XXX TODO clean this up.
if len(bytes) == 4:
width, height = struct.unpack('!HH', ''.join(bytes))
self.protocol.terminalProtocol.terminalSize(width, height)
else:
log.msg("Wrong number of NAWS bytes")
linemodeSubcommands = {
LINEMODE_SLC: 'SLC'}
def telnet_LINEMODE(self, bytes):
revmap = {}
linemodeSubcommand = bytes[0]
if 0:
# XXX TODO: This should be enabled to parse linemode subnegotiation.
getattr(self, 'linemode_' + self.linemodeSubcommands[linemodeSubcommand])(bytes[1:])
def linemode_SLC(self, bytes):
chunks = zip(*[iter(bytes)]*3)
for slcFunction, slcValue, slcWhat in chunks:
# Later, we should parse stuff.
'SLC', ord(slcFunction), ord(slcValue), ord(slcWhat)
from twisted.protocols import basic
class StatefulTelnetProtocol(basic.LineReceiver, TelnetProtocol):
delimiter = '\n'
state = 'Discard'
def connectionLost(self, reason):
basic.LineReceiver.connectionLost(self, reason)
TelnetProtocol.connectionLost(self, reason)
def lineReceived(self, line):
oldState = self.state
newState = getattr(self, "telnet_" + oldState)(line)
if newState is not None:
if self.state == oldState:
self.state = newState
else:
log.msg("Warning: state changed and new state returned")
def telnet_Discard(self, line):
pass
from twisted.cred import credentials
class AuthenticatingTelnetProtocol(StatefulTelnetProtocol):
"""A protocol which prompts for credentials and attempts to authenticate them.
Username and password prompts are given (the password is obscured). When the
information is collected, it is passed to a portal and an avatar implementing
L{ITelnetProtocol} is requested. If an avatar is returned, it connected to this
protocol's transport, and this protocol's transport is connected to it.
Otherwise, the user is re-prompted for credentials.
"""
state = "User"
protocol = None
def __init__(self, portal):
self.portal = portal
def connectionMade(self):
self.transport.write("Username: ")
def connectionLost(self, reason):
StatefulTelnetProtocol.connectionLost(self, reason)
if self.protocol is not None:
try:
self.protocol.connectionLost(reason)
self.logout()
finally:
del self.protocol, self.logout
def telnet_User(self, line):
self.username = line
self.transport.will(ECHO)
self.transport.write("Password: ")
return 'Password'
def telnet_Password(self, line):
username, password = self.username, line
del self.username
def login(ignored):
creds = credentials.UsernamePassword(username, password)
d = self.portal.login(creds, None, ITelnetProtocol)
d.addCallback(self._cbLogin)
d.addErrback(self._ebLogin)
self.transport.wont(ECHO).addCallback(login)
return 'Discard'
def _cbLogin(self, ial):
interface, protocol, logout = ial
assert interface is ITelnetProtocol
self.protocol = protocol
self.logout = logout
self.state = 'Command'
protocol.makeConnection(self.transport)
self.transport.protocol = protocol
def _ebLogin(self, failure):
self.transport.write("\nAuthentication failed\n")
self.transport.write("Username: ")
self.state = "User"
__all__ = [
# Exceptions
'TelnetError', 'NegotiationError', 'OptionRefused',
'AlreadyNegotiating', 'AlreadyEnabled', 'AlreadyDisabled',
# Interfaces
'ITelnetProtocol', 'ITelnetTransport',
# Other stuff, protocols, etc.
'Telnet', 'TelnetProtocol', 'TelnetTransport',
'TelnetBootstrapProtocol',
] | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/telnet.py | telnet.py |
from zope.interface import Interface
class IConchUser(Interface):
"""A user who has been authenticated to Cred through Conch. This is
the interface between the SSH connection and the user.
@ivar conn: The SSHConnection object for this user.
"""
def lookupChannel(channelType, windowSize, maxPacket, data):
"""
The other side requested a channel of some sort.
channelType is the type of channel being requested,
windowSize is the initial size of the remote window,
maxPacket is the largest packet we should send,
data is any other packet data (often nothing).
We return a subclass of L{SSHChannel<ssh.channel.SSHChannel>}. If
an appropriate channel can not be found, an exception will be
raised. If a L{ConchError<error.ConchError>} is raised, the .value
will be the message, and the .data will be the error code.
@type channelType: C{str}
@type windowSize: C{int}
@type maxPacket: C{int}
@type data: C{str}
@rtype: subclass of L{SSHChannel}/C{tuple}
"""
def lookupSubsystem(subsystem, data):
"""
The other side requested a subsystem.
subsystem is the name of the subsystem being requested.
data is any other packet data (often nothing).
We return a L{Protocol}.
"""
def gotGlobalRequest(requestType, data):
"""
A global request was sent from the other side.
By default, this dispatches to a method 'channel_channelType' with any
non-alphanumerics in the channelType replace with _'s. If it cannot
find a suitable method, it returns an OPEN_UNKNOWN_CHANNEL_TYPE error.
The method is called with arguments of windowSize, maxPacket, data.
"""
class ISession(Interface):
def getPty(term, windowSize, modes):
"""
Get a psuedo-terminal for use by a shell or command.
If a psuedo-terminal is not available, or the request otherwise
fails, raise an exception.
"""
def openShell(proto):
"""
Open a shell and connect it to proto.
@param proto: a L{ProcessProtocol} instance.
"""
def execCommand(proto, command):
"""
Execute a command.
@param proto: a L{ProcessProtocol} instance.
"""
def windowChanged(newWindowSize):
"""
Called when the size of the remote screen has changed.
"""
def eofReceived():
"""
Called when the other side has indicated no more data will be sent.
"""
def closed():
"""
Called when the session is closed.
"""
class ISFTPServer(Interface):
"""
The only attribute of this class is "avatar". It is the avatar
returned by the Realm that we are authenticated with, and
represents the logged-in user. Each method should check to verify
that the user has permission for their actions.
"""
def gotVersion(otherVersion, extData):
"""
Called when the client sends their version info.
otherVersion is an integer representing the version of the SFTP
protocol they are claiming.
extData is a dictionary of extended_name : extended_data items.
These items are sent by the client to indicate additional features.
This method should return a dictionary of extended_name : extended_data
items. These items are the additional features (if any) supported
by the server.
"""
return {}
def openFile(filename, flags, attrs):
"""
Called when the clients asks to open a file.
@param filename: a string representing the file to open.
@param flags: an integer of the flags to open the file with, ORed together.
The flags and their values are listed at the bottom of this file.
@param attrs: a list of attributes to open the file with. It is a
dictionary, consisting of 0 or more keys. The possible keys are::
size: the size of the file in bytes
uid: the user ID of the file as an integer
gid: the group ID of the file as an integer
permissions: the permissions of the file with as an integer.
the bit representation of this field is defined by POSIX.
atime: the access time of the file as seconds since the epoch.
mtime: the modification time of the file as seconds since the epoch.
ext_*: extended attributes. The server is not required to
understand this, but it may.
NOTE: there is no way to indicate text or binary files. it is up
to the SFTP client to deal with this.
This method returns an object that meets the ISFTPFile interface.
Alternatively, it can return a L{Deferred} that will be called back
with the object.
"""
def removeFile(filename):
"""
Remove the given file.
This method returns when the remove succeeds, or a Deferred that is
called back when it succeeds.
@param filename: the name of the file as a string.
"""
def renameFile(oldpath, newpath):
"""
Rename the given file.
This method returns when the rename succeeds, or a L{Deferred} that is
called back when it succeeds.
@param oldpath: the current location of the file.
@param newpath: the new file name.
"""
def makeDirectory(path, attrs):
"""
Make a directory.
This method returns when the directory is created, or a Deferred that
is called back when it is created.
@param path: the name of the directory to create as a string.
@param attrs: a dictionary of attributes to create the directory with.
Its meaning is the same as the attrs in the L{openFile} method.
"""
def removeDirectory(path):
"""
Remove a directory (non-recursively)
It is an error to remove a directory that has files or directories in
it.
This method returns when the directory is removed, or a Deferred that
is called back when it is removed.
@param path: the directory to remove.
"""
def openDirectory(path):
"""
Open a directory for scanning.
This method returns an iterable object that has a close() method,
or a Deferred that is called back with same.
The close() method is called when the client is finished reading
from the directory. At this point, the iterable will no longer
be used.
The iterable should return triples of the form (filename,
longname, attrs) or Deferreds that return the same. The
sequence must support __getitem__, but otherwise may be any
'sequence-like' object.
filename is the name of the file relative to the directory.
logname is an expanded format of the filename. The recommended format
is:
-rwxr-xr-x 1 mjos staff 348911 Mar 25 14:29 t-filexfer
1234567890 123 12345678 12345678 12345678 123456789012
The first line is sample output, the second is the length of the field.
The fields are: permissions, link count, user owner, group owner,
size in bytes, modification time.
attrs is a dictionary in the format of the attrs argument to openFile.
@param path: the directory to open.
"""
def getAttrs(path, followLinks):
"""
Return the attributes for the given path.
This method returns a dictionary in the same format as the attrs
argument to openFile or a Deferred that is called back with same.
@param path: the path to return attributes for as a string.
@param followLinks: a boolean. If it is True, follow symbolic links
and return attributes for the real path at the base. If it is False,
return attributes for the specified path.
"""
def setAttrs(path, attrs):
"""
Set the attributes for the path.
This method returns when the attributes are set or a Deferred that is
called back when they are.
@param path: the path to set attributes for as a string.
@param attrs: a dictionary in the same format as the attrs argument to
L{openFile}.
"""
def readLink(path):
"""
Find the root of a set of symbolic links.
This method returns the target of the link, or a Deferred that
returns the same.
@param path: the path of the symlink to read.
"""
def makeLink(linkPath, targetPath):
"""
Create a symbolic link.
This method returns when the link is made, or a Deferred that
returns the same.
@param linkPath: the pathname of the symlink as a string.
@param targetPath: the path of the target of the link as a string.
"""
def realPath(path):
"""
Convert any path to an absolute path.
This method returns the absolute path as a string, or a Deferred
that returns the same.
@param path: the path to convert as a string.
"""
def extendedRequest(extendedName, extendedData):
"""
This is the extension mechanism for SFTP. The other side can send us
arbitrary requests.
If we don't implement the request given by extendedName, raise
NotImplementedError.
The return value is a string, or a Deferred that will be called
back with a string.
@param extendedName: the name of the request as a string.
@param extendedData: the data the other side sent with the request,
as a string.
"""
class ISFTPFile(Interface):
"""
This represents an open file on the server. An object adhering to this
interface should be returned from L{openFile}().
"""
def close():
"""
Close the file.
This method returns nothing if the close succeeds immediately, or a
Deferred that is called back when the close succeeds.
"""
def readChunk(offset, length):
"""
Read from the file.
If EOF is reached before any data is read, raise EOFError.
This method returns the data as a string, or a Deferred that is
called back with same.
@param offset: an integer that is the index to start from in the file.
@param length: the maximum length of data to return. The actual amount
returned may less than this. For normal disk files, however,
this should read the requested number (up to the end of the file).
"""
def writeChunk(offset, data):
"""
Write to the file.
This method returns when the write completes, or a Deferred that is
called when it completes.
@param offset: an integer that is the index to start from in the file.
@param data: a string that is the data to write.
"""
def getAttrs():
"""
Return the attributes for the file.
This method returns a dictionary in the same format as the attrs
argument to L{openFile} or a L{Deferred} that is called back with same.
"""
def setAttrs(attrs):
"""
Set the attributes for the file.
This method returns when the attributes are set or a Deferred that is
called back when they are.
@param attrs: a dictionary in the same format as the attrs argument to
L{openFile}.
""" | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/interfaces.py | interfaces.py |
from zope.interface import implements
from twisted.internet import protocol
from twisted.application import service, strports
from twisted.conch.ssh import session
from twisted.conch import interfaces as iconch
from twisted.cred import portal, checkers
from twisted.python import usage
from twisted.conch.insults import insults
from twisted.conch import manhole, manhole_ssh, telnet
class makeTelnetProtocol:
def __init__(self, portal):
self.portal = portal
def __call__(self):
auth = telnet.AuthenticatingTelnetProtocol
args = (self.portal,)
return telnet.TelnetTransport(auth, *args)
class chainedProtocolFactory:
def __init__(self, namespace):
self.namespace = namespace
def __call__(self):
return insults.ServerProtocol(manhole.ColoredManhole, self.namespace)
class _StupidRealm:
implements(portal.IRealm)
def __init__(self, proto, *a, **kw):
self.protocolFactory = proto
self.protocolArgs = a
self.protocolKwArgs = kw
def requestAvatar(self, avatarId, *interfaces):
if telnet.ITelnetProtocol in interfaces:
return (telnet.ITelnetProtocol,
self.protocolFactory(*self.protocolArgs, **self.protocolKwArgs),
lambda: None)
raise NotImplementedError()
class Options(usage.Options):
optParameters = [
["telnetPort", "t", None, "strports description of the address on which to listen for telnet connections"],
["sshPort", "s", None, "strports description of the address on which to listen for ssh connections"],
["passwd", "p", "/etc/passwd", "name of a passwd(5)-format username/password file"]]
def __init__(self):
usage.Options.__init__(self)
self.users = []
self['namespace'] = None
def opt_user(self, name):
self.users.append(name)
def postOptions(self):
if self['telnetPort'] is None and self['sshPort'] is None:
raise usage.UsageError("At least one of --telnetPort and --sshPort must be specified")
def makeService(options):
"""Create a manhole server service.
@type options: C{dict}
@param options: A mapping describing the configuration of
the desired service. Recognized key/value pairs are::
"telnetPort": strports description of the address on which
to listen for telnet connections. If None,
no telnet service will be started.
"sshPort": strports description of the address on which to
listen for ssh connections. If None, no ssh
service will be started.
"namespace": dictionary containing desired initial locals
for manhole connections. If None, an empty
dictionary will be used.
"passwd": Name of a passwd(5)-format username/password file.
@rtype: L{twisted.application.service.IService}
@return: A manhole service.
"""
svc = service.MultiService()
namespace = options['namespace']
if namespace is None:
namespace = {}
checker = checkers.FilePasswordDB(options['passwd'])
if options['telnetPort']:
telnetRealm = _StupidRealm(telnet.TelnetBootstrapProtocol,
insults.ServerProtocol,
manhole.ColoredManhole,
namespace)
telnetPortal = portal.Portal(telnetRealm, [checker])
telnetFactory = protocol.ServerFactory()
telnetFactory.protocol = makeTelnetProtocol(telnetPortal)
telnetService = strports.service(options['telnetPort'],
telnetFactory)
telnetService.setServiceParent(svc)
if options['sshPort']:
sshRealm = manhole_ssh.TerminalRealm()
sshRealm.chainedProtocolFactory = chainedProtocolFactory(namespace)
sshPortal = portal.Portal(sshRealm, [checker])
sshFactory = manhole_ssh.ConchFactory(sshPortal)
sshService = strports.service(options['sshPort'],
sshFactory)
sshService.setServiceParent(svc)
return svc | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/manhole_tap.py | manhole_tap.py |
import string
from zope.interface import implements
from twisted.conch.insults import insults, helper
from twisted.python import log, reflect
_counters = {}
class Logging(object):
"""Wrapper which logs attribute lookups.
This was useful in debugging something, I guess. I forget what.
It can probably be deleted or moved somewhere more appropriate.
Nothing special going on here, really.
"""
def __init__(self, original):
self.original = original
key = reflect.qual(original.__class__)
count = _counters.get(key, 0)
_counters[key] = count + 1
self._logFile = file(key + '-' + str(count), 'w')
def __str__(self):
return str(super(Logging, self).__getattribute__('original'))
def __repr__(self):
return repr(super(Logging, self).__getattribute__('original'))
def __getattribute__(self, name):
original = super(Logging, self).__getattribute__('original')
logFile = super(Logging, self).__getattribute__('_logFile')
logFile.write(name + '\n')
return getattr(original, name)
class TransportSequence(object):
"""An L{ITerminalTransport} implementation which forwards calls to
one or more other L{ITerminalTransport}s.
This is a cheap way for servers to keep track of the state they
expect the client to see, since all terminal manipulations can be
send to the real client and to a terminal emulator that lives in
the server process.
"""
implements(insults.ITerminalTransport)
for keyID in ('UP_ARROW', 'DOWN_ARROW', 'RIGHT_ARROW', 'LEFT_ARROW',
'HOME', 'INSERT', 'DELETE', 'END', 'PGUP', 'PGDN',
'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9',
'F10', 'F11', 'F12'):
exec '%s = object()' % (keyID,)
TAB = '\t'
BACKSPACE = '\x7f'
def __init__(self, *transports):
assert transports, "Cannot construct a TransportSequence with no transports"
self.transports = transports
for method in insults.ITerminalTransport:
exec """\
def %s(self, *a, **kw):
for tpt in self.transports:
result = tpt.%s(*a, **kw)
return result
""" % (method, method)
class LocalTerminalBufferMixin(object):
"""A mixin for RecvLine subclasses which records the state of the terminal.
This is accomplished by performing all L{ITerminalTransport} operations on both
the transport passed to makeConnection and an instance of helper.TerminalBuffer.
@ivar terminalCopy: A L{helper.TerminalBuffer} instance which efforts
will be made to keep up to date with the actual terminal
associated with this protocol instance.
"""
def makeConnection(self, transport):
self.terminalCopy = helper.TerminalBuffer()
self.terminalCopy.connectionMade()
return super(LocalTerminalBufferMixin, self).makeConnection(
TransportSequence(transport, self.terminalCopy))
def __str__(self):
return str(self.terminalCopy)
class RecvLine(insults.TerminalProtocol):
"""L{TerminalProtocol} which adds line editing features.
Clients will be prompted for lines of input with all the usual
features: character echoing, left and right arrow support for
moving the cursor to different areas of the line buffer, backspace
and delete for removing characters, and insert for toggling
between typeover and insert mode. Tabs will be expanded to enough
spaces to move the cursor to the next tabstop (every four
characters by default). Enter causes the line buffer to be
cleared and the line to be passed to the lineReceived() method
which, by default, does nothing. Subclasses are responsible for
redrawing the input prompt (this will probably change).
"""
width = 80
height = 24
TABSTOP = 4
ps = ('>>> ', '... ')
pn = 0
def connectionMade(self):
# A list containing the characters making up the current line
self.lineBuffer = []
# A zero-based (wtf else?) index into self.lineBuffer.
# Indicates the current cursor position.
self.lineBufferIndex = 0
t = self.terminal
# A map of keyIDs to bound instance methods.
self.keyHandlers = {
t.LEFT_ARROW: self.handle_LEFT,
t.RIGHT_ARROW: self.handle_RIGHT,
t.TAB: self.handle_TAB,
# Both of these should not be necessary, but figuring out
# which is necessary is a huge hassle.
'\r': self.handle_RETURN,
'\n': self.handle_RETURN,
t.BACKSPACE: self.handle_BACKSPACE,
t.DELETE: self.handle_DELETE,
t.INSERT: self.handle_INSERT,
t.HOME: self.handle_HOME,
t.END: self.handle_END}
self.initializeScreen()
def initializeScreen(self):
# Hmm, state sucks. Oh well.
# For now we will just take over the whole terminal.
self.terminal.reset()
self.terminal.write(self.ps[self.pn])
# XXX Note: I would prefer to default to starting in insert
# mode, however this does not seem to actually work! I do not
# know why. This is probably of interest to implementors
# subclassing RecvLine.
# XXX XXX Note: But the unit tests all expect the initial mode
# to be insert right now. Fuck, there needs to be a way to
# query the current mode or something.
# self.setTypeoverMode()
self.setInsertMode()
def currentLineBuffer(self):
s = ''.join(self.lineBuffer)
return s[:self.lineBufferIndex], s[self.lineBufferIndex:]
def setInsertMode(self):
self.mode = 'insert'
self.terminal.setModes([insults.modes.IRM])
def setTypeoverMode(self):
self.mode = 'typeover'
self.terminal.resetModes([insults.modes.IRM])
def drawInputLine(self):
"""
Write a line containing the current input prompt and the current line
buffer at the current cursor position.
"""
self.terminal.write(self.ps[self.pn] + ''.join(self.lineBuffer))
def terminalSize(self, width, height):
# XXX - Clear the previous input line, redraw it at the new
# cursor position
self.terminal.eraseDisplay()
self.terminal.cursorHome()
self.width = width
self.height = height
self.drawInputLine()
def unhandledControlSequence(self, seq):
pass
def keystrokeReceived(self, keyID, modifier):
m = self.keyHandlers.get(keyID)
if m is not None:
m()
elif keyID in string.printable:
self.characterReceived(keyID, False)
else:
log.msg("Received unhandled keyID: %r" % (keyID,))
def characterReceived(self, ch, moreCharactersComing):
if self.mode == 'insert':
self.lineBuffer.insert(self.lineBufferIndex, ch)
else:
self.lineBuffer[self.lineBufferIndex:self.lineBufferIndex+1] = [ch]
self.lineBufferIndex += 1
self.terminal.write(ch)
def handle_TAB(self):
n = self.TABSTOP - (len(self.lineBuffer) % self.TABSTOP)
self.terminal.cursorForward(n)
self.lineBufferIndex += n
self.lineBuffer.extend(' ' * n)
def handle_LEFT(self):
if self.lineBufferIndex > 0:
self.lineBufferIndex -= 1
self.terminal.cursorBackward()
def handle_RIGHT(self):
if self.lineBufferIndex < len(self.lineBuffer):
self.lineBufferIndex += 1
self.terminal.cursorForward()
def handle_HOME(self):
if self.lineBufferIndex:
self.terminal.cursorBackward(self.lineBufferIndex)
self.lineBufferIndex = 0
def handle_END(self):
offset = len(self.lineBuffer) - self.lineBufferIndex
if offset:
self.terminal.cursorForward(offset)
self.lineBufferIndex = len(self.lineBuffer)
def handle_BACKSPACE(self):
if self.lineBufferIndex > 0:
self.lineBufferIndex -= 1
del self.lineBuffer[self.lineBufferIndex]
self.terminal.cursorBackward()
self.terminal.deleteCharacter()
def handle_DELETE(self):
if self.lineBufferIndex < len(self.lineBuffer):
del self.lineBuffer[self.lineBufferIndex]
self.terminal.deleteCharacter()
def handle_RETURN(self):
line = ''.join(self.lineBuffer)
self.lineBuffer = []
self.lineBufferIndex = 0
self.terminal.nextLine()
self.lineReceived(line)
def handle_INSERT(self):
assert self.mode in ('typeover', 'insert')
if self.mode == 'typeover':
self.setInsertMode()
else:
self.setTypeoverMode()
def lineReceived(self, line):
pass
class HistoricRecvLine(RecvLine):
"""L{TerminalProtocol} which adds both basic line-editing features and input history.
Everything supported by L{RecvLine} is also supported by this class. In addition, the
up and down arrows traverse the input history. Each received line is automatically
added to the end of the input history.
"""
def connectionMade(self):
RecvLine.connectionMade(self)
self.historyLines = []
self.historyPosition = 0
t = self.terminal
self.keyHandlers.update({t.UP_ARROW: self.handle_UP,
t.DOWN_ARROW: self.handle_DOWN})
def currentHistoryBuffer(self):
b = tuple(self.historyLines)
return b[:self.historyPosition], b[self.historyPosition:]
def _deliverBuffer(self, buf):
if buf:
for ch in buf[:-1]:
self.characterReceived(ch, True)
self.characterReceived(buf[-1], False)
def handle_UP(self):
if self.lineBuffer and self.historyPosition == len(self.historyLines):
self.historyLines.append(self.lineBuffer)
if self.historyPosition > 0:
self.handle_HOME()
self.terminal.eraseToLineEnd()
self.historyPosition -= 1
self.lineBuffer = []
self._deliverBuffer(self.historyLines[self.historyPosition])
def handle_DOWN(self):
if self.historyPosition < len(self.historyLines) - 1:
self.handle_HOME()
self.terminal.eraseToLineEnd()
self.historyPosition += 1
self.lineBuffer = []
self._deliverBuffer(self.historyLines[self.historyPosition])
else:
self.handle_HOME()
self.terminal.eraseToLineEnd()
self.historyPosition = len(self.historyLines)
self.lineBuffer = []
self.lineBufferIndex = 0
def handle_RETURN(self):
if self.lineBuffer:
self.historyLines.append(''.join(self.lineBuffer))
self.historyPosition = len(self.historyLines)
return RecvLine.handle_RETURN(self) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/recvline.py | recvline.py |
#
from twisted.cred import portal
from twisted.python import components, log
from twisted.internet.process import ProcessExitedAlready
from zope import interface
from ssh import session, forwarding, filetransfer
from ssh.filetransfer import FXF_READ, FXF_WRITE, FXF_APPEND, FXF_CREAT, FXF_TRUNC, FXF_EXCL
from twisted.conch.ls import lsLine
from avatar import ConchUser
from error import ConchError
from interfaces import ISession, ISFTPServer, ISFTPFile
import struct, os, time, socket
import fcntl, tty
import pwd, grp
import pty
import ttymodes
try:
import utmp
except ImportError:
utmp = None
class UnixSSHRealm:
interface.implements(portal.IRealm)
def requestAvatar(self, username, mind, *interfaces):
user = UnixConchUser(username)
return interfaces[0], user, user.logout
class UnixConchUser(ConchUser):
def __init__(self, username):
ConchUser.__init__(self)
self.username = username
self.pwdData = pwd.getpwnam(self.username)
l = [self.pwdData[3]]
for groupname, password, gid, userlist in grp.getgrall():
if username in userlist:
l.append(gid)
self.otherGroups = l
self.listeners = {} # dict mapping (interface, port) -> listener
self.channelLookup.update(
{"session": session.SSHSession,
"direct-tcpip": forwarding.openConnectForwardingClient})
self.subsystemLookup.update(
{"sftp": filetransfer.FileTransferServer})
def getUserGroupId(self):
return self.pwdData[2:4]
def getOtherGroups(self):
return self.otherGroups
def getHomeDir(self):
return self.pwdData[5]
def getShell(self):
return self.pwdData[6]
def global_tcpip_forward(self, data):
hostToBind, portToBind = forwarding.unpackGlobal_tcpip_forward(data)
from twisted.internet import reactor
try: listener = self._runAsUser(
reactor.listenTCP, portToBind,
forwarding.SSHListenForwardingFactory(self.conn,
(hostToBind, portToBind),
forwarding.SSHListenServerForwardingChannel),
interface = hostToBind)
except:
return 0
else:
self.listeners[(hostToBind, portToBind)] = listener
if portToBind == 0:
portToBind = listener.getHost()[2] # the port
return 1, struct.pack('>L', portToBind)
else:
return 1
def global_cancel_tcpip_forward(self, data):
hostToBind, portToBind = forwarding.unpackGlobal_tcpip_forward(data)
listener = self.listeners.get((hostToBind, portToBind), None)
if not listener:
return 0
del self.listeners[(hostToBind, portToBind)]
self._runAsUser(listener.stopListening)
return 1
def logout(self):
# remove all listeners
for listener in self.listeners.itervalues():
self._runAsUser(listener.stopListening)
log.msg('avatar %s logging out (%i)' % (self.username, len(self.listeners)))
def _runAsUser(self, f, *args, **kw):
euid = os.geteuid()
egid = os.getegid()
groups = os.getgroups()
uid, gid = self.getUserGroupId()
os.setegid(0)
os.seteuid(0)
os.setgroups(self.getOtherGroups())
os.setegid(gid)
os.seteuid(uid)
try:
f = iter(f)
except TypeError:
f = [(f, args, kw)]
try:
for i in f:
func = i[0]
args = len(i)>1 and i[1] or ()
kw = len(i)>2 and i[2] or {}
r = func(*args, **kw)
finally:
os.setegid(0)
os.seteuid(0)
os.setgroups(groups)
os.setegid(egid)
os.seteuid(euid)
return r
class SSHSessionForUnixConchUser:
interface.implements(ISession)
def __init__(self, avatar):
self.avatar = avatar
self. environ = {'PATH':'/bin:/usr/bin:/usr/local/bin'}
self.pty = None
self.ptyTuple = 0
def addUTMPEntry(self, loggedIn=1):
if not utmp:
return
ipAddress = self.avatar.conn.transport.transport.getPeer().host
packedIp ,= struct.unpack('L', socket.inet_aton(ipAddress))
ttyName = self.ptyTuple[2][5:]
t = time.time()
t1 = int(t)
t2 = int((t-t1) * 1e6)
entry = utmp.UtmpEntry()
entry.ut_type = loggedIn and utmp.USER_PROCESS or utmp.DEAD_PROCESS
entry.ut_pid = self.pty.pid
entry.ut_line = ttyName
entry.ut_id = ttyName[-4:]
entry.ut_tv = (t1,t2)
if loggedIn:
entry.ut_user = self.avatar.username
entry.ut_host = socket.gethostbyaddr(ipAddress)[0]
entry.ut_addr_v6 = (packedIp, 0, 0, 0)
a = utmp.UtmpRecord(utmp.UTMP_FILE)
a.pututline(entry)
a.endutent()
b = utmp.UtmpRecord(utmp.WTMP_FILE)
b.pututline(entry)
b.endutent()
def getPty(self, term, windowSize, modes):
self.environ['TERM'] = term
self.winSize = windowSize
self.modes = modes
master, slave = pty.openpty()
ttyname = os.ttyname(slave)
self.environ['SSH_TTY'] = ttyname
self.ptyTuple = (master, slave, ttyname)
def openShell(self, proto):
from twisted.internet import reactor
if not self.ptyTuple: # we didn't get a pty-req
log.msg('tried to get shell without pty, failing')
raise ConchError("no pty")
uid, gid = self.avatar.getUserGroupId()
homeDir = self.avatar.getHomeDir()
shell = self.avatar.getShell()
self.environ['USER'] = self.avatar.username
self.environ['HOME'] = homeDir
self.environ['SHELL'] = shell
shellExec = os.path.basename(shell)
peer = self.avatar.conn.transport.transport.getPeer()
host = self.avatar.conn.transport.transport.getHost()
self.environ['SSH_CLIENT'] = '%s %s %s' % (peer.host, peer.port, host.port)
self.getPtyOwnership()
self.pty = reactor.spawnProcess(proto, \
shell, ['-%s' % shellExec], self.environ, homeDir, uid, gid,
usePTY = self.ptyTuple)
self.addUTMPEntry()
fcntl.ioctl(self.pty.fileno(), tty.TIOCSWINSZ,
struct.pack('4H', *self.winSize))
if self.modes:
self.setModes()
self.oldWrite = proto.transport.write
proto.transport.write = self._writeHack
self.avatar.conn.transport.transport.setTcpNoDelay(1)
def execCommand(self, proto, cmd):
from twisted.internet import reactor
uid, gid = self.avatar.getUserGroupId()
homeDir = self.avatar.getHomeDir()
shell = self.avatar.getShell() or '/bin/sh'
command = (shell, '-c', cmd)
peer = self.avatar.conn.transport.transport.getPeer()
host = self.avatar.conn.transport.transport.getHost()
self.environ['SSH_CLIENT'] = '%s %s %s' % (peer.host, peer.port, host.port)
if self.ptyTuple:
self.getPtyOwnership()
self.pty = reactor.spawnProcess(proto, \
shell, command, self.environ, homeDir,
uid, gid, usePTY = self.ptyTuple or 0)
if self.ptyTuple:
self.addUTMPEntry()
if self.modes:
self.setModes()
# else:
# tty.setraw(self.pty.pipes[0].fileno(), tty.TCSANOW)
self.avatar.conn.transport.transport.setTcpNoDelay(1)
def getPtyOwnership(self):
ttyGid = os.stat(self.ptyTuple[2])[5]
uid, gid = self.avatar.getUserGroupId()
euid, egid = os.geteuid(), os.getegid()
os.setegid(0)
os.seteuid(0)
try:
os.chown(self.ptyTuple[2], uid, ttyGid)
finally:
os.setegid(egid)
os.seteuid(euid)
def setModes(self):
pty = self.pty
attr = tty.tcgetattr(pty.fileno())
for mode, modeValue in self.modes:
if not ttymodes.TTYMODES.has_key(mode): continue
ttyMode = ttymodes.TTYMODES[mode]
if len(ttyMode) == 2: # flag
flag, ttyAttr = ttyMode
if not hasattr(tty, ttyAttr): continue
ttyval = getattr(tty, ttyAttr)
if modeValue:
attr[flag] = attr[flag]|ttyval
else:
attr[flag] = attr[flag]&~ttyval
elif ttyMode == 'OSPEED':
attr[tty.OSPEED] = getattr(tty, 'B%s'%modeValue)
elif ttyMode == 'ISPEED':
attr[tty.ISPEED] = getattr(tty, 'B%s'%modeValue)
else:
if not hasattr(tty, ttyMode): continue
ttyval = getattr(tty, ttyMode)
attr[tty.CC][ttyval] = chr(modeValue)
tty.tcsetattr(pty.fileno(), tty.TCSANOW, attr)
def eofReceived(self):
if self.pty:
self.pty.closeStdin()
def closed(self):
if self.ptyTuple and os.path.exists(self.ptyTuple[2]):
ttyGID = os.stat(self.ptyTuple[2])[5]
os.chown(self.ptyTuple[2], 0, ttyGID)
if self.pty:
try:
self.pty.signalProcess('HUP')
except (OSError,ProcessExitedAlready):
pass
self.pty.loseConnection()
self.addUTMPEntry(0)
log.msg('shell closed')
def windowChanged(self, winSize):
self.winSize = winSize
fcntl.ioctl(self.pty.fileno(), tty.TIOCSWINSZ,
struct.pack('4H', *self.winSize))
def _writeHack(self, data):
"""
Hack to send ignore messages when we aren't echoing.
"""
if self.pty is not None:
attr = tty.tcgetattr(self.pty.fileno())[3]
if not attr & tty.ECHO and attr & tty.ICANON: # no echo
self.avatar.conn.transport.sendIgnore('\x00'*(8+len(data)))
self.oldWrite(data)
class SFTPServerForUnixConchUser:
interface.implements(ISFTPServer)
def __init__(self, avatar):
self.avatar = avatar
def _setAttrs(self, path, attrs):
"""
NOTE: this function assumes it runs as the logged-in user:
i.e. under _runAsUser()
"""
if attrs.has_key("uid") and attrs.has_key("gid"):
os.chown(path, attrs["uid"], attrs["gid"])
if attrs.has_key("permissions"):
os.chmod(path, attrs["permissions"])
if attrs.has_key("atime") and attrs.has_key("mtime"):
os.utime(path, (attrs["atime"], attrs["mtime"]))
def _getAttrs(self, s):
return {
"size" : s.st_size,
"uid" : s.st_uid,
"gid" : s.st_gid,
"permissions" : s.st_mode,
"atime" : int(s.st_atime),
"mtime" : int(s.st_mtime)
}
def _absPath(self, path):
home = self.avatar.getHomeDir()
return os.path.abspath(os.path.join(home, path))
def gotVersion(self, otherVersion, extData):
return {}
def openFile(self, filename, flags, attrs):
return UnixSFTPFile(self, self._absPath(filename), flags, attrs)
def removeFile(self, filename):
filename = self._absPath(filename)
return self.avatar._runAsUser(os.remove, filename)
def renameFile(self, oldpath, newpath):
oldpath = self._absPath(oldpath)
newpath = self._absPath(newpath)
return self.avatar._runAsUser(os.rename, oldpath, newpath)
def makeDirectory(self, path, attrs):
path = self._absPath(path)
return self.avatar._runAsUser([(os.mkdir, (path,)),
(self._setAttrs, (path, attrs))])
def removeDirectory(self, path):
path = self._absPath(path)
self.avatar._runAsUser(os.rmdir, path)
def openDirectory(self, path):
return UnixSFTPDirectory(self, self._absPath(path))
def getAttrs(self, path, followLinks):
path = self._absPath(path)
if followLinks:
s = self.avatar._runAsUser(os.stat, path)
else:
s = self.avatar._runAsUser(os.lstat, path)
return self._getAttrs(s)
def setAttrs(self, path, attrs):
path = self._absPath(path)
self.avatar._runAsUser(self._setAttrs, path, attrs)
def readLink(self, path):
path = self._absPath(path)
return self.avatar._runAsUser(os.readlink, path)
def makeLink(self, linkPath, targetPath):
linkPath = self._absPath(linkPath)
targetPath = self._absPath(targetPath)
return self.avatar._runAsUser(os.symlink, targetPath, linkPath)
def realPath(self, path):
return os.path.realpath(self._absPath(path))
def extendedRequest(self, extName, extData):
raise NotImplementedError
class UnixSFTPFile:
interface.implements(ISFTPFile)
def __init__(self, server, filename, flags, attrs):
self.server = server
openFlags = 0
if flags & FXF_READ == FXF_READ and flags & FXF_WRITE == 0:
openFlags = os.O_RDONLY
if flags & FXF_WRITE == FXF_WRITE and flags & FXF_READ == 0:
openFlags = os.O_WRONLY
if flags & FXF_WRITE == FXF_WRITE and flags & FXF_READ == FXF_READ:
openFlags = os.O_RDWR
if flags & FXF_APPEND == FXF_APPEND:
openFlags |= os.O_APPEND
if flags & FXF_CREAT == FXF_CREAT:
openFlags |= os.O_CREAT
if flags & FXF_TRUNC == FXF_TRUNC:
openFlags |= os.O_TRUNC
if flags & FXF_EXCL == FXF_EXCL:
openFlags |= os.O_EXCL
if attrs.has_key("permissions"):
mode = attrs["permissions"]
del attrs["permissions"]
else:
mode = 0777
fd = server.avatar._runAsUser(os.open, filename, openFlags, mode)
if attrs:
server.avatar._runAsUser(server._setAttrs, filename, attrs)
self.fd = fd
def close(self):
return self.server.avatar._runAsUser(os.close, self.fd)
def readChunk(self, offset, length):
return self.server.avatar._runAsUser([ (os.lseek, (self.fd, offset, 0)),
(os.read, (self.fd, length)) ])
def writeChunk(self, offset, data):
return self.server.avatar._runAsUser([(os.lseek, (self.fd, offset, 0)),
(os.write, (self.fd, data))])
def getAttrs(self):
s = self.server.avatar._runAsUser(os.fstat, self.fd)
return self.server._getAttrs(s)
def setAttrs(self, attrs):
raise NotImplementedError
class UnixSFTPDirectory:
def __init__(self, server, directory):
self.server = server
self.files = server.avatar._runAsUser(os.listdir, directory)
self.dir = directory
def __iter__(self):
return self
def next(self):
try:
f = self.files.pop(0)
except IndexError:
raise StopIteration
else:
s = self.server.avatar._runAsUser(os.lstat, os.path.join(self.dir, f))
longname = lsLine(f, s)
attrs = self.server._getAttrs(s)
return (f, longname, attrs)
def close(self):
self.files = []
components.registerAdapter(SFTPServerForUnixConchUser, UnixConchUser, filetransfer.ISFTPServer)
components.registerAdapter(SSHSessionForUnixConchUser, UnixConchUser, session.ISession) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/unix.py | unix.py |
import os, base64, binascii
try:
import pwd
except ImportError:
pwd = None
else:
import crypt
try:
# get this from http://www.twistedmatrix.com/users/z3p/files/pyshadow-0.2.tar.gz
import shadow
except:
shadow = None
try:
import pamauth
except ImportError:
pamauth = None
from twisted.conch import error
from twisted.conch.ssh import keys
from twisted.cred.checkers import ICredentialsChecker
from twisted.cred.credentials import IUsernamePassword, ISSHPrivateKey, IPluggableAuthenticationModules
from twisted.cred.error import UnauthorizedLogin, UnhandledCredentials
from twisted.internet import defer
from twisted.python import failure, reflect, log
from zope import interface
def verifyCryptedPassword(crypted, pw):
if crypted[0] == '$': # md5_crypt encrypted
salt = '$1$' + crypted.split('$')[2]
else:
salt = crypted[:2]
return crypt.crypt(pw, salt) == crypted
class UNIXPasswordDatabase:
credentialInterfaces = IUsernamePassword,
interface.implements(ICredentialsChecker)
def requestAvatarId(self, credentials):
if pwd:
try:
cryptedPass = pwd.getpwnam(credentials.username)[1]
except KeyError:
return defer.fail(UnauthorizedLogin())
else:
if cryptedPass not in ['*', 'x'] and \
verifyCryptedPassword(cryptedPass, credentials.password):
return defer.succeed(credentials.username)
if shadow:
gid = os.getegid()
uid = os.geteuid()
os.setegid(0)
os.seteuid(0)
try:
shadowPass = shadow.getspnam(credentials.username)[1]
except KeyError:
os.setegid(gid)
os.seteuid(uid)
return defer.fail(UnauthorizedLogin())
os.setegid(gid)
os.seteuid(uid)
if verifyCryptedPassword(shadowPass, credentials.password):
return defer.succeed(credentials.username)
return defer.fail(UnauthorizedLogin())
return defer.fail(UnauthorizedLogin())
class SSHPublicKeyDatabase:
credentialInterfaces = ISSHPrivateKey,
interface.implements(ICredentialsChecker)
def requestAvatarId(self, credentials):
d = defer.maybeDeferred(self.checkKey, credentials)
d.addCallback(self._cbRequestAvatarId, credentials)
d.addErrback(self._ebRequestAvatarId)
return d
def _cbRequestAvatarId(self, validKey, credentials):
if not validKey:
return failure.Failure(UnauthorizedLogin())
if not credentials.signature:
return failure.Failure(error.ValidPublicKey())
else:
try:
pubKey = keys.getPublicKeyObject(data = credentials.blob)
if keys.verifySignature(pubKey, credentials.signature,
credentials.sigData):
return credentials.username
except: # any error should be treated as a failed login
f = failure.Failure()
log.err()
return f
return failure.Failure(UnauthorizedLogin())
def checkKey(self, credentials):
sshDir = os.path.expanduser('~%s/.ssh/' % credentials.username)
if sshDir.startswith('~'): # didn't expand
return 0
uid, gid = os.geteuid(), os.getegid()
ouid, ogid = pwd.getpwnam(credentials.username)[2:4]
os.setegid(0)
os.seteuid(0)
os.setegid(ogid)
os.seteuid(ouid)
for name in ['authorized_keys2', 'authorized_keys']:
if not os.path.exists(sshDir+name):
continue
lines = open(sshDir+name).xreadlines()
os.setegid(0)
os.seteuid(0)
os.setegid(gid)
os.seteuid(uid)
for l in lines:
l2 = l.split()
if len(l2) < 2:
continue
try:
if base64.decodestring(l2[1]) == credentials.blob:
return 1
except binascii.Error:
continue
return 0
def _ebRequestAvatarId(self, f):
if not f.check(UnauthorizedLogin, error.ValidPublicKey):
log.msg(f)
return failure.Failure(UnauthorizedLogin())
return f
class SSHProtocolChecker:
interface.implements(ICredentialsChecker)
checkers = {}
successfulCredentials = {}
def get_credentialInterfaces(self):
return self.checkers.keys()
credentialInterfaces = property(get_credentialInterfaces)
def registerChecker(self, checker, *credentialInterfaces):
if not credentialInterfaces:
credentialInterfaces = checker.credentialInterfaces
for credentialInterface in credentialInterfaces:
self.checkers[credentialInterface] = checker
def requestAvatarId(self, credentials):
ifac = interface.providedBy(credentials)
for i in ifac:
c = self.checkers.get(i)
if c is not None:
return c.requestAvatarId(credentials).addCallback(
self._cbGoodAuthentication, credentials)
return defer.fail(UnhandledCredentials("No checker for %s" % \
', '.join(map(reflect.qal, ifac))))
def _cbGoodAuthentication(self, avatarId, credentials):
if avatarId not in self.successfulCredentials:
self.successfulCredentials[avatarId] = []
self.successfulCredentials[avatarId].append(credentials)
if self.areDone(avatarId):
del self.successfulCredentials[avatarId]
return avatarId
else:
raise error.NotEnoughAuthentication()
def areDone(self, avatarId):
"""Override to determine if the authentication is finished for a given
avatarId.
"""
return 1 | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/checkers.py | checkers.py |
from zope.interface import implements
from twisted.conch import avatar, interfaces as iconch, error as econch
from twisted.conch.ssh import factory, keys, session
from twisted.cred import credentials, checkers, portal
from twisted.python import components
from twisted.conch.insults import insults
class _Glue:
"""A feeble class for making one attribute look like another.
This should be replaced with a real class at some point, probably.
Try not to write new code that uses it.
"""
def __init__(self, **kw):
self.__dict__.update(kw)
def __getattr__(self, name):
raise AttributeError(self.name, "has no attribute", name)
class TerminalSessionTransport:
def __init__(self, proto, chainedProtocol, avatar, width, height):
self.proto = proto
self.avatar = avatar
self.chainedProtocol = chainedProtocol
session = self.proto.session
self.proto.makeConnection(
_Glue(write=self.chainedProtocol.dataReceived,
loseConnection=lambda: avatar.conn.sendClose(session),
name="SSH Proto Transport"))
def loseConnection():
self.proto.loseConnection()
self.chainedProtocol.makeConnection(
_Glue(write=self.proto.write,
loseConnection=loseConnection,
name="Chained Proto Transport"))
# XXX TODO
# chainedProtocol is supposed to be an ITerminalTransport,
# maybe. That means perhaps its terminalProtocol attribute is
# an ITerminalProtocol, it could be. So calling terminalSize
# on that should do the right thing But it'd be nice to clean
# this bit up.
self.chainedProtocol.terminalProtocol.terminalSize(width, height)
class TerminalSession(components.Adapter):
implements(iconch.ISession)
transportFactory = TerminalSessionTransport
chainedProtocolFactory = insults.ServerProtocol
def getPty(self, term, windowSize, attrs):
self.height, self.width = windowSize[:2]
def openShell(self, proto):
self.transportFactory(
proto, self.chainedProtocolFactory(),
iconch.IConchUser(self.original),
self.width, self.height)
def execCommand(self, proto, cmd):
raise econch.ConchError("Cannot execute commands")
def closed(self):
pass
class TerminalUser(avatar.ConchUser, components.Adapter):
def __init__(self, original, avatarId):
components.Adapter.__init__(self, original)
avatar.ConchUser.__init__(self)
self.channelLookup['session'] = session.SSHSession
class TerminalRealm:
userFactory = TerminalUser
sessionFactory = TerminalSession
transportFactory = TerminalSessionTransport
chainedProtocolFactory = insults.ServerProtocol
def _getAvatar(self, avatarId):
comp = components.Componentized()
user = self.userFactory(comp, avatarId)
sess = self.sessionFactory(comp)
sess.transportFactory = self.transportFactory
sess.chainedProtocolFactory = self.chainedProtocolFactory
comp.setComponent(iconch.IConchUser, user)
comp.setComponent(iconch.ISession, sess)
return user
def __init__(self, transportFactory=None):
if transportFactory is not None:
self.transportFactory = transportFactory
def requestAvatar(self, avatarId, mind, *interfaces):
for i in interfaces:
if i is iconch.IConchUser:
return (iconch.IConchUser,
self._getAvatar(avatarId),
lambda: None)
raise NotImplementedError()
class ConchFactory(factory.SSHFactory):
publicKey = 'ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAGEArzJx8OYOnJmzf4tfBEvLi8DVPrJ3/c9k2I/Az64fxjHf9imyRJbixtQhlH9lfNjUIx+4LmrJH5QNRsFporcHDKOTwTTYLh5KmRpslkYHRivcJSkbh/C+BR3utDS555mV'
publicKeys = {
'ssh-rsa' : keys.getPublicKeyString(data = publicKey)
}
del publicKey
privateKey = """-----BEGIN RSA PRIVATE KEY-----
MIIByAIBAAJhAK8ycfDmDpyZs3+LXwRLy4vA1T6yd/3PZNiPwM+uH8Yx3/YpskSW
4sbUIZR/ZXzY1CMfuC5qyR+UDUbBaaK3Bwyjk8E02C4eSpkabJZGB0Yr3CUpG4fw
vgUd7rQ0ueeZlQIBIwJgbh+1VZfr7WftK5lu7MHtqE1S1vPWZQYE3+VUn8yJADyb
Z4fsZaCrzW9lkIqXkE3GIY+ojdhZhkO1gbG0118sIgphwSWKRxK0mvh6ERxKqIt1
xJEJO74EykXZV4oNJ8sjAjEA3J9r2ZghVhGN6V8DnQrTk24Td0E8hU8AcP0FVP+8
PQm/g/aXf2QQkQT+omdHVEJrAjEAy0pL0EBH6EVS98evDCBtQw22OZT52qXlAwZ2
gyTriKFVoqjeEjt3SZKKqXHSApP/AjBLpF99zcJJZRq2abgYlf9lv1chkrWqDHUu
DZttmYJeEfiFBBavVYIF1dOlZT0G8jMCMBc7sOSZodFnAiryP+Qg9otSBjJ3bQML
pSTqy7c3a2AScC/YyOwkDaICHnnD3XyjMwIxALRzl0tQEKMXs6hH8ToUdlLROCrP
EhQ0wahUTCk1gKA4uPD6TMTChavbh4K63OvbKg==
-----END RSA PRIVATE KEY-----"""
privateKeys = {
'ssh-rsa' : keys.getPrivateKeyObject(data = privateKey)
}
del privateKey
def __init__(self, portal):
self.portal = portal | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/manhole_ssh.py | manhole_ssh.py |
#
"""Module to parse ANSI escape sequences
Maintainer: U{Jean-Paul Calderone <[email protected]>}
"""
import string
# Twisted imports
from twisted.python import log
class ColorText:
"""
Represents an element of text along with the texts colors and
additional attributes.
"""
# The colors to use
COLORS = ('b', 'r', 'g', 'y', 'l', 'm', 'c', 'w')
BOLD_COLORS = tuple([x.upper() for x in COLORS])
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(len(COLORS))
# Color names
COLOR_NAMES = (
'Black', 'Red', 'Green', 'Yellow', 'Blue', 'Magenta', 'Cyan', 'White'
)
def __init__(self, text, fg, bg, display, bold, underline, flash, reverse):
self.text, self.fg, self.bg = text, fg, bg
self.display = display
self.bold = bold
self.underline = underline
self.flash = flash
self.reverse = reverse
if self.reverse:
self.fg, self.bg = self.bg, self.fg
class AnsiParser:
"""
Parser class for ANSI codes.
"""
# Terminators for cursor movement ansi controls - unsupported
CURSOR_SET = ('H', 'f', 'A', 'B', 'C', 'D', 'R', 's', 'u', 'd','G')
# Terminators for erasure ansi controls - unsupported
ERASE_SET = ('J', 'K', 'P')
# Terminators for mode change ansi controls - unsupported
MODE_SET = ('h', 'l')
# Terminators for keyboard assignment ansi controls - unsupported
ASSIGN_SET = ('p',)
# Terminators for color change ansi controls - supported
COLOR_SET = ('m',)
SETS = (CURSOR_SET, ERASE_SET, MODE_SET, ASSIGN_SET, COLOR_SET)
def __init__(self, defaultFG, defaultBG):
self.defaultFG, self.defaultBG = defaultFG, defaultBG
self.currentFG, self.currentBG = self.defaultFG, self.defaultBG
self.bold, self.flash, self.underline, self.reverse = 0, 0, 0, 0
self.display = 1
self.prepend = ''
def stripEscapes(self, string):
"""
Remove all ANSI color escapes from the given string.
"""
result = ''
show = 1
i = 0
L = len(string)
while i < L:
if show == 0 and string[i] in _sets:
show = 1
elif show:
n = string.find('\x1B', i)
if n == -1:
return result + string[i:]
else:
result = result + string[i:n]
i = n
show = 0
i = i + 1
return result
def writeString(self, colorstr):
pass
def parseString(self, str):
"""
Turn a string input into a list of L{ColorText} elements.
"""
if self.prepend:
str = self.prepend + str
self.prepend = ''
parts = str.split('\x1B')
if len(parts) == 1:
self.writeString(self.formatText(parts[0]))
else:
self.writeString(self.formatText(parts[0]))
for s in parts[1:]:
L = len(s)
i = 0
type = None
while i < L:
if s[i] not in string.digits+'[;?':
break
i+=1
if not s:
self.prepend = '\x1b'
return
if s[0]!='[':
self.writeString(self.formatText(s[i+1:]))
continue
else:
s=s[1:]
i-=1
if i==L-1:
self.prepend = '\x1b['
return
type = _setmap.get(s[i], None)
if type is None:
continue
if type == AnsiParser.COLOR_SET:
self.parseColor(s[:i + 1])
s = s[i + 1:]
self.writeString(self.formatText(s))
elif type == AnsiParser.CURSOR_SET:
cursor, s = s[:i+1], s[i+1:]
self.parseCursor(cursor)
self.writeString(self.formatText(s))
elif type == AnsiParser.ERASE_SET:
erase, s = s[:i+1], s[i+1:]
self.parseErase(erase)
self.writeString(self.formatText(s))
elif type == AnsiParser.MODE_SET:
mode, s = s[:i+1], s[i+1:]
#self.parseErase('2J')
self.writeString(self.formatText(s))
elif i == L:
self.prepend = '\x1B[' + s
else:
log.msg('Unhandled ANSI control type: %c' % (s[i],))
s = s[i + 1:]
self.writeString(self.formatText(s))
def parseColor(self, str):
"""
Handle a single ANSI color sequence
"""
# Drop the trailing 'm'
str = str[:-1]
if not str:
str = '0'
try:
parts = map(int, str.split(';'))
except ValueError:
log.msg('Invalid ANSI color sequence (%d): %s' % (len(str), str))
self.currentFG, self.currentBG = self.defaultFG, self.defaultBG
return
for x in parts:
if x == 0:
self.currentFG, self.currentBG = self.defaultFG, self.defaultBG
self.bold, self.flash, self.underline, self.reverse = 0, 0, 0, 0
self.display = 1
elif x == 1:
self.bold = 1
elif 30 <= x <= 37:
self.currentFG = x - 30
elif 40 <= x <= 47:
self.currentBG = x - 40
elif x == 39:
self.currentFG = self.defaultFG
elif x == 49:
self.currentBG = self.defaultBG
elif x == 4:
self.underline = 1
elif x == 5:
self.flash = 1
elif x == 7:
self.reverse = 1
elif x == 8:
self.display = 0
elif x == 22:
self.bold = 0
elif x == 24:
self.underline = 0
elif x == 25:
self.blink = 0
elif x == 27:
self.reverse = 0
elif x == 28:
self.display = 1
else:
log.msg('Unrecognised ANSI color command: %d' % (x,))
def parseCursor(self, cursor):
pass
def parseErase(self, erase):
pass
def pickColor(self, value, mode, BOLD = ColorText.BOLD_COLORS):
if mode:
return ColorText.COLORS[value]
else:
return self.bold and BOLD[value] or ColorText.COLORS[value]
def formatText(self, text):
return ColorText(
text,
self.pickColor(self.currentFG, 0),
self.pickColor(self.currentBG, 1),
self.display, self.bold, self.underline, self.flash, self.reverse
)
_sets = ''.join(map(''.join, AnsiParser.SETS))
_setmap = {}
for s in AnsiParser.SETS:
for r in s:
_setmap[r] = s
del s | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/ui/ansi.py | ansi.py |
#
"""Module to emulate a VT100 terminal in Tkinter.
Maintainer: U{Paul Swartz <mailto:[email protected]>}
"""
import Tkinter, tkFont
import ansi
import string
ttyFont = None#tkFont.Font(family = 'Courier', size = 10)
fontWidth, fontHeight = None,None#max(map(ttyFont.measure, string.letters+string.digits)), int(ttyFont.metrics()['linespace'])
colorKeys = (
'b', 'r', 'g', 'y', 'l', 'm', 'c', 'w',
'B', 'R', 'G', 'Y', 'L', 'M', 'C', 'W'
)
colorMap = {
'b': '#000000', 'r': '#c40000', 'g': '#00c400', 'y': '#c4c400',
'l': '#000080', 'm': '#c400c4', 'c': '#00c4c4', 'w': '#c4c4c4',
'B': '#626262', 'R': '#ff0000', 'G': '#00ff00', 'Y': '#ffff00',
'L': '#0000ff', 'M': '#ff00ff', 'C': '#00ffff', 'W': '#ffffff',
}
class VT100Frame(Tkinter.Frame):
def __init__(self, *args, **kw):
global ttyFont, fontHeight, fontWidth
ttyFont = tkFont.Font(family = 'Courier', size = 10)
fontWidth, fontHeight = max(map(ttyFont.measure, string.letters+string.digits)), int(ttyFont.metrics()['linespace'])
self.width = kw.get('width', 80)
self.height = kw.get('height', 25)
self.callback = kw['callback']
del kw['callback']
kw['width'] = w = fontWidth * self.width
kw['height'] = h = fontHeight * self.height
Tkinter.Frame.__init__(self, *args, **kw)
self.canvas = Tkinter.Canvas(bg='#000000', width=w, height=h)
self.canvas.pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=1)
self.canvas.bind('<Key>', self.keyPressed)
self.canvas.bind('<1>', lambda x: 'break')
self.canvas.bind('<Up>', self.upPressed)
self.canvas.bind('<Down>', self.downPressed)
self.canvas.bind('<Left>', self.leftPressed)
self.canvas.bind('<Right>', self.rightPressed)
self.canvas.focus()
self.ansiParser = ansi.AnsiParser(ansi.ColorText.WHITE, ansi.ColorText.BLACK)
self.ansiParser.writeString = self.writeString
self.ansiParser.parseCursor = self.parseCursor
self.ansiParser.parseErase = self.parseErase
#for (a, b) in colorMap.items():
# self.canvas.tag_config(a, foreground=b)
# self.canvas.tag_config('b'+a, background=b)
#self.canvas.tag_config('underline', underline=1)
self.x = 0
self.y = 0
self.cursor = self.canvas.create_rectangle(0,0,fontWidth-1,fontHeight-1,fill='green',outline='green')
def _delete(self, sx, sy, ex, ey):
csx = sx*fontWidth + 1
csy = sy*fontHeight + 1
cex = ex*fontWidth + 3
cey = ey*fontHeight + 3
items = self.canvas.find_overlapping(csx,csy, cex,cey)
for item in items:
self.canvas.delete(item)
def _write(self, ch, fg, bg):
if self.x == self.width:
self.x = 0
self.y+=1
if self.y == self.height:
[self.canvas.move(x,0,-fontHeight) for x in self.canvas.find_all()]
self.y-=1
canvasX = self.x*fontWidth + 1
canvasY = self.y*fontHeight + 1
items = self.canvas.find_overlapping(canvasX, canvasY, canvasX+2, canvasY+2)
if items:
[self.canvas.delete(item) for item in items]
if bg:
self.canvas.create_rectangle(canvasX, canvasY, canvasX+fontWidth-1, canvasY+fontHeight-1, fill=bg, outline=bg)
self.canvas.create_text(canvasX, canvasY, anchor=Tkinter.NW, font=ttyFont, text=ch, fill=fg)
self.x+=1
def write(self, data):
#print self.x,self.y,repr(data)
#if len(data)>5: raw_input()
self.ansiParser.parseString(data)
self.canvas.delete(self.cursor)
canvasX = self.x*fontWidth + 1
canvasY = self.y*fontHeight + 1
self.cursor = self.canvas.create_rectangle(canvasX,canvasY,canvasX+fontWidth-1,canvasY+fontHeight-1, fill='green', outline='green')
self.canvas.lower(self.cursor)
def writeString(self, i):
if not i.display:
return
fg = colorMap[i.fg]
bg = i.bg != 'b' and colorMap[i.bg]
for ch in i.text:
b = ord(ch)
if b == 7: # bell
self.bell()
elif b == 8: # BS
if self.x:
self.x-=1
elif b == 9: # TAB
[self._write(' ',fg,bg) for i in range(8)]
elif b == 10:
if self.y == self.height-1:
self._delete(0,0,self.width,0)
[self.canvas.move(x,0,-fontHeight) for x in self.canvas.find_all()]
else:
self.y+=1
elif b == 13:
self.x = 0
elif 32 <= b < 127:
self._write(ch, fg, bg)
def parseErase(self, erase):
if ';' in erase:
end = erase[-1]
parts = erase[:-1].split(';')
[self.parseErase(x+end) for x in parts]
return
start = 0
x,y = self.x, self.y
if len(erase) > 1:
start = int(erase[:-1])
if erase[-1] == 'J':
if start == 0:
self._delete(x,y,self.width,self.height)
else:
self._delete(0,0,self.width,self.height)
self.x = 0
self.y = 0
elif erase[-1] == 'K':
if start == 0:
self._delete(x,y,self.width,y)
elif start == 1:
self._delete(0,y,x,y)
self.x = 0
else:
self._delete(0,y,self.width,y)
self.x = 0
elif erase[-1] == 'P':
self._delete(x,y,x+start,y)
def parseCursor(self, cursor):
#if ';' in cursor and cursor[-1]!='H':
# end = cursor[-1]
# parts = cursor[:-1].split(';')
# [self.parseCursor(x+end) for x in parts]
# return
start = 1
if len(cursor) > 1 and cursor[-1]!='H':
start = int(cursor[:-1])
if cursor[-1] == 'C':
self.x+=start
elif cursor[-1] == 'D':
self.x-=start
elif cursor[-1]=='d':
self.y=start-1
elif cursor[-1]=='G':
self.x=start-1
elif cursor[-1]=='H':
if len(cursor)>1:
y,x = map(int, cursor[:-1].split(';'))
y-=1
x-=1
else:
x,y=0,0
self.x = x
self.y = y
def keyPressed(self, event):
if self.callback and event.char:
self.callback(event.char)
return 'break'
def upPressed(self, event):
self.callback('\x1bOA')
def downPressed(self, event):
self.callback('\x1bOB')
def rightPressed(self, event):
self.callback('\x1bOC')
def leftPressed(self, event):
self.callback('\x1bOD') | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/ui/tkvt100.py | tkvt100.py |
import re, string
from zope.interface import implements
from twisted.internet import defer, protocol, reactor
from twisted.python import log
from twisted.conch.insults import insults
FOREGROUND = 30
BACKGROUND = 40
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, N_COLORS = range(9)
class CharacterAttribute:
"""Represents the attributes of a single character.
Character set, intensity, underlinedness, blinkitude, video
reversal, as well as foreground and background colors made up a
character's attributes.
"""
def __init__(self, charset=insults.G0,
bold=False, underline=False,
blink=False, reverseVideo=False,
foreground=WHITE, background=BLACK,
_subtracting=False):
self.charset = charset
self.bold = bold
self.underline = underline
self.blink = blink
self.reverseVideo = reverseVideo
self.foreground = foreground
self.background = background
self._subtracting = _subtracting
def __eq__(self, other):
return vars(self) == vars(other)
def __ne__(self, other):
return not self.__eq__(other)
def copy(self):
c = self.__class__()
c.__dict__.update(vars(self))
return c
def wantOne(self, **kw):
k, v = kw.popitem()
if getattr(self, k) != v:
attr = self.copy()
attr._subtracting = not v
setattr(attr, k, v)
return attr
else:
return self.copy()
def toVT102(self):
# Spit out a vt102 control sequence that will set up
# all the attributes set here. Except charset.
attrs = []
if self._subtracting:
attrs.append(0)
if self.bold:
attrs.append(insults.BOLD)
if self.underline:
attrs.append(insults.UNDERLINE)
if self.blink:
attrs.append(insults.BLINK)
if self.reverseVideo:
attrs.append(insults.REVERSE_VIDEO)
if self.foreground != WHITE:
attrs.append(FOREGROUND + self.foreground)
if self.background != BLACK:
attrs.append(BACKGROUND + self.background)
if attrs:
return '\x1b[' + ';'.join(map(str, attrs)) + 'm'
return ''
# XXX - need to support scroll regions and scroll history
class TerminalBuffer(protocol.Protocol):
implements(insults.ITerminalTransport)
for keyID in ('UP_ARROW', 'DOWN_ARROW', 'RIGHT_ARROW', 'LEFT_ARROW',
'HOME', 'INSERT', 'DELETE', 'END', 'PGUP', 'PGDN',
'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9',
'F10', 'F11', 'F12'):
exec '%s = object()' % (keyID,)
TAB = '\t'
BACKSPACE = '\x7f'
width = 80
height = 24
fill = ' '
void = object()
def getCharacter(self, x, y):
return self.lines[y][x]
def connectionMade(self):
self.reset()
def write(self, bytes):
for b in bytes:
self.insertAtCursor(b)
def _currentCharacterAttributes(self):
return CharacterAttribute(self.activeCharset, **self.graphicRendition)
def insertAtCursor(self, b):
if b == '\r':
self.x = 0
elif b == '\n' or self.x >= self.width:
self.x = 0
self._scrollDown()
if b in string.printable and b not in '\r\n':
ch = (b, self._currentCharacterAttributes())
if self.modes.get(insults.modes.IRM):
self.lines[self.y][self.x:self.x] = [ch]
self.lines[self.y].pop()
else:
self.lines[self.y][self.x] = ch
self.x += 1
def _emptyLine(self, width):
return [(self.void, self._currentCharacterAttributes()) for i in xrange(width)]
def _scrollDown(self):
self.y += 1
if self.y >= self.height:
self.y -= 1
del self.lines[0]
self.lines.append(self._emptyLine(self.width))
def _scrollUp(self):
self.y -= 1
if self.y < 0:
self.y = 0
del self.lines[-1]
self.lines.insert(0, self._emptyLine(self.width))
def cursorUp(self, n=1):
self.y = max(0, self.y - n)
def cursorDown(self, n=1):
self.y = min(self.height - 1, self.y + n)
def cursorBackward(self, n=1):
self.x = max(0, self.x - n)
def cursorForward(self, n=1):
self.x = min(self.width, self.x + n)
def cursorPosition(self, column, line):
self.x = column
self.y = line
def cursorHome(self):
self.x = self.home.x
self.y = self.home.y
def index(self):
self._scrollDown()
def reverseIndex(self):
self._scrollUp()
def nextLine(self):
self.insertAtCursor('\n')
def saveCursor(self):
self._savedCursor = (self.x, self.y)
def restoreCursor(self):
self.x, self.y = self._savedCursor
del self._savedCursor
def setModes(self, modes):
for m in modes:
self.modes[m] = True
def resetModes(self, modes):
for m in modes:
try:
del self.modes[m]
except KeyError:
pass
def applicationKeypadMode(self):
self.keypadMode = 'app'
def numericKeypadMode(self):
self.keypadMode = 'num'
def selectCharacterSet(self, charSet, which):
self.charsets[which] = charSet
def shiftIn(self):
self.activeCharset = insults.G0
def shiftOut(self):
self.activeCharset = insults.G1
def singleShift2(self):
oldActiveCharset = self.activeCharset
self.activeCharset = insults.G2
f = self.insertAtCursor
def insertAtCursor(b):
f(b)
del self.insertAtCursor
self.activeCharset = oldActiveCharset
self.insertAtCursor = insertAtCursor
def singleShift3(self):
oldActiveCharset = self.activeCharset
self.activeCharset = insults.G3
f = self.insertAtCursor
def insertAtCursor(b):
f(b)
del self.insertAtCursor
self.activeCharset = oldActiveCharset
self.insertAtCursor = insertAtCursor
def selectGraphicRendition(self, *attributes):
for a in attributes:
if a == insults.NORMAL:
self.graphicRendition = {
'bold': False,
'underline': False,
'blink': False,
'reverseVideo': False,
'foreground': WHITE,
'background': BLACK}
elif a == insults.BOLD:
self.graphicRendition['bold'] = True
elif a == insults.UNDERLINE:
self.graphicRendition['underline'] = True
elif a == insults.BLINK:
self.graphicRendition['blink'] = True
elif a == insults.REVERSE_VIDEO:
self.graphicRendition['reverseVideo'] = True
else:
try:
v = int(a)
except ValueError:
log.msg("Unknown graphic rendition attribute: " + repr(a))
else:
if FOREGROUND <= v <= FOREGROUND + N_COLORS:
self.graphicRendition['foreground'] = v - FOREGROUND
elif BACKGROUND <= v <= BACKGROUND + N_COLORS:
self.graphicRendition['background'] = v - BACKGROUND
else:
log.msg("Unknown graphic rendition attribute: " + repr(a))
def eraseLine(self):
self.lines[self.y] = self._emptyLine(self.width)
def eraseToLineEnd(self):
width = self.width - self.x
self.lines[self.y][self.x:] = self._emptyLine(width)
def eraseToLineBeginning(self):
self.lines[self.y][:self.x + 1] = self._emptyLine(self.x + 1)
def eraseDisplay(self):
self.lines = [self._emptyLine(self.width) for i in xrange(self.height)]
def eraseToDisplayEnd(self):
self.eraseToLineEnd()
height = self.height - self.y - 1
self.lines[self.y + 1:] = [self._emptyLine(self.width) for i in range(height)]
def eraseToDisplayBeginning(self):
self.eraseToLineBeginning()
self.lines[:self.y] = [self._emptyLine(self.width) for i in range(self.y)]
def deleteCharacter(self, n=1):
del self.lines[self.y][self.x:self.x+n]
self.lines[self.y].extend(self._emptyLine(min(self.width - self.x, n)))
def insertLine(self, n=1):
self.lines[self.y:self.y] = [self._emptyLine(self.width) for i in range(n)]
del self.lines[self.height:]
def deleteLine(self, n=1):
del self.lines[self.y:self.y+n]
self.lines.extend([self._emptyLine(self.width) for i in range(n)])
def reportCursorPosition(self):
return (self.x, self.y)
def reset(self):
self.home = insults.Vector(0, 0)
self.x = self.y = 0
self.modes = {}
self.numericKeypad = 'app'
self.activeCharset = insults.G0
self.graphicRendition = {
'bold': False,
'underline': False,
'blink': False,
'reverseVideo': False,
'foreground': WHITE,
'background': BLACK}
self.charsets = {
insults.G0: insults.CS_US,
insults.G1: insults.CS_US,
insults.G2: insults.CS_ALTERNATE,
insults.G3: insults.CS_ALTERNATE_SPECIAL}
self.eraseDisplay()
def unhandledControlSequence(self, buf):
print 'Could not handle', repr(buf)
def __str__(self):
lines = []
for L in self.lines:
buf = []
length = 0
for (ch, attr) in L:
if ch is not self.void:
buf.append(ch)
length = len(buf)
else:
buf.append(self.fill)
lines.append(''.join(buf[:length]))
return '\n'.join(lines)
class ExpectationTimeout(Exception):
pass
class ExpectableBuffer(TerminalBuffer):
_mark = 0
def connectionMade(self):
TerminalBuffer.connectionMade(self)
self._expecting = []
def write(self, bytes):
TerminalBuffer.write(self, bytes)
self._checkExpected()
def cursorHome(self):
TerminalBuffer.cursorHome(self)
self._mark = 0
def _timeoutExpected(self, d):
d.errback(ExpectationTimeout())
self._checkExpected()
def _checkExpected(self):
s = str(self)[self._mark:]
while self._expecting:
expr, timer, deferred = self._expecting[0]
if timer and not timer.active():
del self._expecting[0]
continue
for match in expr.finditer(s):
if timer:
timer.cancel()
del self._expecting[0]
self._mark += match.end()
s = s[match.end():]
deferred.callback(match)
break
else:
return
def expect(self, expression, timeout=None, scheduler=reactor):
d = defer.Deferred()
timer = None
if timeout:
timer = scheduler.callLater(timeout, self._timeoutExpected, d)
self._expecting.append((re.compile(expression), timer, d))
self._checkExpected()
return d
__all__ = ['CharacterAttribute', 'TerminalBuffer', 'ExpectableBuffer'] | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/insults/helper.py | helper.py |
import string
from zope.interface import implements, Interface
from twisted.internet import protocol, defer, interfaces as iinternet
class ITerminalProtocol(Interface):
def makeConnection(transport):
"""Called with an L{ITerminalTransport} when a connection is established.
"""
def keystrokeReceived(keyID, modifier):
"""A keystroke was received.
Each keystroke corresponds to one invocation of this method.
keyID is a string identifier for that key. Printable characters
are represented by themselves. Control keys, such as arrows and
function keys, are represented with symbolic constants on
L{ServerProtocol}.
"""
def terminalSize(width, height):
"""Called to indicate the size of the terminal.
A terminal of 80x24 should be assumed if this method is not
called. This method might not be called for real terminals.
"""
def unhandledControlSequence(seq):
"""Called when an unsupported control sequence is received.
@type seq: C{str}
@param seq: The whole control sequence which could not be interpreted.
"""
def connectionLost(reason):
"""Called when the connection has been lost.
reason is a Failure describing why.
"""
class TerminalProtocol(object):
implements(ITerminalProtocol)
def makeConnection(self, terminal):
# assert ITerminalTransport.providedBy(transport), "TerminalProtocol.makeConnection must be passed an ITerminalTransport implementor"
self.terminal = terminal
self.connectionMade()
def connectionMade(self):
"""Called after a connection has been established.
"""
def keystrokeReceived(self, keyID, modifier):
pass
def terminalSize(self, width, height):
pass
def unhandledControlSequence(self, seq):
pass
def connectionLost(self, reason):
pass
class ITerminalTransport(iinternet.ITransport):
def cursorUp(n=1):
"""Move the cursor up n lines.
"""
def cursorDown(n=1):
"""Move the cursor down n lines.
"""
def cursorForward(n=1):
"""Move the cursor right n columns.
"""
def cursorBackward(n=1):
"""Move the cursor left n columns.
"""
def cursorPosition(column, line):
"""Move the cursor to the given line and column.
"""
def cursorHome():
"""Move the cursor home.
"""
def index():
"""Move the cursor down one line, performing scrolling if necessary.
"""
def reverseIndex():
"""Move the cursor up one line, performing scrolling if necessary.
"""
def nextLine():
"""Move the cursor to the first position on the next line, performing scrolling if necessary.
"""
def saveCursor():
"""Save the cursor position, character attribute, character set, and origin mode selection.
"""
def restoreCursor():
"""Restore the previously saved cursor position, character attribute, character set, and origin mode selection.
If no cursor state was previously saved, move the cursor to the home position.
"""
def setModes(modes):
"""Set the given modes on the terminal.
"""
def resetModes(mode):
"""Reset the given modes on the terminal.
"""
def applicationKeypadMode():
"""Cause keypad to generate control functions.
Cursor key mode selects the type of characters generated by cursor keys.
"""
def numericKeypadMode():
"""Cause keypad to generate normal characters.
"""
def selectCharacterSet(charSet, which):
"""Select a character set.
charSet should be one of CS_US, CS_UK, CS_DRAWING, CS_ALTERNATE, or
CS_ALTERNATE_SPECIAL.
which should be one of G0 or G1.
"""
def shiftIn():
"""Activate the G0 character set.
"""
def shiftOut():
"""Activate the G1 character set.
"""
def singleShift2():
"""Shift to the G2 character set for a single character.
"""
def singleShift3():
"""Shift to the G3 character set for a single character.
"""
def selectGraphicRendition(*attributes):
"""Enabled one or more character attributes.
Arguments should be one or more of UNDERLINE, REVERSE_VIDEO, BLINK, or BOLD.
NORMAL may also be specified to disable all character attributes.
"""
def horizontalTabulationSet():
"""Set a tab stop at the current cursor position.
"""
def tabulationClear():
"""Clear the tab stop at the current cursor position.
"""
def tabulationClearAll():
"""Clear all tab stops.
"""
def doubleHeightLine(top=True):
"""Make the current line the top or bottom half of a double-height, double-width line.
If top is True, the current line is the top half. Otherwise, it is the bottom half.
"""
def singleWidthLine():
"""Make the current line a single-width, single-height line.
"""
def doubleWidthLine():
"""Make the current line a double-width line.
"""
def eraseToLineEnd():
"""Erase from the cursor to the end of line, including cursor position.
"""
def eraseToLineBeginning():
"""Erase from the cursor to the beginning of the line, including the cursor position.
"""
def eraseLine():
"""Erase the entire cursor line.
"""
def eraseToDisplayEnd():
"""Erase from the cursor to the end of the display, including the cursor position.
"""
def eraseToDisplayBeginning():
"""Erase from the cursor to the beginning of the display, including the cursor position.
"""
def eraseDisplay():
"""Erase the entire display.
"""
def deleteCharacter(n=1):
"""Delete n characters starting at the cursor position.
Characters to the right of deleted characters are shifted to the left.
"""
def insertLine(n=1):
"""Insert n lines at the cursor position.
Lines below the cursor are shifted down. Lines moved past the bottom margin are lost.
This command is ignored when the cursor is outside the scroll region.
"""
def deleteLine(n=1):
"""Delete n lines starting at the cursor position.
Lines below the cursor are shifted up. This command is ignored when the cursor is outside
the scroll region.
"""
def reportCursorPosition():
"""Return a Deferred that fires with a two-tuple of (x, y) indicating the cursor position.
"""
def reset():
"""Reset the terminal to its initial state.
"""
def unhandledControlSequence(seq):
"""Called when an unsupported control sequence is received.
@type seq: C{str}
@param seq: The whole control sequence which could not be interpreted.
"""
CSI = '\x1b'
CST = {'~': 'tilde'}
class modes:
"""ECMA 48 standardized modes
"""
# BREAKS YOPUR KEYBOARD MOFO
KEYBOARD_ACTION = KAM = 2
# When set, enables character insertion. New display characters
# move old display characters to the right. Characters moved past
# the right margin are lost.
# When reset, enables replacement mode (disables character
# insertion). New display characters replace old display
# characters at cursor position. The old character is erased.
INSERTION_REPLACEMENT = IRM = 4
# Set causes a received linefeed, form feed, or vertical tab to
# move cursor to first column of next line. RETURN transmits both
# a carriage return and linefeed. This selection is also called
# new line option.
# Reset causes a received linefeed, form feed, or vertical tab to
# move cursor to next line in current column. RETURN transmits a
# carriage return.
LINEFEED_NEWLINE = LNM = 20
class privateModes:
"""ANSI-Compatible Private Modes
"""
ERROR = 0
CURSOR_KEY = 1
ANSI_VT52 = 2
COLUMN = 3
SCROLL = 4
SCREEN = 5
ORIGIN = 6
AUTO_WRAP = 7
AUTO_REPEAT = 8
PRINTER_FORM_FEED = 18
PRINTER_EXTENT = 19
# Toggle cursor visibility (reset hides it)
CURSOR_MODE = 25
# Character sets
CS_US = 'CS_US'
CS_UK = 'CS_UK'
CS_DRAWING = 'CS_DRAWING'
CS_ALTERNATE = 'CS_ALTERNATE'
CS_ALTERNATE_SPECIAL = 'CS_ALTERNATE_SPECIAL'
# Groupings (or something?? These are like variables that can be bound to character sets)
G0 = 'G0'
G1 = 'G1'
# G2 and G3 cannot be changed, but they can be shifted to.
G2 = 'G2'
G3 = 'G3'
# Character attributes
NORMAL = 0
BOLD = 1
UNDERLINE = 4
BLINK = 5
REVERSE_VIDEO = 7
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def log(s):
file('log', 'a').write(str(s) + '\n')
# XXX TODO - These attributes are really part of the
# ITerminalTransport interface, I think.
_KEY_NAMES = ('UP_ARROW', 'DOWN_ARROW', 'RIGHT_ARROW', 'LEFT_ARROW',
'HOME', 'INSERT', 'DELETE', 'END', 'PGUP', 'PGDN', 'NUMPAD_MIDDLE',
'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9',
'F10', 'F11', 'F12',
'ALT', 'SHIFT', 'CONTROL')
class _const(object):
"""
@ivar name: A string naming this constant
"""
def __init__(self, name):
self.name = name
def __repr__(self):
return '[' + self.name + ']'
FUNCTION_KEYS = [
_const(_name) for _name in _KEY_NAMES]
class ServerProtocol(protocol.Protocol):
implements(ITerminalTransport)
protocolFactory = None
terminalProtocol = None
TAB = '\t'
BACKSPACE = '\x7f'
##
lastWrite = ''
state = 'data'
termSize = Vector(80, 24)
cursorPos = Vector(0, 0)
scrollRegion = None
# Factory who instantiated me
factory = None
def __init__(self, protocolFactory=None, *a, **kw):
"""
@param protocolFactory: A callable which will be invoked with
*a, **kw and should return an ITerminalProtocol implementor.
This will be invoked when a connection to this ServerProtocol
is established.
@param a: Any positional arguments to pass to protocolFactory.
@param kw: Any keyword arguments to pass to protocolFactory.
"""
# assert protocolFactory is None or ITerminalProtocol.implementedBy(protocolFactory), "ServerProtocol.__init__ must be passed an ITerminalProtocol implementor"
if protocolFactory is not None:
self.protocolFactory = protocolFactory
self.protocolArgs = a
self.protocolKwArgs = kw
self._cursorReports = []
def connectionMade(self):
if self.protocolFactory is not None:
self.terminalProtocol = self.protocolFactory(*self.protocolArgs, **self.protocolKwArgs)
try:
factory = self.factory
except AttributeError:
pass
else:
self.terminalProtocol.factory = factory
self.terminalProtocol.makeConnection(self)
def dataReceived(self, data):
for ch in data:
if self.state == 'data':
if ch == '\x1b':
self.state = 'escaped'
else:
self.terminalProtocol.keystrokeReceived(ch, None)
elif self.state == 'escaped':
if ch == '[':
self.state = 'bracket-escaped'
self.escBuf = []
elif ch == 'O':
self.state = 'low-function-escaped'
else:
self.state = 'data'
self._handleShortControlSequence(ch)
elif self.state == 'bracket-escaped':
if ch == 'O':
self.state = 'low-function-escaped'
elif ch.isalpha() or ch == '~':
self._handleControlSequence(''.join(self.escBuf) + ch)
del self.escBuf
self.state = 'data'
else:
self.escBuf.append(ch)
elif self.state == 'low-function-escaped':
self._handleLowFunctionControlSequence(ch)
self.state = 'data'
else:
raise ValueError("Illegal state")
def _handleShortControlSequence(self, ch):
self.terminalProtocol.keystrokeReceived(ch, self.ALT)
def _handleControlSequence(self, buf):
buf = '\x1b[' + buf
f = getattr(self.controlSequenceParser, CST.get(buf[-1], buf[-1]), None)
if f is None:
self.unhandledControlSequence(buf)
else:
f(self, self.terminalProtocol, buf[:-1])
def unhandledControlSequence(self, buf):
self.terminalProtocol.unhandledControlSequence(buf)
def _handleLowFunctionControlSequence(self, ch):
map = {'P': self.F1, 'Q': self.F2, 'R': self.F3, 'S': self.F4}
keyID = map.get(ch)
if keyID is not None:
self.terminalProtocol.keystrokeReceived(keyID, None)
else:
self.terminalProtocol.unhandledControlSequence('\x1b[O' + ch)
class ControlSequenceParser:
def A(self, proto, handler, buf):
if buf == '\x1b[':
handler.keystrokeReceived(proto.UP_ARROW, None)
else:
handler.unhandledControlSequence(buf + 'A')
def B(self, proto, handler, buf):
if buf == '\x1b[':
handler.keystrokeReceived(proto.DOWN_ARROW, None)
else:
handler.unhandledControlSequence(buf + 'B')
def C(self, proto, handler, buf):
if buf == '\x1b[':
handler.keystrokeReceived(proto.RIGHT_ARROW, None)
else:
handler.unhandledControlSequence(buf + 'C')
def D(self, proto, handler, buf):
if buf == '\x1b[':
handler.keystrokeReceived(proto.LEFT_ARROW, None)
else:
handler.unhandledControlSequence(buf + 'D')
def E(self, proto, handler, buf):
if buf == '\x1b[':
handler.keystrokeReceived(proto.NUMPAD_MIDDLE, None)
else:
handler.unhandledControlSequence(buf + 'E')
def F(self, proto, handler, buf):
if buf == '\x1b[':
handler.keystrokeReceived(proto.END, None)
else:
handler.unhandledControlSequence(buf + 'F')
def H(self, proto, handler, buf):
if buf == '\x1b[':
handler.keystrokeReceived(proto.HOME, None)
else:
handler.unhandledControlSequence(buf + 'H')
def R(self, proto, handler, buf):
if not proto._cursorReports:
handler.unhandledControlSequence(buf + 'R')
elif buf.startswith('\x1b['):
report = buf[2:]
parts = report.split(';')
if len(parts) != 2:
handler.unhandledControlSequence(buf + 'R')
else:
Pl, Pc = parts
try:
Pl, Pc = int(Pl), int(Pc)
except ValueError:
handler.unhandledControlSequence(buf + 'R')
else:
d = proto._cursorReports.pop(0)
d.callback((Pc - 1, Pl - 1))
else:
handler.unhandledControlSequence(buf + 'R')
def Z(self, proto, handler, buf):
if buf == '\x1b[':
handler.keystrokeReceived(proto.TAB, proto.SHIFT)
else:
handler.unhandledControlSequence(buf + 'Z')
def tilde(self, proto, handler, buf):
map = {1: proto.HOME, 2: proto.INSERT, 3: proto.DELETE,
4: proto.END, 5: proto.PGUP, 6: proto.PGDN,
15: proto.F5, 17: proto.F6, 18: proto.F7,
19: proto.F8, 20: proto.F9, 21: proto.F10,
23: proto.F11, 24: proto.F12}
if buf.startswith('\x1b['):
ch = buf[2:]
try:
v = int(ch)
except ValueError:
handler.unhandledControlSequence(buf + '~')
else:
symbolic = map.get(v)
if symbolic is not None:
handler.keystrokeReceived(map[v], None)
else:
handler.unhandledControlSequence(buf + '~')
else:
handler.unhandledControlSequence(buf + '~')
controlSequenceParser = ControlSequenceParser()
# ITerminalTransport
def cursorUp(self, n=1):
assert n >= 1
self.cursorPos.y = max(self.cursorPos.y - n, 0)
self.write('\x1b[%dA' % (n,))
def cursorDown(self, n=1):
assert n >= 1
self.cursorPos.y = min(self.cursorPos.y + n, self.termSize.y - 1)
self.write('\x1b[%dB' % (n,))
def cursorForward(self, n=1):
assert n >= 1
self.cursorPos.x = min(self.cursorPos.x + n, self.termSize.x - 1)
self.write('\x1b[%dC' % (n,))
def cursorBackward(self, n=1):
assert n >= 1
self.cursorPos.x = max(self.cursorPos.x - n, 0)
self.write('\x1b[%dD' % (n,))
def cursorPosition(self, column, line):
self.write('\x1b[%d;%dH' % (line + 1, column + 1))
def cursorHome(self):
self.cursorPos.x = self.cursorPos.y = 0
self.write('\x1b[H')
def index(self):
self.cursorPos.y = min(self.cursorPos.y + 1, self.termSize.y - 1)
self.write('\x1bD')
def reverseIndex(self):
self.cursorPos.y = max(self.cursorPos.y - 1, 0)
self.write('\x1bM')
def nextLine(self):
self.cursorPos.x = 0
self.cursorPos.y = min(self.cursorPos.y + 1, self.termSize.y - 1)
self.write('\x1bE')
def saveCursor(self):
self._savedCursorPos = Vector(self.cursorPos.x, self.cursorPos.y)
self.write('\x1b7')
def restoreCursor(self):
self.cursorPos = self._savedCursorPos
del self._savedCursorPos
self.write('\x1b8')
def setModes(self, modes):
# XXX Support ANSI-Compatible private modes
self.write('\x1b[%sh' % (';'.join(map(str, modes)),))
def setPrivateModes(self, modes):
self.write('\x1b[?%sh' % (';'.join(map(str, modes)),))
def resetModes(self, modes):
# XXX Support ANSI-Compatible private modes
self.write('\x1b[%sl' % (';'.join(map(str, modes)),))
def resetPrivateModes(self, modes):
self.write('\x1b[?%sl' % (';'.join(map(str, modes)),))
def applicationKeypadMode(self):
self.write('\x1b=')
def numericKeypadMode(self):
self.write('\x1b>')
def selectCharacterSet(self, charSet, which):
# XXX Rewrite these as dict lookups
if which == G0:
which = '('
elif which == G1:
which = ')'
else:
raise ValueError("`which' argument to selectCharacterSet must be G0 or G1")
if charSet == CS_UK:
charSet = 'A'
elif charSet == CS_US:
charSet = 'B'
elif charSet == CS_DRAWING:
charSet = '0'
elif charSet == CS_ALTERNATE:
charSet = '1'
elif charSet == CS_ALTERNATE_SPECIAL:
charSet = '2'
else:
raise ValueError("Invalid `charSet' argument to selectCharacterSet")
self.write('\x1b' + which + charSet)
def shiftIn(self):
self.write('\x15')
def shiftOut(self):
self.write('\x14')
def singleShift2(self):
self.write('\x1bN')
def singleShift3(self):
self.write('\x1bO')
def selectGraphicRendition(self, *attributes):
attrs = []
for a in attributes:
attrs.append(a)
self.write('\x1b[%sm' % (';'.join(attrs),))
def horizontalTabulationSet(self):
self.write('\x1bH')
def tabulationClear(self):
self.write('\x1b[q')
def tabulationClearAll(self):
self.write('\x1b[3q')
def doubleHeightLine(self, top=True):
if top:
self.write('\x1b#3')
else:
self.write('\x1b#4')
def singleWidthLine(self):
self.write('\x1b#5')
def doubleWidthLine(self):
self.write('\x1b#6')
def eraseToLineEnd(self):
self.write('\x1b[K')
def eraseToLineBeginning(self):
self.write('\x1b[1K')
def eraseLine(self):
self.write('\x1b[2K')
def eraseToDisplayEnd(self):
self.write('\x1b[J')
def eraseToDisplayBeginning(self):
self.write('\x1b[1J')
def eraseDisplay(self):
self.write('\x1b[2J')
def deleteCharacter(self, n=1):
self.write('\x1b[%dP' % (n,))
def insertLine(self, n=1):
self.write('\x1b[%dL' % (n,))
def deleteLine(self, n=1):
self.write('\x1b[%dM' % (n,))
def setScrollRegion(self, first=None, last=None):
if first is not None:
first = '%d' % (first,)
else:
first = ''
if last is not None:
last = '%d' % (last,)
else:
last = ''
self.write('\x1b[%s;%sr' % (first, last))
def resetScrollRegion(self):
self.setScrollRegion()
def reportCursorPosition(self):
d = defer.Deferred()
self._cursorReports.append(d)
self.write('\x1b[6n')
return d
def reset(self):
self.cursorPos.x = self.cursorPos.y = 0
try:
del self._savedCursorPos
except AttributeError:
pass
self.write('\x1bc')
# ITransport
def write(self, bytes):
if bytes:
self.lastWrite = bytes
self.transport.write('\r\n'.join(bytes.split('\n')))
def writeSequence(self, bytes):
self.write(''.join(bytes))
def loseConnection(self):
self.reset()
self.transport.loseConnection()
def connectionLost(self, reason):
if self.terminalProtocol is not None:
try:
self.terminalProtocol.connectionLost(reason)
finally:
self.terminalProtocol = None
# Add symbolic names for function keys
for name, const in zip(_KEY_NAMES, FUNCTION_KEYS):
setattr(ServerProtocol, name, const)
class ClientProtocol(protocol.Protocol):
terminalFactory = None
terminal = None
state = 'data'
_escBuf = None
_shorts = {
'D': 'index',
'M': 'reverseIndex',
'E': 'nextLine',
'7': 'saveCursor',
'8': 'restoreCursor',
'=': 'applicationKeypadMode',
'>': 'numericKeypadMode',
'N': 'singleShift2',
'O': 'singleShift3',
'H': 'horizontalTabulationSet',
'c': 'reset'}
_longs = {
'[': 'bracket-escape',
'(': 'select-g0',
')': 'select-g1',
'#': 'select-height-width'}
_charsets = {
'A': CS_UK,
'B': CS_US,
'0': CS_DRAWING,
'1': CS_ALTERNATE,
'2': CS_ALTERNATE_SPECIAL}
# Factory who instantiated me
factory = None
def __init__(self, terminalFactory=None, *a, **kw):
"""
@param terminalFactory: A callable which will be invoked with
*a, **kw and should return an ITerminalTransport provider.
This will be invoked when this ClientProtocol establishes a
connection.
@param a: Any positional arguments to pass to terminalFactory.
@param kw: Any keyword arguments to pass to terminalFactory.
"""
# assert terminalFactory is None or ITerminalTransport.implementedBy(terminalFactory), "ClientProtocol.__init__ must be passed an ITerminalTransport implementor"
if terminalFactory is not None:
self.terminalFactory = terminalFactory
self.terminalArgs = a
self.terminalKwArgs = kw
def connectionMade(self):
if self.terminalFactory is not None:
self.terminal = self.terminalFactory(*self.terminalArgs, **self.terminalKwArgs)
self.terminal.factory = self.factory
self.terminal.makeConnection(self)
def connectionLost(self, reason):
if self.terminal is not None:
try:
self.terminal.connectionLost(reason)
finally:
del self.terminal
def dataReceived(self, bytes):
for b in bytes:
if self.state == 'data':
if b == '\x1b':
self.state = 'escaped'
elif b == '\x14':
self.terminal.shiftOut()
elif b == '\x15':
self.terminal.shiftIn()
elif b == '\x08':
self.terminal.cursorBackward()
else:
self.terminal.write(b)
elif self.state == 'escaped':
fName = self._shorts.get(b)
if fName is not None:
self.state = 'data'
getattr(self.terminal, fName)()
else:
state = self._longs.get(b)
if state is not None:
self.state = state
else:
self.terminal.unhandledControlSequence('\x1b' + b)
self.state = 'data'
elif self.state == 'bracket-escape':
if self._escBuf is None:
self._escBuf = []
if b.isalpha() or b == '~':
self._handleControlSequence(''.join(self._escBuf), b)
del self._escBuf
self.state = 'data'
else:
self._escBuf.append(b)
elif self.state == 'select-g0':
self.terminal.selectCharacterSet(self._charsets.get(b, b), G0)
self.state = 'data'
elif self.state == 'select-g1':
self.terminal.selectCharacterSet(self._charsets.get(b, b), G1)
self.state = 'data'
elif self.state == 'select-height-width':
self._handleHeightWidth(b)
self.state = 'data'
else:
raise ValueError("Illegal state")
def _handleControlSequence(self, buf, terminal):
f = getattr(self.controlSequenceParser, CST.get(terminal, terminal), None)
if f is None:
self.terminal.unhandledControlSequence('\x1b[' + buf + terminal)
else:
f(self, self.terminal, buf)
class ControlSequenceParser:
def _makeSimple(ch, fName):
n = 'cursor' + fName
def simple(self, proto, handler, buf):
if not buf:
getattr(handler, n)(1)
else:
try:
m = int(buf)
except ValueError:
handler.unhandledControlSequence('\x1b[' + buf + ch)
else:
getattr(handler, n)(m)
return simple
for (ch, fName) in (('A', 'Up'),
('B', 'Down'),
('C', 'Forward'),
('D', 'Backward')):
exec ch + " = _makeSimple(ch, fName)"
del _makeSimple
def h(self, proto, handler, buf):
# XXX - Handle '?' to introduce ANSI-Compatible private modes.
try:
modes = map(int, buf.split(';'))
except ValueError:
handler.unhandledControlSequence('\x1b[' + buf + 'h')
else:
handler.setModes(modes)
def l(self, proto, handler, buf):
# XXX - Handle '?' to introduce ANSI-Compatible private modes.
try:
modes = map(int, buf.split(';'))
except ValueError:
handler.unhandledControlSequence('\x1b[' + buf + 'l')
else:
handler.resetModes(modes)
def r(self, proto, handler, buf):
parts = buf.split(';')
if len(parts) == 1:
handler.setScrollRegion(None, None)
elif len(parts) == 2:
try:
if parts[0]:
pt = int(parts[0])
else:
pt = None
if parts[1]:
pb = int(parts[1])
else:
pb = None
except ValueError:
handler.unhandledControlSequence('\x1b[' + buf + 'r')
else:
handler.setScrollRegion(pt, pb)
else:
handler.unhandledControlSequence('\x1b[' + buf + 'r')
def K(self, proto, handler, buf):
if not buf:
handler.eraseToLineEnd()
elif buf == '1':
handler.eraseToLineBeginning()
elif buf == '2':
handler.eraseLine()
else:
handler.unhandledControlSequence('\x1b[' + buf + 'K')
def H(self, proto, handler, buf):
handler.cursorHome()
def J(self, proto, handler, buf):
if not buf:
handler.eraseToDisplayEnd()
elif buf == '1':
handler.eraseToDisplayBeginning()
elif buf == '2':
handler.eraseDisplay()
else:
handler.unhandledControlSequence('\x1b[' + buf + 'J')
def P(self, proto, handler, buf):
if not buf:
handler.deleteCharacter(1)
else:
try:
n = int(buf)
except ValueError:
handler.unhandledControlSequence('\x1b[' + buf + 'P')
else:
handler.deleteCharacter(n)
def L(self, proto, handler, buf):
if not buf:
handler.insertLine(1)
else:
try:
n = int(buf)
except ValueError:
handler.unhandledControlSequence('\x1b[' + buf + 'L')
else:
handler.insertLine(n)
def M(self, proto, handler, buf):
if not buf:
handler.deleteLine(1)
else:
try:
n = int(buf)
except ValueError:
handler.unhandledControlSequence('\x1b[' + buf + 'M')
else:
handler.deleteLine(n)
def n(self, proto, handler, buf):
if buf == '6':
x, y = handler.reportCursorPosition()
proto.transport.write('\x1b[%d;%dR' % (x + 1, y + 1))
else:
handler.unhandledControlSequence('\x1b[' + buf + 'n')
def m(self, proto, handler, buf):
if not buf:
handler.selectGraphicRendition(NORMAL)
else:
attrs = []
for a in buf.split(';'):
try:
a = int(a)
except ValueError:
pass
attrs.append(a)
handler.selectGraphicRendition(*attrs)
controlSequenceParser = ControlSequenceParser()
def _handleHeightWidth(self, b):
if b == '3':
self.terminal.doubleHeightLine(True)
elif b == '4':
self.terminal.doubleHeightLine(False)
elif b == '5':
self.terminal.singleWidthLine()
elif b == '6':
self.terminal.doubleWidthLine()
else:
self.terminal.unhandledControlSequence('\x1b#' + b)
__all__ = [
# Interfaces
'ITerminalProtocol', 'ITerminalTransport',
# Symbolic constants
'modes', 'privateModes', 'FUNCTION_KEYS',
'CS_US', 'CS_UK', 'CS_DRAWING', 'CS_ALTERNATE', 'CS_ALTERNATE_SPECIAL',
'G0', 'G1', 'G2', 'G3',
'UNDERLINE', 'REVERSE_VIDEO', 'BLINK', 'BOLD', 'NORMAL',
# Protocol classes
'ServerProtocol', 'ClientProtocol'] | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/insults/insults.py | insults.py |
from twisted.internet import protocol
class InsultsClient(protocol.Protocol):
escapeTimeout = 0.2
def __init__(self):
self.width = self.height = None
self.xpos = self.ypos = 0
self.commandQueue = []
self.inEscape = ''
def setSize(self, width, height):
call = 0
if self.width:
call = 1
self.width = width
self.height = height
if call:
self.windowSizeChanged()
def dataReceived(self, data):
from twisted.internet import reactor
for ch in data:
if ch == '\x1b':
if self.inEscape:
self.keyReceived(ch)
self.inEscape = ''
else:
self.inEscape = ch
self.escapeCall = reactor.callLater(self.escapeTimeout,
self.endEscape)
elif ch in 'ABCD' and self.inEscape:
self.inEscape = ''
self.escapeCall.cancel()
if ch == 'A':
self.keyReceived('<Up>')
elif ch == 'B':
self.keyReceived('<Down>')
elif ch == 'C':
self.keyReceived('<Right>')
elif ch == 'D':
self.keyReceived('<Left>')
elif self.inEscape:
self.inEscape += ch
else:
self.keyReceived(ch)
def endEscape(self):
ch = self.inEscape
self.inEscape = ''
self.keyReceived(ch)
def initScreen(self):
self.transport.write('\x1b=\x1b[?1h')
def gotoXY(self, x, y):
"""Go to a position on the screen.
"""
self.xpos = x
self.ypos = y
self.commandQueue.append(('gotoxy', x, y))
def writeCh(self, ch):
"""Write a character to the screen. If we're at the end of the row,
ignore the write.
"""
if self.xpos < self.width - 1:
self.commandQueue.append(('write', ch))
self.xpos += 1
def writeStr(self, s):
"""Write a string to the screen. This does not wrap a the edge of the
screen, and stops at \\r and \\n.
"""
s = s[:self.width-self.xpos]
if '\n' in s:
s=s[:s.find('\n')]
if '\r' in s:
s=s[:s.find('\r')]
self.commandQueue.append(('write', s))
self.xpos += len(s)
def eraseToLine(self):
"""Erase from the current position to the end of the line.
"""
self.commandQueue.append(('eraseeol',))
def eraseToScreen(self):
"""Erase from the current position to the end of the screen.
"""
self.commandQueue.append(('eraseeos',))
def clearScreen(self):
"""Clear the screen, and return the cursor to 0, 0.
"""
self.commandQueue = [('cls',)]
self.xpos = self.ypos = 0
def setAttributes(self, *attrs):
"""Set the attributes for drawing on the screen.
"""
self.commandQueue.append(('attributes', attrs))
def refresh(self):
"""Redraw the screen.
"""
redraw = ''
for command in self.commandQueue:
if command[0] == 'gotoxy':
redraw += '\x1b[%i;%iH' % (command[2]+1, command[1]+1)
elif command[0] == 'write':
redraw += command[1]
elif command[0] == 'eraseeol':
redraw += '\x1b[0K'
elif command[0] == 'eraseeos':
redraw += '\x1b[OJ'
elif command[0] == 'cls':
redraw += '\x1b[H\x1b[J'
elif command[0] == 'attributes':
redraw += '\x1b[%sm' % ';'.join(map(str, command[1]))
else:
print command
self.commandQueue = []
self.transport.write(redraw)
def windowSizeChanged(self):
"""Called when the size of the window changes.
Might want to redraw the screen here, or something.
"""
def keyReceived(self, key):
"""Called when the user hits a key.
""" | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/insults/client.py | client.py |
from twisted.conch.insults import helper, insults
class _Attribute(object):
def __init__(self):
self.children = []
def __getitem__(self, item):
assert isinstance(item, (list, tuple, _Attribute, str))
if isinstance(item, (list, tuple)):
self.children.extend(item)
else:
self.children.append(item)
return self
def serialize(self, write, attrs=None):
if attrs is None:
attrs = helper.CharacterAttribute()
for ch in self.children:
if isinstance(ch, _Attribute):
ch.serialize(write, attrs.copy())
else:
write(attrs.toVT102())
write(ch)
class _NormalAttr(_Attribute):
def serialize(self, write, attrs):
attrs.__init__()
super(_NormalAttr, self).serialize(write, attrs)
class _OtherAttr(_Attribute):
def __init__(self, attrname, attrvalue):
self.attrname = attrname
self.attrvalue = attrvalue
self.children = []
def __neg__(self):
result = _OtherAttr(self.attrname, not self.attrvalue)
result.children.extend(self.children)
return result
def serialize(self, write, attrs):
attrs = attrs.wantOne(**{self.attrname: self.attrvalue})
super(_OtherAttr, self).serialize(write, attrs)
class _ColorAttr(_Attribute):
def __init__(self, color, ground):
self.color = color
self.ground = ground
self.children = []
def serialize(self, write, attrs):
attrs = attrs.wantOne(**{self.ground: self.color})
super(_ColorAttr, self).serialize(write, attrs)
class _ForegroundColorAttr(_ColorAttr):
def __init__(self, color):
super(_ForegroundColorAttr, self).__init__(color, 'foreground')
class _BackgroundColorAttr(_ColorAttr):
def __init__(self, color):
super(_BackgroundColorAttr, self).__init__(color, 'background')
class CharacterAttributes(object):
class _ColorAttribute(object):
def __init__(self, ground):
self.ground = ground
attrs = {
'black': helper.BLACK,
'red': helper.RED,
'green': helper.GREEN,
'yellow': helper.YELLOW,
'blue': helper.BLUE,
'magenta': helper.MAGENTA,
'cyan': helper.CYAN,
'white': helper.WHITE}
def __getattr__(self, name):
try:
return self.ground(self.attrs[name])
except KeyError:
raise AttributeError(name)
fg = _ColorAttribute(_ForegroundColorAttr)
bg = _ColorAttribute(_BackgroundColorAttr)
attrs = {
'bold': insults.BOLD,
'blink': insults.BLINK,
'underline': insults.UNDERLINE,
'reverseVideo': insults.REVERSE_VIDEO}
def __getattr__(self, name):
if name == 'normal':
return _NormalAttr()
if name in self.attrs:
return _OtherAttr(name, True)
raise AttributeError(name)
def flatten(output, attrs):
"""Serialize a sequence of characters with attribute information
The resulting string can be interpreted by VT102-compatible
terminals so that the contained characters are displayed and, for
those attributes which the terminal supports, have the attributes
specified in the input.
For example, if your terminal is VT102 compatible, you might run
this for a colorful variation on the \"hello world\" theme::
| from twisted.conch.insults.text import flatten, attributes as A
| from twisted.conch.insults.helper import CharacterAttribute
| print flatten(
| A.normal[A.bold[A.fg.red['He'], A.fg.green['ll'], A.fg.magenta['o'], ' ',
| A.fg.yellow['Wo'], A.fg.blue['rl'], A.fg.cyan['d!']]],
| CharacterAttribute())
@param output: Object returned by accessing attributes of the
module-level attributes object.
@param attrs: A L{twisted.conch.insults.helper.CharacterAttribute}
instance
@return: A VT102-friendly string
"""
L = []
output.serialize(L.append, attrs)
return ''.join(L)
attributes = CharacterAttributes()
__all__ = ['attributes', 'flatten'] | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/insults/text.py | text.py |
import array
from twisted.conch.insults import insults, helper
from twisted.python import text as tptext
class YieldFocus(Exception):
"""Input focus manipulation exception
"""
class BoundedTerminalWrapper(object):
def __init__(self, terminal, width, height, xoff, yoff):
self.width = width
self.height = height
self.xoff = xoff
self.yoff = yoff
self.terminal = terminal
self.cursorForward = terminal.cursorForward
self.selectCharacterSet = terminal.selectCharacterSet
self.selectGraphicRendition = terminal.selectGraphicRendition
self.saveCursor = terminal.saveCursor
self.restoreCursor = terminal.restoreCursor
def cursorPosition(self, x, y):
return self.terminal.cursorPosition(
self.xoff + min(self.width, x),
self.yoff + min(self.height, y)
)
def cursorHome(self):
return self.terminal.cursorPosition(
self.xoff, self.yoff)
def write(self, bytes):
return self.terminal.write(bytes)
class Widget(object):
focused = False
parent = None
dirty = False
width = height = None
def repaint(self):
if not self.dirty:
self.dirty = True
if self.parent is not None and not self.parent.dirty:
self.parent.repaint()
def filthy(self):
self.dirty = True
def redraw(self, width, height, terminal):
self.filthy()
self.draw(width, height, terminal)
def draw(self, width, height, terminal):
if width != self.width or height != self.height or self.dirty:
self.width = width
self.height = height
self.dirty = False
self.render(width, height, terminal)
def render(self, width, height, terminal):
pass
def sizeHint(self):
return None
def keystrokeReceived(self, keyID, modifier):
if keyID == '\t':
self.tabReceived(modifier)
elif keyID == '\x7f':
self.backspaceReceived()
elif keyID in insults.FUNCTION_KEYS:
self.functionKeyReceived(keyID, modifier)
else:
self.characterReceived(keyID, modifier)
def tabReceived(self, modifier):
# XXX TODO - Handle shift+tab
raise YieldFocus()
def focusReceived(self):
"""Called when focus is being given to this widget.
May raise YieldFocus is this widget does not want focus.
"""
self.focused = True
self.repaint()
def focusLost(self):
self.focused = False
self.repaint()
def backspaceReceived(self):
pass
def functionKeyReceived(self, keyID, modifier):
func = getattr(self, 'func_' + keyID.name, None)
if func is not None:
func(modifier)
def characterReceived(self, keyID, modifier):
pass
class ContainerWidget(Widget):
"""
@ivar focusedChild: The contained widget which currently has
focus, or None.
"""
focusedChild = None
focused = False
def __init__(self):
Widget.__init__(self)
self.children = []
def addChild(self, child):
assert child.parent is None
child.parent = self
self.children.append(child)
if self.focusedChild is None and self.focused:
try:
child.focusReceived()
except YieldFocus:
pass
else:
self.focusedChild = child
self.repaint()
def remChild(self, child):
assert child.parent is self
child.parent = None
self.children.remove(child)
self.repaint()
def filthy(self):
for ch in self.children:
ch.filthy()
Widget.filthy(self)
def render(self, width, height, terminal):
for ch in self.children:
ch.draw(width, height, terminal)
def changeFocus(self):
self.repaint()
if self.focusedChild is not None:
self.focusedChild.focusLost()
focusedChild = self.focusedChild
self.focusedChild = None
try:
curFocus = self.children.index(focusedChild) + 1
except ValueError:
raise YieldFocus()
else:
curFocus = 0
while curFocus < len(self.children):
try:
self.children[curFocus].focusReceived()
except YieldFocus:
curFocus += 1
else:
self.focusedChild = self.children[curFocus]
return
# None of our children wanted focus
raise YieldFocus()
def focusReceived(self):
self.changeFocus()
self.focused = True
def keystrokeReceived(self, keyID, modifier):
if self.focusedChild is not None:
try:
self.focusedChild.keystrokeReceived(keyID, modifier)
except YieldFocus:
self.changeFocus()
self.repaint()
else:
Widget.keystrokeReceived(self, keyID, modifier)
class TopWindow(ContainerWidget):
focused = True
def __init__(self, painter):
ContainerWidget.__init__(self)
self.painter = painter
_paintCall = None
def repaint(self):
if self._paintCall is None:
from twisted.internet import reactor
self._paintCall = reactor.callLater(0, self._paint)
ContainerWidget.repaint(self)
def _paint(self):
self._paintCall = None
self.painter()
def changeFocus(self):
try:
ContainerWidget.changeFocus(self)
except YieldFocus:
try:
ContainerWidget.changeFocus(self)
except YieldFocus:
pass
def keystrokeReceived(self, keyID, modifier):
try:
ContainerWidget.keystrokeReceived(self, keyID, modifier)
except YieldFocus:
self.changeFocus()
class AbsoluteBox(ContainerWidget):
def moveChild(self, child, x, y):
for n in range(len(self.children)):
if self.children[n][0] is child:
self.children[n] = (child, x, y)
break
else:
raise ValueError("No such child", child)
def render(self, width, height, terminal):
for (ch, x, y) in self.children:
wrap = BoundedTerminalWrapper(terminal, width - x, height - y, x, y)
ch.draw(width, height, wrap)
class _Box(ContainerWidget):
TOP, CENTER, BOTTOM = range(3)
def __init__(self, gravity=CENTER):
ContainerWidget.__init__(self)
self.gravity = gravity
def sizeHint(self):
height = 0
width = 0
for ch in self.children:
hint = ch.sizeHint()
if hint is None:
hint = (None, None)
if self.variableDimension == 0:
if hint[0] is None:
width = None
elif width is not None:
width += hint[0]
if hint[1] is None:
height = None
elif height is not None:
height = max(height, hint[1])
else:
if hint[0] is None:
width = None
elif width is not None:
width = max(width, hint[0])
if hint[1] is None:
height = None
elif height is not None:
height += hint[1]
return width, height
def render(self, width, height, terminal):
if not self.children:
return
greedy = 0
wants = []
for ch in self.children:
hint = ch.sizeHint()
if hint is None:
hint = (None, None)
if hint[self.variableDimension] is None:
greedy += 1
wants.append(hint[self.variableDimension])
length = (width, height)[self.variableDimension]
totalWant = sum([w for w in wants if w is not None])
if greedy:
leftForGreedy = int((length - totalWant) / greedy)
widthOffset = heightOffset = 0
for want, ch in zip(wants, self.children):
if want is None:
want = leftForGreedy
subWidth, subHeight = width, height
if self.variableDimension == 0:
subWidth = want
else:
subHeight = want
wrap = BoundedTerminalWrapper(
terminal,
subWidth,
subHeight,
widthOffset,
heightOffset,
)
ch.draw(subWidth, subHeight, wrap)
if self.variableDimension == 0:
widthOffset += want
else:
heightOffset += want
class HBox(_Box):
variableDimension = 0
class VBox(_Box):
variableDimension = 1
class Packer(ContainerWidget):
def render(self, width, height, terminal):
if not self.children:
return
root = int(len(self.children) ** 0.5 + 0.5)
boxes = [VBox() for n in range(root)]
for n, ch in enumerate(self.children):
boxes[n % len(boxes)].addChild(ch)
h = HBox()
map(h.addChild, boxes)
h.render(width, height, terminal)
class Canvas(Widget):
focused = False
contents = None
def __init__(self):
Widget.__init__(self)
self.resize(1, 1)
def resize(self, width, height):
contents = array.array('c', ' ' * width * height)
if self.contents is not None:
for x in range(min(width, self._width)):
for y in range(min(height, self._height)):
contents[width * y + x] = self[x, y]
self.contents = contents
self._width = width
self._height = height
if self.x >= width:
self.x = width - 1
if self.y >= height:
self.y = height - 1
def __getitem__(self, (x, y)):
return self.contents[(self._width * y) + x]
def __setitem__(self, (x, y), value):
self.contents[(self._width * y) + x] = value
def clear(self):
self.contents = array.array('c', ' ' * len(self.contents))
def render(self, width, height, terminal):
if not width or not height:
return
if width != self._width or height != self._height:
self.resize(width, height)
for i in range(height):
terminal.cursorPosition(0, i)
terminal.write(''.join(self.contents[self._width * i:self._width * i + self._width])[:width])
def horizontalLine(terminal, y, left, right):
terminal.selectCharacterSet(insults.CS_DRAWING, insults.G0)
terminal.cursorPosition(left, y)
terminal.write(chr(0161) * (right - left))
terminal.selectCharacterSet(insults.CS_US, insults.G0)
def verticalLine(terminal, x, top, bottom):
terminal.selectCharacterSet(insults.CS_DRAWING, insults.G0)
for n in xrange(top, bottom):
terminal.cursorPosition(x, n)
terminal.write(chr(0170))
terminal.selectCharacterSet(insults.CS_US, insults.G0)
def rectangle(terminal, (top, left), (width, height)):
terminal.selectCharacterSet(insults.CS_DRAWING, insults.G0)
terminal.cursorPosition(top, left)
terminal.write(chr(0154))
terminal.write(chr(0161) * (width - 2))
terminal.write(chr(0153))
for n in range(height - 2):
terminal.cursorPosition(left, top + n + 1)
terminal.write(chr(0170))
terminal.cursorForward(width - 2)
terminal.write(chr(0170))
terminal.cursorPosition(0, top + height - 1)
terminal.write(chr(0155))
terminal.write(chr(0161) * (width - 2))
terminal.write(chr(0152))
terminal.selectCharacterSet(insults.CS_US, insults.G0)
class Border(Widget):
def __init__(self, containee):
Widget.__init__(self)
self.containee = containee
self.containee.parent = self
def focusReceived(self):
return self.containee.focusReceived()
def focusLost(self):
return self.containee.focusLost()
def keystrokeReceived(self, keyID, modifier):
return self.containee.keystrokeReceived(keyID, modifier)
def sizeHint(self):
hint = self.containee.sizeHint()
if hint is None:
hint = (None, None)
if hint[0] is None:
x = None
else:
x = hint[0] + 2
if hint[1] is None:
y = None
else:
y = hint[1] + 2
return x, y
def filthy(self):
self.containee.filthy()
Widget.filthy(self)
def render(self, width, height, terminal):
if self.containee.focused:
terminal.write('\x1b[31m')
rectangle(terminal, (0, 0), (width, height))
terminal.write('\x1b[0m')
wrap = BoundedTerminalWrapper(terminal, width - 2, height - 2, 1, 1)
self.containee.draw(width - 2, height - 2, wrap)
class Button(Widget):
def __init__(self, label, onPress):
Widget.__init__(self)
self.label = label
self.onPress = onPress
def sizeHint(self):
return len(self.label), 1
def characterReceived(self, keyID, modifier):
if keyID == '\r':
self.onPress()
def render(self, width, height, terminal):
terminal.cursorPosition(0, 0)
if self.focused:
terminal.write('\x1b[1m' + self.label + '\x1b[0m')
else:
terminal.write(self.label)
class TextInput(Widget):
def __init__(self, maxwidth, onSubmit):
Widget.__init__(self)
self.onSubmit = onSubmit
self.maxwidth = maxwidth
self.buffer = ''
self.cursor = 0
def setText(self, text):
self.buffer = text[:self.maxwidth]
self.cursor = len(self.buffer)
self.repaint()
def func_LEFT_ARROW(self, modifier):
if self.cursor > 0:
self.cursor -= 1
self.repaint()
def func_RIGHT_ARROW(self, modifier):
if self.cursor < len(self.buffer):
self.cursor += 1
self.repaint()
def backspaceReceived(self):
if self.cursor > 0:
self.buffer = self.buffer[:self.cursor - 1] + self.buffer[self.cursor:]
self.cursor -= 1
self.repaint()
def characterReceived(self, keyID, modifier):
if keyID == '\r':
self.onSubmit(self.buffer)
else:
if len(self.buffer) < self.maxwidth:
self.buffer = self.buffer[:self.cursor] + keyID + self.buffer[self.cursor:]
self.cursor += 1
self.repaint()
def sizeHint(self):
return self.maxwidth + 1, 1
def render(self, width, height, terminal):
currentText = self._renderText()
terminal.cursorPosition(0, 0)
if self.focused:
terminal.write(currentText[:self.cursor])
cursor(terminal, currentText[self.cursor:self.cursor+1] or ' ')
terminal.write(currentText[self.cursor+1:])
terminal.write(' ' * (self.maxwidth - len(currentText) + 1))
else:
more = self.maxwidth - len(currentText)
terminal.write(currentText + '_' * more)
def _renderText(self):
return self.buffer
class PasswordInput(TextInput):
def _renderText(self):
return '*' * len(self.buffer)
class TextOutput(Widget):
text = ''
def __init__(self, size=None):
Widget.__init__(self)
self.size = size
def sizeHint(self):
return self.size
def render(self, width, height, terminal):
terminal.cursorPosition(0, 0)
text = self.text[:width]
terminal.write(text + ' ' * (width - len(text)))
def setText(self, text):
self.text = text
self.repaint()
def focusReceived(self):
raise YieldFocus()
class TextOutputArea(TextOutput):
WRAP, TRUNCATE = range(2)
def __init__(self, size=None, longLines=WRAP):
TextOutput.__init__(self, size)
self.longLines = longLines
def render(self, width, height, terminal):
n = 0
inputLines = self.text.splitlines()
outputLines = []
while inputLines:
if self.longLines == self.WRAP:
wrappedLines = tptext.greedyWrap(inputLines.pop(0), width)
outputLines.extend(wrappedLines or [''])
else:
outputLines.append(inputLines.pop(0)[:width])
if len(outputLines) >= height:
break
for n, L in enumerate(outputLines[:height]):
terminal.cursorPosition(0, n)
terminal.write(L)
class Viewport(Widget):
_xOffset = 0
_yOffset = 0
def xOffset():
def get(self):
return self._xOffset
def set(self, value):
if self._xOffset != value:
self._xOffset = value
self.repaint()
return get, set
xOffset = property(*xOffset())
def yOffset():
def get(self):
return self._yOffset
def set(self, value):
if self._yOffset != value:
self._yOffset = value
self.repaint()
return get, set
yOffset = property(*yOffset())
_width = 160
_height = 24
def __init__(self, containee):
Widget.__init__(self)
self.containee = containee
self.containee.parent = self
self._buf = helper.TerminalBuffer()
self._buf.width = self._width
self._buf.height = self._height
self._buf.connectionMade()
def filthy(self):
self.containee.filthy()
Widget.filthy(self)
def render(self, width, height, terminal):
self.containee.draw(self._width, self._height, self._buf)
# XXX /Lame/
for y, line in enumerate(self._buf.lines[self._yOffset:self._yOffset + height]):
terminal.cursorPosition(0, y)
n = 0
for n, (ch, attr) in enumerate(line[self._xOffset:self._xOffset + width]):
if ch is self._buf.void:
ch = ' '
terminal.write(ch)
if n < width:
terminal.write(' ' * (width - n - 1))
class _Scrollbar(Widget):
def __init__(self, onScroll):
Widget.__init__(self)
self.onScroll = onScroll
self.percent = 0.0
def smaller(self):
self.percent = min(1.0, max(0.0, self.onScroll(-1)))
self.repaint()
def bigger(self):
self.percent = min(1.0, max(0.0, self.onScroll(+1)))
self.repaint()
class HorizontalScrollbar(_Scrollbar):
def sizeHint(self):
return (None, 1)
def func_LEFT_ARROW(self, modifier):
self.smaller()
def func_RIGHT_ARROW(self, modifier):
self.bigger()
_left = u'\N{BLACK LEFT-POINTING TRIANGLE}'
_right = u'\N{BLACK RIGHT-POINTING TRIANGLE}'
_bar = u'\N{LIGHT SHADE}'
_slider = u'\N{DARK SHADE}'
def render(self, width, height, terminal):
terminal.cursorPosition(0, 0)
n = width - 3
before = int(n * self.percent)
after = n - before
me = self._left + (self._bar * before) + self._slider + (self._bar * after) + self._right
terminal.write(me.encode('utf-8'))
class VerticalScrollbar(_Scrollbar):
def sizeHint(self):
return (1, None)
def func_UP_ARROW(self, modifier):
self.smaller()
def func_DOWN_ARROW(self, modifier):
self.bigger()
_up = u'\N{BLACK UP-POINTING TRIANGLE}'
_down = u'\N{BLACK DOWN-POINTING TRIANGLE}'
_bar = u'\N{LIGHT SHADE}'
_slider = u'\N{DARK SHADE}'
def render(self, width, height, terminal):
terminal.cursorPosition(0, 0)
knob = int(self.percent * (height - 2))
terminal.write(self._up.encode('utf-8'))
for i in xrange(1, height - 1):
terminal.cursorPosition(0, i)
if i != (knob + 1):
terminal.write(self._bar.encode('utf-8'))
else:
terminal.write(self._slider.encode('utf-8'))
terminal.cursorPosition(0, height - 1)
terminal.write(self._down.encode('utf-8'))
class ScrolledArea(Widget):
def __init__(self, containee):
Widget.__init__(self, containee)
self._viewport = Viewport(containee)
self._horiz = HorizontalScrollbar(self._horizScroll)
self._vert = VerticalScrollbar(self._vertScroll)
for w in self._viewport, self._horiz, self._vert:
w.parent = self
def _horizScroll(self, n):
self._viewport.xOffset += n
self._viewport.xOffset = max(0, self._viewport.xOffset)
return self._viewport.xOffset / 25.0
def _vertScroll(self, n):
self._viewport.yOffset += n
self._viewport.yOffset = max(0, self._viewport.yOffset)
return self._viewport.yOffset / 25.0
def func_UP_ARROW(self, modifier):
self._vert.smaller()
def func_DOWN_ARROW(self, modifier):
self._vert.bigger()
def func_LEFT_ARROW(self, modifier):
self._horiz.smaller()
def func_RIGHT_ARROW(self, modifier):
self._horiz.bigger()
def filthy(self):
self._viewport.filthy()
self._horiz.filthy()
self._vert.filthy()
Widget.filthy(self)
def render(self, width, height, terminal):
wrapper = BoundedTerminalWrapper(terminal, width - 2, height - 2, 1, 1)
self._viewport.draw(width - 2, height - 2, wrapper)
if self.focused:
terminal.write('\x1b[31m')
horizontalLine(terminal, 0, 1, width - 1)
verticalLine(terminal, 0, 1, height - 1)
self._vert.draw(1, height - 1, BoundedTerminalWrapper(terminal, 1, height - 1, width - 1, 0))
self._horiz.draw(width, 1, BoundedTerminalWrapper(terminal, width, 1, 0, height - 1))
terminal.write('\x1b[0m')
def cursor(terminal, ch):
terminal.saveCursor()
terminal.selectGraphicRendition(str(insults.REVERSE_VIDEO))
terminal.write(ch)
terminal.restoreCursor()
terminal.cursorForward()
class Selection(Widget):
# Index into the sequence
focusedIndex = 0
# Offset into the displayed subset of the sequence
renderOffset = 0
def __init__(self, sequence, onSelect, minVisible=None):
Widget.__init__(self)
self.sequence = sequence
self.onSelect = onSelect
self.minVisible = minVisible
if minVisible is not None:
self._width = max(map(len, self.sequence))
def sizeHint(self):
if self.minVisible is not None:
return self._width, self.minVisible
def func_UP_ARROW(self, modifier):
if self.focusedIndex > 0:
self.focusedIndex -= 1
if self.renderOffset > 0:
self.renderOffset -= 1
self.repaint()
def func_PGUP(self, modifier):
if self.renderOffset != 0:
self.focusedIndex -= self.renderOffset
self.renderOffset = 0
else:
self.focusedIndex = max(0, self.focusedIndex - self.height)
self.repaint()
def func_DOWN_ARROW(self, modifier):
if self.focusedIndex < len(self.sequence) - 1:
self.focusedIndex += 1
if self.renderOffset < self.height - 1:
self.renderOffset += 1
self.repaint()
def func_PGDN(self, modifier):
if self.renderOffset != self.height - 1:
change = self.height - self.renderOffset - 1
if change + self.focusedIndex >= len(self.sequence):
change = len(self.sequence) - self.focusedIndex - 1
self.focusedIndex += change
self.renderOffset = self.height - 1
else:
self.focusedIndex = min(len(self.sequence) - 1, self.focusedIndex + self.height)
self.repaint()
def characterReceived(self, keyID, modifier):
if keyID == '\r':
self.onSelect(self.sequence[self.focusedIndex])
def render(self, width, height, terminal):
self.height = height
start = self.focusedIndex - self.renderOffset
if start > len(self.sequence) - height:
start = max(0, len(self.sequence) - height)
elements = self.sequence[start:start+height]
for n, ele in enumerate(elements):
terminal.cursorPosition(0, n)
if n == self.renderOffset:
terminal.saveCursor()
if self.focused:
modes = str(insults.REVERSE_VIDEO), str(insults.BOLD)
else:
modes = str(insults.REVERSE_VIDEO),
terminal.selectGraphicRendition(*modes)
text = ele[:width]
terminal.write(text + (' ' * (width - len(text))))
if n == self.renderOffset:
terminal.restoreCursor() | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/insults/window.py | window.py |
#
# $Id: conch.py,v 1.65 2004/03/11 00:29:14 z3p Exp $
#""" Implementation module for the `conch` command.
#"""
from twisted.conch.client import agent, connect, default, options
from twisted.conch.error import ConchError
from twisted.conch.ssh import connection, common
from twisted.conch.ssh import session, forwarding, channel
from twisted.internet import reactor, stdio, defer, task
from twisted.python import log, usage
import os, sys, getpass, struct, tty, fcntl, base64, signal, stat, errno
class ClientOptions(options.ConchOptions):
synopsis = """Usage: conch [options] host [command]
"""
optParameters = [['escape', 'e', '~'],
['localforward', 'L', None, 'listen-port:host:port Forward local port to remote address'],
['remoteforward', 'R', None, 'listen-port:host:port Forward remote port to local address'],
]
optFlags = [['null', 'n', 'Redirect input from /dev/null.'],
['fork', 'f', 'Fork to background after authentication.'],
['tty', 't', 'Tty; allocate a tty even if command is given.'],
['notty', 'T', 'Do not allocate a tty.'],
['noshell', 'N', 'Do not execute a shell or command.'],
['subsystem', 's', 'Invoke command (mandatory) as SSH2 subsystem.'],
]
#zsh_altArgDescr = {"foo":"use this description for foo instead"}
#zsh_multiUse = ["foo", "bar"]
#zsh_mutuallyExclusive = [("foo", "bar"), ("bar", "baz")]
#zsh_actions = {"foo":'_files -g "*.foo"', "bar":"(one two three)"}
zsh_actionDescr = {"localforward":"listen-port:host:port",
"remoteforward":"listen-port:host:port"}
zsh_extras = ["*:command: "]
localForwards = []
remoteForwards = []
def opt_escape(self, esc):
"Set escape character; ``none'' = disable"
if esc == 'none':
self['escape'] = None
elif esc[0] == '^' and len(esc) == 2:
self['escape'] = chr(ord(esc[1])-64)
elif len(esc) == 1:
self['escape'] = esc
else:
sys.exit("Bad escape character '%s'." % esc)
def opt_localforward(self, f):
"Forward local port to remote address (lport:host:port)"
localPort, remoteHost, remotePort = f.split(':') # doesn't do v6 yet
localPort = int(localPort)
remotePort = int(remotePort)
self.localForwards.append((localPort, (remoteHost, remotePort)))
def opt_remoteforward(self, f):
"""Forward remote port to local address (rport:host:port)"""
remotePort, connHost, connPort = f.split(':') # doesn't do v6 yet
remotePort = int(remotePort)
connPort = int(connPort)
self.remoteForwards.append((remotePort, (connHost, connPort)))
def parseArgs(self, host, *command):
self['host'] = host
self['command'] = ' '.join(command)
# Rest of code in "run"
options = None
conn = None
exitStatus = 0
old = None
_inRawMode = 0
_savedRawMode = None
def run():
global options, old
args = sys.argv[1:]
if '-l' in args: # cvs is an idiot
i = args.index('-l')
args = args[i:i+2]+args
del args[i+2:i+4]
for arg in args[:]:
try:
i = args.index(arg)
if arg[:2] == '-o' and args[i+1][0]!='-':
args[i:i+2] = [] # suck on it scp
except ValueError:
pass
options = ClientOptions()
try:
options.parseOptions(args)
except usage.UsageError, u:
print 'ERROR: %s' % u
options.opt_help()
sys.exit(1)
if options['log']:
if options['logfile']:
if options['logfile'] == '-':
f = sys.stdout
else:
f = file(options['logfile'], 'a+')
else:
f = sys.stderr
realout = sys.stdout
log.startLogging(f)
sys.stdout = realout
else:
log.discardLogs()
doConnect()
fd = sys.stdin.fileno()
try:
old = tty.tcgetattr(fd)
except:
old = None
try:
oldUSR1 = signal.signal(signal.SIGUSR1, lambda *a: reactor.callLater(0, reConnect))
except:
oldUSR1 = None
try:
reactor.run()
finally:
if old:
tty.tcsetattr(fd, tty.TCSANOW, old)
if oldUSR1:
signal.signal(signal.SIGUSR1, oldUSR1)
if (options['command'] and options['tty']) or not options['notty']:
signal.signal(signal.SIGWINCH, signal.SIG_DFL)
if sys.stdout.isatty() and not options['command']:
print 'Connection to %s closed.' % options['host']
sys.exit(exitStatus)
def handleError():
from twisted.python import failure
global exitStatus
exitStatus = 2
reactor.callLater(0.01, _stopReactor)
log.err(failure.Failure())
raise
def _stopReactor():
try:
reactor.stop()
except: pass
def doConnect():
# log.deferr = handleError # HACK
if '@' in options['host']:
options['user'], options['host'] = options['host'].split('@',1)
if not options.identitys:
options.identitys = ['~/.ssh/id_rsa', '~/.ssh/id_dsa']
host = options['host']
if not options['user']:
options['user'] = getpass.getuser()
if not options['port']:
options['port'] = 22
else:
options['port'] = int(options['port'])
host = options['host']
port = options['port']
vhk = default.verifyHostKey
uao = default.SSHUserAuthClient(options['user'], options, SSHConnection())
connect.connect(host, port, options, vhk, uao).addErrback(_ebExit)
def _ebExit(f):
global exitStatus
if hasattr(f.value, 'value'):
s = f.value.value
else:
s = str(f)
exitStatus = "conch: exiting with error %s" % f
reactor.callLater(0.1, _stopReactor)
def onConnect():
# if keyAgent and options['agent']:
# cc = protocol.ClientCreator(reactor, SSHAgentForwardingLocal, conn)
# cc.connectUNIX(os.environ['SSH_AUTH_SOCK'])
if hasattr(conn.transport, 'sendIgnore'):
_KeepAlive(conn)
if options.localForwards:
for localPort, hostport in options.localForwards:
s = reactor.listenTCP(localPort,
forwarding.SSHListenForwardingFactory(conn,
hostport,
SSHListenClientForwardingChannel))
conn.localForwards.append(s)
if options.remoteForwards:
for remotePort, hostport in options.remoteForwards:
log.msg('asking for remote forwarding for %s:%s' %
(remotePort, hostport))
conn.requestRemoteForwarding(remotePort, hostport)
reactor.addSystemEventTrigger('before', 'shutdown', beforeShutdown)
if not options['noshell'] or options['agent']:
conn.openChannel(SSHSession())
if options['fork']:
if os.fork():
os._exit(0)
os.setsid()
for i in range(3):
try:
os.close(i)
except OSError, e:
import errno
if e.errno != errno.EBADF:
raise
def reConnect():
beforeShutdown()
conn.transport.transport.loseConnection()
def beforeShutdown():
remoteForwards = options.remoteForwards
for remotePort, hostport in remoteForwards:
log.msg('cancelling %s:%s' % (remotePort, hostport))
conn.cancelRemoteForwarding(remotePort)
def stopConnection():
if not options['reconnect']:
reactor.callLater(0.1, _stopReactor)
class _KeepAlive:
def __init__(self, conn):
self.conn = conn
self.globalTimeout = None
self.lc = task.LoopingCall(self.sendGlobal)
self.lc.start(300)
def sendGlobal(self):
d = self.conn.sendGlobalRequest("[email protected]",
"", wantReply = 1)
d.addBoth(self._cbGlobal)
self.globalTimeout = reactor.callLater(30, self._ebGlobal)
def _cbGlobal(self, res):
if self.globalTimeout:
self.globalTimeout.cancel()
self.globalTimeout = None
def _ebGlobal(self):
if self.globalTimeout:
self.globalTimeout = None
self.conn.transport.loseConnection()
class SSHConnection(connection.SSHConnection):
def serviceStarted(self):
global conn
conn = self
self.localForwards = []
self.remoteForwards = {}
if not isinstance(self, connection.SSHConnection):
# make these fall through
del self.__class__.requestRemoteForwarding
del self.__class__.cancelRemoteForwarding
onConnect()
def serviceStopped(self):
lf = self.localForwards
self.localForwards = []
for s in lf:
s.loseConnection()
stopConnection()
def requestRemoteForwarding(self, remotePort, hostport):
data = forwarding.packGlobal_tcpip_forward(('0.0.0.0', remotePort))
d = self.sendGlobalRequest('tcpip-forward', data,
wantReply=1)
log.msg('requesting remote forwarding %s:%s' %(remotePort, hostport))
d.addCallback(self._cbRemoteForwarding, remotePort, hostport)
d.addErrback(self._ebRemoteForwarding, remotePort, hostport)
def _cbRemoteForwarding(self, result, remotePort, hostport):
log.msg('accepted remote forwarding %s:%s' % (remotePort, hostport))
self.remoteForwards[remotePort] = hostport
log.msg(repr(self.remoteForwards))
def _ebRemoteForwarding(self, f, remotePort, hostport):
log.msg('remote forwarding %s:%s failed' % (remotePort, hostport))
log.msg(f)
def cancelRemoteForwarding(self, remotePort):
data = forwarding.packGlobal_tcpip_forward(('0.0.0.0', remotePort))
self.sendGlobalRequest('cancel-tcpip-forward', data)
log.msg('cancelling remote forwarding %s' % remotePort)
try:
del self.remoteForwards[remotePort]
except:
pass
log.msg(repr(self.remoteForwards))
def channel_forwarded_tcpip(self, windowSize, maxPacket, data):
log.msg('%s %s' % ('FTCP', repr(data)))
remoteHP, origHP = forwarding.unpackOpen_forwarded_tcpip(data)
log.msg(self.remoteForwards)
log.msg(remoteHP)
if self.remoteForwards.has_key(remoteHP[1]):
connectHP = self.remoteForwards[remoteHP[1]]
log.msg('connect forwarding %s' % (connectHP,))
return SSHConnectForwardingChannel(connectHP,
remoteWindow = windowSize,
remoteMaxPacket = maxPacket,
conn = self)
else:
raise ConchError(connection.OPEN_CONNECT_FAILED, "don't know about that port")
# def channel_auth_agent_openssh_com(self, windowSize, maxPacket, data):
# if options['agent'] and keyAgent:
# return agent.SSHAgentForwardingChannel(remoteWindow = windowSize,
# remoteMaxPacket = maxPacket,
# conn = self)
# else:
# return connection.OPEN_CONNECT_FAILED, "don't have an agent"
def channelClosed(self, channel):
log.msg('connection closing %s' % channel)
log.msg(self.channels)
if len(self.channels) == 1 and not (options['noshell'] and not options['nocache']): # just us left
log.msg('stopping connection')
stopConnection()
else:
# because of the unix thing
self.__class__.__bases__[0].channelClosed(self, channel)
class SSHSession(channel.SSHChannel):
name = 'session'
def channelOpen(self, foo):
log.msg('session %s open' % self.id)
if options['agent']:
d = self.conn.sendRequest(self, '[email protected]', '', wantReply=1)
d.addBoth(lambda x:log.msg(x))
if options['noshell']: return
if (options['command'] and options['tty']) or not options['notty']:
_enterRawMode()
c = session.SSHSessionClient()
if options['escape'] and not options['notty']:
self.escapeMode = 1
c.dataReceived = self.handleInput
else:
c.dataReceived = self.write
c.connectionLost = lambda x=None,s=self:s.sendEOF()
self.stdio = stdio.StandardIO(c)
fd = 0
if options['subsystem']:
self.conn.sendRequest(self, 'subsystem', \
common.NS(options['command']))
elif options['command']:
if options['tty']:
term = os.environ['TERM']
winsz = fcntl.ioctl(fd, tty.TIOCGWINSZ, '12345678')
winSize = struct.unpack('4H', winsz)
ptyReqData = session.packRequest_pty_req(term, winSize, '')
self.conn.sendRequest(self, 'pty-req', ptyReqData)
signal.signal(signal.SIGWINCH, self._windowResized)
self.conn.sendRequest(self, 'exec', \
common.NS(options['command']))
else:
if not options['notty']:
term = os.environ['TERM']
winsz = fcntl.ioctl(fd, tty.TIOCGWINSZ, '12345678')
winSize = struct.unpack('4H', winsz)
ptyReqData = session.packRequest_pty_req(term, winSize, '')
self.conn.sendRequest(self, 'pty-req', ptyReqData)
signal.signal(signal.SIGWINCH, self._windowResized)
self.conn.sendRequest(self, 'shell', '')
#if hasattr(conn.transport, 'transport'):
# conn.transport.transport.setTcpNoDelay(1)
def handleInput(self, char):
#log.msg('handling %s' % repr(char))
if char in ('\n', '\r'):
self.escapeMode = 1
self.write(char)
elif self.escapeMode == 1 and char == options['escape']:
self.escapeMode = 2
elif self.escapeMode == 2:
self.escapeMode = 1 # so we can chain escapes together
if char == '.': # disconnect
log.msg('disconnecting from escape')
stopConnection()
return
elif char == '\x1a': # ^Z, suspend
def _():
_leaveRawMode()
sys.stdout.flush()
sys.stdin.flush()
os.kill(os.getpid(), signal.SIGTSTP)
_enterRawMode()
reactor.callLater(0, _)
return
elif char == 'R': # rekey connection
log.msg('rekeying connection')
self.conn.transport.sendKexInit()
return
elif char == '#': # display connections
self.stdio.write('\r\nThe following connections are open:\r\n')
channels = self.conn.channels.keys()
channels.sort()
for channelId in channels:
self.stdio.write(' #%i %s\r\n' % (channelId, str(self.conn.channels[channelId])))
return
self.write('~' + char)
else:
self.escapeMode = 0
self.write(char)
def dataReceived(self, data):
self.stdio.write(data)
def extReceived(self, t, data):
if t==connection.EXTENDED_DATA_STDERR:
log.msg('got %s stderr data' % len(data))
sys.stderr.write(data)
def eofReceived(self):
log.msg('got eof')
self.stdio.closeStdin()
def closeReceived(self):
log.msg('remote side closed %s' % self)
self.conn.sendClose(self)
def closed(self):
global old
log.msg('closed %s' % self)
log.msg(repr(self.conn.channels))
if not options['nocache']: # fork into the background
if os.fork():
if old:
fd = sys.stdin.fileno()
tty.tcsetattr(fd, tty.TCSANOW, old)
if (options['command'] and options['tty']) or \
not options['notty']:
signal.signal(signal.SIGWINCH, signal.SIG_DFL)
os._exit(0)
os.setsid()
for i in range(3):
try:
os.close(i)
except OSError, e:
import errno
if e.errno != errno.EBADF:
raise
def request_exit_status(self, data):
global exitStatus
exitStatus = int(struct.unpack('>L', data)[0])
log.msg('exit status: %s' % exitStatus)
def sendEOF(self):
self.conn.sendEOF(self)
def stopWriting(self):
self.stdio.pauseProducing()
def startWriting(self):
self.stdio.resumeProducing()
def _windowResized(self, *args):
winsz = fcntl.ioctl(0, tty.TIOCGWINSZ, '12345678')
winSize = struct.unpack('4H', winsz)
newSize = winSize[1], winSize[0], winSize[2], winSize[3]
self.conn.sendRequest(self, 'window-change', struct.pack('!4L', *newSize))
class SSHListenClientForwardingChannel(forwarding.SSHListenClientForwardingChannel): pass
class SSHConnectForwardingChannel(forwarding.SSHConnectForwardingChannel): pass
def _leaveRawMode():
global _inRawMode
if not _inRawMode:
return
fd = sys.stdin.fileno()
tty.tcsetattr(fd, tty.TCSANOW, _savedMode)
_inRawMode = 0
def _enterRawMode():
global _inRawMode, _savedMode
if _inRawMode:
return
fd = sys.stdin.fileno()
try:
old = tty.tcgetattr(fd)
new = old[:]
except:
log.msg('not a typewriter!')
else:
# iflage
new[0] = new[0] | tty.IGNPAR
new[0] = new[0] & ~(tty.ISTRIP | tty.INLCR | tty.IGNCR | tty.ICRNL |
tty.IXON | tty.IXANY | tty.IXOFF)
if hasattr(tty, 'IUCLC'):
new[0] = new[0] & ~tty.IUCLC
# lflag
new[3] = new[3] & ~(tty.ISIG | tty.ICANON | tty.ECHO | tty.ECHO |
tty.ECHOE | tty.ECHOK | tty.ECHONL)
if hasattr(tty, 'IEXTEN'):
new[3] = new[3] & ~tty.IEXTEN
#oflag
new[1] = new[1] & ~tty.OPOST
new[6][tty.VMIN] = 1
new[6][tty.VTIME] = 0
_savedMode = old
tty.tcsetattr(fd, tty.TCSANOW, new)
#tty.setraw(fd)
_inRawMode = 1
if __name__ == '__main__':
run() | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/scripts/conch.py | conch.py |
#
# $Id: ckeygen.py,v 1.8 2003/05/10 14:03:40 spiv Exp $
#""" Implementation module for the `ckeygen` command.
#"""
from twisted.conch.ssh import keys, common
from twisted.python import log, usage
import sys, os, getpass, md5, socket
if getpass.getpass == getpass.unix_getpass:
try:
import termios # hack around broken termios
termios.tcgetattr, termios.tcsetattr
except (ImportError, AttributeError):
sys.modules['termios'] = None
reload(getpass)
class GeneralOptions(usage.Options):
synopsis = """Usage: ckeygen [options]
"""
optParameters = [['bits', 'b', 1024, 'Number of bits in the key to create.'],
['filename', 'f', None, 'Filename of the key file.'],
['type', 't', None, 'Specify type of key to create.'],
['comment', 'C', None, 'Provide new comment.'],
['newpass', 'N', None, 'Provide new passphrase.'],
['pass', 'P', None, 'Provide old passphrase']]
optFlags = [['fingerprint', 'l', 'Show fingerprint of key file.'],
['changepass', 'p', 'Change passphrase of private key file.'],
['quiet', 'q', 'Quiet.'],
['showpub', 'y', 'Read private key file and print public key.']]
#zsh_altArgDescr = {"bits":"Number of bits in the key (default: 1024)"}
#zsh_multiUse = ["foo", "bar"]
#zsh_mutuallyExclusive = [("foo", "bar"), ("bar", "baz")]
zsh_actions = {"type":"(rsa dsa)"}
#zsh_actionDescr = {"logfile":"log file name", "random":"random seed"}
def run():
options = GeneralOptions()
try:
options.parseOptions(sys.argv[1:])
except usage.UsageError, u:
print 'ERROR: %s' % u
options.opt_help()
sys.exit(1)
log.discardLogs()
log.deferr = handleError # HACK
if options['type']:
if options['type'] == 'rsa':
generateRSAkey(options)
elif options['type'] == 'dsa':
generateDSAkey(options)
else:
sys.exit('Key type was %s, must be one of: rsa, dsa' % options['type'])
elif options['fingerprint']:
printFingerprint(options)
elif options['changepass']:
changePassPhrase(options)
elif options['showpub']:
displayPublicKey(options)
else:
options.opt_help()
sys.exit(1)
def handleError():
from twisted.python import failure
global exitStatus
exitStatus = 2
log.err(failure.Failure())
reactor.stop()
raise
def generateRSAkey(options):
from Crypto.PublicKey import RSA
print 'Generating public/private rsa key pair.'
key = RSA.generate(int(options['bits']), common.entropy.get_bytes)
_saveKey(key, options)
def generateDSAkey(options):
from Crypto.PublicKey import DSA
print 'Generating public/private dsa key pair.'
key = DSA.generate(int(options['bits']), common.entropy.get_bytes)
_saveKey(key, options)
def printFingerprint(options):
if not options['filename']:
filename = os.path.expanduser('~/.ssh/id_rsa')
options['filename'] = raw_input('Enter file in which the key is (%s): ' % filename)
if os.path.exists(options['filename']+'.pub'):
options['filename'] += '.pub'
try:
string = keys.getPublicKeyString(options['filename'])
obj = keys.getPublicKeyObject(string)
print '%s %s %s' % (
obj.size()+1,
':'.join(['%02x' % ord(x) for x in md5.new(string).digest()]),
os.path.basename(options['filename']))
except:
sys.exit('bad key')
def changePassPhrase(options):
if not options['filename']:
filename = os.path.expanduser('~/.ssh/id_rsa')
options['filename'] = raw_input('Enter file in which the key is (%s): ' % filename)
try:
key = keys.getPrivateKeyObject(options['filename'])
except keys.BadKeyError, e:
if e.args[0] != 'encrypted key with no passphrase':
raise
else:
if not options['pass']:
options['pass'] = getpass.getpass('Enter old passphrase: ')
key = keys.getPrivateKeyObject(options['filename'], passphrase = options['pass'])
if not options['newpass']:
while 1:
p1 = getpass.getpass('Enter new passphrase (empty for no passphrase): ')
p2 = getpass.getpass('Enter same passphrase again: ')
if p1 == p2:
break
print 'Passphrases do not match. Try again.'
options['newpass'] = p1
open(options['filename'], 'w').write(
keys.makePrivateKeyString(key, passphrase=options['newpass']))
print 'Your identification has been saved with the new passphrase.'
def displayPublicKey(options):
if not options['filename']:
filename = os.path.expanduser('~/.ssh/id_rsa')
options['filename'] = raw_input('Enter file in which the key is (%s): ' % filename)
try:
key = keys.getPrivateKeyObject(options['filename'])
except keys.BadKeyError, e:
if e.args[0] != 'encrypted key with no passphrase':
raise
else:
if not options['pass']:
options['pass'] = getpass.getpass('Enter passphrase: ')
key = keys.getPrivateKeyObject(options['filename'], passphrase = options['pass'])
print keys.makePublicKeyString(key)
def _saveKey(key, options):
if not options['filename']:
kind = keys.objectType(key)
kind = {'ssh-rsa':'rsa','ssh-dss':'dsa'}[kind]
filename = os.path.expanduser('~/.ssh/id_%s'%kind)
options['filename'] = raw_input('Enter file in which to save the key (%s): '%filename).strip() or filename
if os.path.exists(options['filename']):
print '%s already exists.' % options['filename']
yn = raw_input('Overwrite (y/n)? ')
if yn[0].lower() != 'y':
sys.exit()
if not options['pass']:
while 1:
p1 = getpass.getpass('Enter passphrase (empty for no passphrase): ')
p2 = getpass.getpass('Enter same passphrase again: ')
if p1 == p2:
break
print 'Passphrases do not match. Try again.'
options['pass'] = p1
comment = '%s@%s' % (getpass.getuser(), socket.gethostname())
open(options['filename'], 'w').write(
keys.makePrivateKeyString(key, passphrase=options['pass']))
os.chmod(options['filename'], 33152)
open(options['filename']+'.pub', 'w').write(
keys.makePublicKeyString(key, comment = comment))
pubKey = keys.getPublicKeyString(data=keys.makePublicKeyString(key, comment=comment))
print 'Your identification has been saved in %s' % options['filename']
print 'Your public key has been saved in %s.pub' % options['filename']
print 'The key fingerprint is:'
print ':'.join(['%02x' % ord(x) for x in md5.new(pubKey).digest()])
if __name__ == '__main__':
run() | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/scripts/ckeygen.py | ckeygen.py |
#
# $Id: tkconch.py,v 1.6 2003/02/22 08:10:15 z3p Exp $
""" Implementation module for the `tkconch` command.
"""
from __future__ import nested_scopes
import Tkinter, tkFileDialog, tkFont, tkMessageBox, string
from twisted.conch.ui import tkvt100
from twisted.conch.ssh import transport, userauth, connection, common, keys
from twisted.conch.ssh import session, forwarding, channel
from twisted.conch.client.default import isInKnownHosts
from twisted.internet import reactor, defer, protocol, tksupport
from twisted.python import usage, log
import os, sys, getpass, struct, base64, signal
class TkConchMenu(Tkinter.Frame):
def __init__(self, *args, **params):
## Standard heading: initialization
apply(Tkinter.Frame.__init__, (self,) + args, params)
self.master.title('TkConch')
self.localRemoteVar = Tkinter.StringVar()
self.localRemoteVar.set('local')
Tkinter.Label(self, anchor='w', justify='left', text='Hostname').grid(column=1, row=1, sticky='w')
self.host = Tkinter.Entry(self)
self.host.grid(column=2, columnspan=2, row=1, sticky='nesw')
Tkinter.Label(self, anchor='w', justify='left', text='Port').grid(column=1, row=2, sticky='w')
self.port = Tkinter.Entry(self)
self.port.grid(column=2, columnspan=2, row=2, sticky='nesw')
Tkinter.Label(self, anchor='w', justify='left', text='Username').grid(column=1, row=3, sticky='w')
self.user = Tkinter.Entry(self)
self.user.grid(column=2, columnspan=2, row=3, sticky='nesw')
Tkinter.Label(self, anchor='w', justify='left', text='Command').grid(column=1, row=4, sticky='w')
self.command = Tkinter.Entry(self)
self.command.grid(column=2, columnspan=2, row=4, sticky='nesw')
Tkinter.Label(self, anchor='w', justify='left', text='Identity').grid(column=1, row=5, sticky='w')
self.identity = Tkinter.Entry(self)
self.identity.grid(column=2, row=5, sticky='nesw')
Tkinter.Button(self, command=self.getIdentityFile, text='Browse').grid(column=3, row=5, sticky='nesw')
Tkinter.Label(self, text='Port Forwarding').grid(column=1, row=6, sticky='w')
self.forwards = Tkinter.Listbox(self, height=0, width=0)
self.forwards.grid(column=2, columnspan=2, row=6, sticky='nesw')
Tkinter.Button(self, text='Add', command=self.addForward).grid(column=1, row=7)
Tkinter.Button(self, text='Remove', command=self.removeForward).grid(column=1, row=8)
self.forwardPort = Tkinter.Entry(self)
self.forwardPort.grid(column=2, row=7, sticky='nesw')
Tkinter.Label(self, text='Port').grid(column=3, row=7, sticky='nesw')
self.forwardHost = Tkinter.Entry(self)
self.forwardHost.grid(column=2, row=8, sticky='nesw')
Tkinter.Label(self, text='Host').grid(column=3, row=8, sticky='nesw')
self.localForward = Tkinter.Radiobutton(self, text='Local', variable=self.localRemoteVar, value='local')
self.localForward.grid(column=2, row=9)
self.remoteForward = Tkinter.Radiobutton(self, text='Remote', variable=self.localRemoteVar, value='remote')
self.remoteForward.grid(column=3, row=9)
Tkinter.Label(self, text='Advanced Options').grid(column=1, columnspan=3, row=10, sticky='nesw')
Tkinter.Label(self, anchor='w', justify='left', text='Cipher').grid(column=1, row=11, sticky='w')
self.cipher = Tkinter.Entry(self, name='cipher')
self.cipher.grid(column=2, columnspan=2, row=11, sticky='nesw')
Tkinter.Label(self, anchor='w', justify='left', text='MAC').grid(column=1, row=12, sticky='w')
self.mac = Tkinter.Entry(self, name='mac')
self.mac.grid(column=2, columnspan=2, row=12, sticky='nesw')
Tkinter.Label(self, anchor='w', justify='left', text='Escape Char').grid(column=1, row=13, sticky='w')
self.escape = Tkinter.Entry(self, name='escape')
self.escape.grid(column=2, columnspan=2, row=13, sticky='nesw')
Tkinter.Button(self, text='Connect!', command=self.doConnect).grid(column=1, columnspan=3, row=14, sticky='nesw')
# Resize behavior(s)
self.grid_rowconfigure(6, weight=1, minsize=64)
self.grid_columnconfigure(2, weight=1, minsize=2)
self.master.protocol("WM_DELETE_WINDOW", sys.exit)
def getIdentityFile(self):
r = tkFileDialog.askopenfilename()
if r:
self.identity.delete(0, Tkinter.END)
self.identity.insert(Tkinter.END, r)
def addForward(self):
port = self.forwardPort.get()
self.forwardPort.delete(0, Tkinter.END)
host = self.forwardHost.get()
self.forwardHost.delete(0, Tkinter.END)
if self.localRemoteVar.get() == 'local':
self.forwards.insert(Tkinter.END, 'L:%s:%s' % (port, host))
else:
self.forwards.insert(Tkinter.END, 'R:%s:%s' % (port, host))
def removeForward(self):
cur = self.forwards.curselection()
if cur:
self.forwards.remove(cur[0])
def doConnect(self):
finished = 1
options['host'] = self.host.get()
options['port'] = self.port.get()
options['user'] = self.user.get()
options['command'] = self.command.get()
cipher = self.cipher.get()
mac = self.mac.get()
escape = self.escape.get()
if cipher:
if cipher in SSHClientTransport.supportedCiphers:
SSHClientTransport.supportedCiphers = [cipher]
else:
tkMessageBox.showerror('TkConch', 'Bad cipher.')
finished = 0
if mac:
if mac in SSHClientTransport.supportedMACs:
SSHClientTransport.supportedMACs = [mac]
elif finished:
tkMessageBox.showerror('TkConch', 'Bad MAC.')
finished = 0
if escape:
if escape == 'none':
options['escape'] = None
elif escape[0] == '^' and len(escape) == 2:
options['escape'] = chr(ord(escape[1])-64)
elif len(escape) == 1:
options['escape'] = escape
elif finished:
tkMessageBox.showerror('TkConch', "Bad escape character '%s'." % escape)
finished = 0
if self.identity.get():
options.identitys.append(self.identity.get())
for line in self.forwards.get(0,Tkinter.END):
if line[0]=='L':
options.opt_localforward(line[2:])
else:
options.opt_remoteforward(line[2:])
if '@' in options['host']:
options['user'], options['host'] = options['host'].split('@',1)
if (not options['host'] or not options['user']) and finished:
tkMessageBox.showerror('TkConch', 'Missing host or username.')
finished = 0
if finished:
self.master.quit()
self.master.destroy()
if options['log']:
realout = sys.stdout
log.startLogging(sys.stderr)
sys.stdout = realout
else:
log.discardLogs()
log.deferr = handleError # HACK
if not options.identitys:
options.identitys = ['~/.ssh/id_rsa', '~/.ssh/id_dsa']
host = options['host']
port = int(options['port'] or 22)
log.msg((host,port))
reactor.connectTCP(host, port, SSHClientFactory())
frame.master.deiconify()
frame.master.title('%s@%s - TkConch' % (options['user'], options['host']))
else:
self.focus()
class GeneralOptions(usage.Options):
synopsis = """Usage: tkconch [options] host [command]
"""
optParameters = [['user', 'l', None, 'Log in using this user name.'],
['identity', 'i', '~/.ssh/identity', 'Identity for public key authentication'],
['escape', 'e', '~', "Set escape character; ``none'' = disable"],
['cipher', 'c', None, 'Select encryption algorithm.'],
['macs', 'm', None, 'Specify MAC algorithms for protocol version 2.'],
['port', 'p', None, 'Connect to this port. Server must be on the same port.'],
['localforward', 'L', None, 'listen-port:host:port Forward local port to remote address'],
['remoteforward', 'R', None, 'listen-port:host:port Forward remote port to local address'],
]
optFlags = [['tty', 't', 'Tty; allocate a tty even if command is given.'],
['notty', 'T', 'Do not allocate a tty.'],
['version', 'V', 'Display version number only.'],
['compress', 'C', 'Enable compression.'],
['noshell', 'N', 'Do not execute a shell or command.'],
['subsystem', 's', 'Invoke command (mandatory) as SSH2 subsystem.'],
['log', 'v', 'Log to stderr'],
['ansilog', 'a', 'Print the receieved data to stdout']]
#zsh_altArgDescr = {"foo":"use this description for foo instead"}
#zsh_multiUse = ["foo", "bar"]
zsh_mutuallyExclusive = [("tty", "notty")]
zsh_actions = {"cipher":"(%s)" % " ".join(transport.SSHClientTransport.supportedCiphers),
"macs":"(%s)" % " ".join(transport.SSHClientTransport.supportedMACs)}
zsh_actionDescr = {"localforward":"listen-port:host:port",
"remoteforward":"listen-port:host:port"}
# user, host, or user@host completion similar to zsh's ssh completion
zsh_extras = ['1:host | user@host:{_ssh;if compset -P "*@"; then _wanted hosts expl "remote host name" _ssh_hosts && ret=0 elif compset -S "@*"; then _wanted users expl "login name" _ssh_users -S "" && ret=0 else if (( $+opt_args[-l] )); then tmp=() else tmp=( "users:login name:_ssh_users -qS@" ) fi; _alternative "hosts:remote host name:_ssh_hosts" "$tmp[@]" && ret=0 fi}',
'*:command: ']
identitys = []
localForwards = []
remoteForwards = []
def opt_identity(self, i):
self.identitys.append(i)
def opt_localforward(self, f):
localPort, remoteHost, remotePort = f.split(':') # doesn't do v6 yet
localPort = int(localPort)
remotePort = int(remotePort)
self.localForwards.append((localPort, (remoteHost, remotePort)))
def opt_remoteforward(self, f):
remotePort, connHost, connPort = f.split(':') # doesn't do v6 yet
remotePort = int(remotePort)
connPort = int(connPort)
self.remoteForwards.append((remotePort, (connHost, connPort)))
def opt_compress(self):
SSHClientTransport.supportedCompressions[0:1] = ['zlib']
def parseArgs(self, *args):
if args:
self['host'] = args[0]
self['command'] = ' '.join(args[1:])
else:
self['host'] = ''
self['command'] = ''
# Rest of code in "run"
options = None
menu = None
exitStatus = 0
frame = None
def deferredAskFrame(question, echo):
if frame.callback:
raise "can't ask 2 questions at once!"
d = defer.Deferred()
resp = []
def gotChar(ch, resp=resp):
if not ch: return
if ch=='\x03': # C-c
reactor.stop()
if ch=='\r':
frame.write('\r\n')
stresp = ''.join(resp)
del resp
frame.callback = None
d.callback(stresp)
return
elif 32 <= ord(ch) < 127:
resp.append(ch)
if echo:
frame.write(ch)
elif ord(ch) == 8 and resp: # BS
if echo: frame.write('\x08 \x08')
resp.pop()
frame.callback = gotChar
frame.write(question)
frame.canvas.focus_force()
return d
def run():
global menu, options, frame
args = sys.argv[1:]
if '-l' in args: # cvs is an idiot
i = args.index('-l')
args = args[i:i+2]+args
del args[i+2:i+4]
for arg in args[:]:
try:
i = args.index(arg)
if arg[:2] == '-o' and args[i+1][0]!='-':
args[i:i+2] = [] # suck on it scp
except ValueError:
pass
root = Tkinter.Tk()
root.withdraw()
top = Tkinter.Toplevel()
menu = TkConchMenu(top)
menu.pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=1)
options = GeneralOptions()
try:
options.parseOptions(args)
except usage.UsageError, u:
print 'ERROR: %s' % u
options.opt_help()
sys.exit(1)
for k,v in options.items():
if v and hasattr(menu, k):
getattr(menu,k).insert(Tkinter.END, v)
for (p, (rh, rp)) in options.localForwards:
menu.forwards.insert(Tkinter.END, 'L:%s:%s:%s' % (p, rh, rp))
options.localForwards = []
for (p, (rh, rp)) in options.remoteForwards:
menu.forwards.insert(Tkinter.END, 'R:%s:%s:%s' % (p, rh, rp))
options.remoteForwards = []
frame = tkvt100.VT100Frame(root, callback=None)
root.geometry('%dx%d'%(tkvt100.fontWidth*frame.width+3, tkvt100.fontHeight*frame.height+3))
frame.pack(side = Tkinter.TOP)
tksupport.install(root)
root.withdraw()
if (options['host'] and options['user']) or '@' in options['host']:
menu.doConnect()
else:
top.mainloop()
reactor.run()
sys.exit(exitStatus)
def handleError():
from twisted.python import failure
global exitStatus
exitStatus = 2
log.err(failure.Failure())
reactor.stop()
raise
class SSHClientFactory(protocol.ClientFactory):
noisy = 1
def stopFactory(self):
reactor.stop()
def buildProtocol(self, addr):
return SSHClientTransport()
def clientConnectionFailed(self, connector, reason):
tkMessageBox.showwarning('TkConch','Connection Failed, Reason:\n %s: %s' % (reason.type, reason.value))
class SSHClientTransport(transport.SSHClientTransport):
def receiveError(self, code, desc):
global exitStatus
exitStatus = 'conch:\tRemote side disconnected with error code %i\nconch:\treason: %s' % (code, desc)
def sendDisconnect(self, code, reason):
global exitStatus
exitStatus = 'conch:\tSending disconnect with error code %i\nconch:\treason: %s' % (code, reason)
transport.SSHClientTransport.sendDisconnect(self, code, reason)
def receiveDebug(self, alwaysDisplay, message, lang):
global options
if alwaysDisplay or options['log']:
log.msg('Received Debug Message: %s' % message)
def verifyHostKey(self, pubKey, fingerprint):
#d = defer.Deferred()
#d.addCallback(lambda x:defer.succeed(1))
#d.callback(2)
#return d
goodKey = isInKnownHosts(options['host'], pubKey, {'known-hosts': None})
if goodKey == 1: # good key
return defer.succeed(1)
elif goodKey == 2: # AAHHHHH changed
return defer.fail(error.ConchError('bad host key'))
else:
if options['host'] == self.transport.getPeer()[1]:
host = options['host']
khHost = options['host']
else:
host = '%s (%s)' % (options['host'],
self.transport.getPeer()[1])
khHost = '%s,%s' % (options['host'],
self.transport.getPeer()[1])
keyType = common.getNS(pubKey)[0]
ques = """The authenticity of host '%s' can't be established.\r
%s key fingerprint is %s.""" % (host,
{'ssh-dss':'DSA', 'ssh-rsa':'RSA'}[keyType],
fingerprint)
ques+='\r\nAre you sure you want to continue connecting (yes/no)? '
return deferredAskFrame(ques, 1).addCallback(self._cbVerifyHostKey, pubKey, khHost, keyType)
def _cbVerifyHostKey(self, ans, pubKey, khHost, keyType):
if ans.lower() not in ('yes', 'no'):
return deferredAskFrame("Please type 'yes' or 'no': ",1).addCallback(self._cbVerifyHostKey, pubKey, khHost, keyType)
if ans.lower() == 'no':
frame.write('Host key verification failed.\r\n')
raise error.ConchError('bad host key')
try:
frame.write("Warning: Permanently added '%s' (%s) to the list of known hosts.\r\n" % (khHost, {'ssh-dss':'DSA', 'ssh-rsa':'RSA'}[keyType]))
known_hosts = open(os.path.expanduser('~/.ssh/known_hosts'), 'a')
encodedKey = base64.encodestring(pubKey).replace('\n', '')
known_hosts.write('\n%s %s %s' % (khHost, keyType, encodedKey))
known_hosts.close()
except:
log.deferr()
raise error.ConchError
def connectionSecure(self):
if options['user']:
user = options['user']
else:
user = getpass.getuser()
self.requestService(SSHUserAuthClient(user, SSHConnection()))
class SSHUserAuthClient(userauth.SSHUserAuthClient):
usedFiles = []
def getPassword(self, prompt = None):
if not prompt:
prompt = "%s@%s's password: " % (self.user, options['host'])
return deferredAskFrame(prompt,0)
def getPublicKey(self):
files = [x for x in options.identitys if x not in self.usedFiles]
if not files:
return None
file = files[0]
log.msg(file)
self.usedFiles.append(file)
file = os.path.expanduser(file)
file += '.pub'
if not os.path.exists(file):
return
try:
return keys.getPublicKeyString(file)
except:
return self.getPublicKey() # try again
def getPrivateKey(self):
file = os.path.expanduser(self.usedFiles[-1])
if not os.path.exists(file):
return None
try:
return defer.succeed(keys.getPrivateKeyObject(file))
except keys.BadKeyError, e:
if e.args[0] == 'encrypted key with no password':
prompt = "Enter passphrase for key '%s': " % \
self.usedFiles[-1]
return deferredAskFrame(prompt, 0).addCallback(self._cbGetPrivateKey, 0)
def _cbGetPrivateKey(self, ans, count):
file = os.path.expanduser(self.usedFiles[-1])
try:
return keys.getPrivateKeyObject(file, password = ans)
except keys.BadKeyError:
if count == 2:
raise
prompt = "Enter passphrase for key '%s': " % \
self.usedFiles[-1]
return deferredAskFrame(prompt, 0).addCallback(self._cbGetPrivateKey, count+1)
class SSHConnection(connection.SSHConnection):
def serviceStarted(self):
if not options['noshell']:
self.openChannel(SSHSession())
if options.localForwards:
for localPort, hostport in options.localForwards:
reactor.listenTCP(localPort,
forwarding.SSHListenForwardingFactory(self,
hostport,
forwarding.SSHListenClientForwardingChannel))
if options.remoteForwards:
for remotePort, hostport in options.remoteForwards:
log.msg('asking for remote forwarding for %s:%s' %
(remotePort, hostport))
data = forwarding.packGlobal_tcpip_forward(
('0.0.0.0', remotePort))
d = self.sendGlobalRequest('tcpip-forward', data)
self.remoteForwards[remotePort] = hostport
class SSHSession(channel.SSHChannel):
name = 'session'
def channelOpen(self, foo):
#global globalSession
#globalSession = self
# turn off local echo
self.escapeMode = 1
c = session.SSHSessionClient()
if options['escape']:
c.dataReceived = self.handleInput
else:
c.dataReceived = self.write
c.connectionLost = self.sendEOF
frame.callback = c.dataReceived
frame.canvas.focus_force()
if options['subsystem']:
self.conn.sendRequest(self, 'subsystem', \
common.NS(options['command']))
elif options['command']:
if options['tty']:
term = os.environ.get('TERM', 'xterm')
#winsz = fcntl.ioctl(fd, tty.TIOCGWINSZ, '12345678')
winSize = (25,80,0,0) #struct.unpack('4H', winsz)
ptyReqData = session.packRequest_pty_req(term, winSize, '')
self.conn.sendRequest(self, 'pty-req', ptyReqData)
self.conn.sendRequest(self, 'exec', \
common.NS(options['command']))
else:
if not options['notty']:
term = os.environ.get('TERM', 'xterm')
#winsz = fcntl.ioctl(fd, tty.TIOCGWINSZ, '12345678')
winSize = (25,80,0,0) #struct.unpack('4H', winsz)
ptyReqData = session.packRequest_pty_req(term, winSize, '')
self.conn.sendRequest(self, 'pty-req', ptyReqData)
self.conn.sendRequest(self, 'shell', '')
self.conn.transport.transport.setTcpNoDelay(1)
def handleInput(self, char):
#log.msg('handling %s' % repr(char))
if char in ('\n', '\r'):
self.escapeMode = 1
self.write(char)
elif self.escapeMode == 1 and char == options['escape']:
self.escapeMode = 2
elif self.escapeMode == 2:
self.escapeMode = 1 # so we can chain escapes together
if char == '.': # disconnect
log.msg('disconnecting from escape')
reactor.stop()
return
elif char == '\x1a': # ^Z, suspend
# following line courtesy of Erwin@freenode
os.kill(os.getpid(), signal.SIGSTOP)
return
elif char == 'R': # rekey connection
log.msg('rekeying connection')
self.conn.transport.sendKexInit()
return
self.write('~' + char)
else:
self.escapeMode = 0
self.write(char)
def dataReceived(self, data):
if options['ansilog']:
print repr(data)
frame.write(data)
def extReceived(self, t, data):
if t==connection.EXTENDED_DATA_STDERR:
log.msg('got %s stderr data' % len(data))
sys.stderr.write(data)
sys.stderr.flush()
def eofReceived(self):
log.msg('got eof')
sys.stdin.close()
def closed(self):
log.msg('closed %s' % self)
if len(self.conn.channels) == 1: # just us left
reactor.stop()
def request_exit_status(self, data):
global exitStatus
exitStatus = int(struct.unpack('>L', data)[0])
log.msg('exit status: %s' % exitStatus)
def sendEOF(self):
self.conn.sendEOF(self)
if __name__=="__main__":
run() | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/scripts/tkconch.py | tkconch.py |
#
# $Id: cftp.py,v 1.65 2004/03/11 00:29:14 z3p Exp $
#""" Implementation module for the `cftp` command.
#"""
from twisted.conch.client import agent, connect, default, options
from twisted.conch.error import ConchError
from twisted.conch.ssh import connection, common
from twisted.conch.ssh import channel, filetransfer
from twisted.protocols import basic
from twisted.internet import reactor, stdio, defer, utils
from twisted.python import log, usage, failure
import os, sys, getpass, struct, tty, fcntl, base64, signal, stat, errno
import fnmatch, pwd, time, glob
class ClientOptions(options.ConchOptions):
synopsis = """Usage: cftp [options] [user@]host
cftp [options] [user@]host[:dir[/]]
cftp [options] [user@]host[:file [localfile]]
"""
optParameters = [
['buffersize', 'B', 32768, 'Size of the buffer to use for sending/receiving.'],
['batchfile', 'b', None, 'File to read commands from, or \'-\' for stdin.'],
['requests', 'R', 5, 'Number of requests to make before waiting for a reply.'],
['subsystem', 's', 'sftp', 'Subsystem/server program to connect to.']]
zsh_altArgDescr = {"buffersize":"Size of send/receive buffer (default: 32768)"}
#zsh_multiUse = ["foo", "bar"]
#zsh_mutuallyExclusive = [("foo", "bar"), ("bar", "baz")]
#zsh_actions = {"foo":'_files -g "*.foo"', "bar":"(one two three)"}
#zsh_actionDescr = {"logfile":"log file name", "random":"random seed"}
zsh_extras = ['2::localfile:{if [[ $words[1] == *:* ]]; then; _files; fi}']
def parseArgs(self, host, localPath=None):
self['remotePath'] = ''
if ':' in host:
host, self['remotePath'] = host.split(':', 1)
self['remotePath'].rstrip('/')
self['host'] = host
self['localPath'] = localPath
def run():
# import hotshot
# prof = hotshot.Profile('cftp.prof')
# prof.start()
args = sys.argv[1:]
if '-l' in args: # cvs is an idiot
i = args.index('-l')
args = args[i:i+2]+args
del args[i+2:i+4]
options = ClientOptions()
try:
options.parseOptions(args)
except usage.UsageError, u:
print 'ERROR: %s' % u
sys.exit(1)
if options['log']:
realout = sys.stdout
log.startLogging(sys.stderr)
sys.stdout = realout
else:
log.discardLogs()
doConnect(options)
reactor.run()
# prof.stop()
# prof.close()
def handleError():
from twisted.python import failure
global exitStatus
exitStatus = 2
try:
reactor.stop()
except: pass
log.err(failure.Failure())
raise
def doConnect(options):
# log.deferr = handleError # HACK
if '@' in options['host']:
options['user'], options['host'] = options['host'].split('@',1)
host = options['host']
if not options['user']:
options['user'] = getpass.getuser()
if not options['port']:
options['port'] = 22
else:
options['port'] = int(options['port'])
host = options['host']
port = options['port']
conn = SSHConnection()
conn.options = options
vhk = default.verifyHostKey
uao = default.SSHUserAuthClient(options['user'], options, conn)
connect.connect(host, port, options, vhk, uao).addErrback(_ebExit)
def _ebExit(f):
#global exitStatus
if hasattr(f.value, 'value'):
s = f.value.value
else:
s = str(f)
print s
#exitStatus = "conch: exiting with error %s" % f
try:
reactor.stop()
except: pass
def _ignore(*args): pass
class FileWrapper:
def __init__(self, f):
self.f = f
self.total = 0.0
f.seek(0, 2) # seek to the end
self.size = f.tell()
def __getattr__(self, attr):
return getattr(self.f, attr)
class StdioClient(basic.LineReceiver):
ps = 'cftp> '
delimiter = '\n'
def __init__(self, client, f = None):
self.client = client
self.currentDirectory = ''
self.file = f
self.useProgressBar = (not f and 1) or 0
def connectionMade(self):
self.client.realPath('').addCallback(self._cbSetCurDir)
def _cbSetCurDir(self, path):
self.currentDirectory = path
self._newLine()
def lineReceived(self, line):
if self.client.transport.localClosed:
return
log.msg('got line %s' % repr(line))
line = line.lstrip()
if not line:
self._newLine()
return
if self.file and line.startswith('-'):
self.ignoreErrors = 1
line = line[1:]
else:
self.ignoreErrors = 0
if ' ' in line:
command, rest = line.split(' ', 1)
rest = rest.lstrip()
else:
command, rest = line, ''
if command.startswith('!'): # command
f = self.cmd_EXEC
rest = (command[1:] + ' ' + rest).strip()
else:
command = command.upper()
log.msg('looking up cmd %s' % command)
f = getattr(self, 'cmd_%s' % command, None)
if f is not None:
d = defer.maybeDeferred(f, rest)
d.addCallback(self._cbCommand)
d.addErrback(self._ebCommand)
else:
self._ebCommand(failure.Failure(NotImplementedError(
"No command called `%s'" % command)))
self._newLine()
def _printFailure(self, f):
log.msg(f)
e = f.trap(NotImplementedError, filetransfer.SFTPError, OSError, IOError)
if e == NotImplementedError:
self.transport.write(self.cmd_HELP(''))
elif e == filetransfer.SFTPError:
self.transport.write("remote error %i: %s\n" %
(f.value.code, f.value.message))
elif e in (OSError, IOError):
self.transport.write("local error %i: %s\n" %
(f.value.errno, f.value.strerror))
def _newLine(self):
if self.client.transport.localClosed:
return
self.transport.write(self.ps)
self.ignoreErrors = 0
if self.file:
l = self.file.readline()
if not l:
self.client.transport.loseConnection()
else:
self.transport.write(l)
self.lineReceived(l.strip())
def _cbCommand(self, result):
if result is not None:
self.transport.write(result)
if not result.endswith('\n'):
self.transport.write('\n')
self._newLine()
def _ebCommand(self, f):
self._printFailure(f)
if self.file and not self.ignoreErrors:
self.client.transport.loseConnection()
self._newLine()
def cmd_CD(self, path):
path, rest = self._getFilename(path)
if not path.endswith('/'):
path += '/'
newPath = path and os.path.join(self.currentDirectory, path) or ''
d = self.client.openDirectory(newPath)
d.addCallback(self._cbCd)
d.addErrback(self._ebCommand)
return d
def _cbCd(self, directory):
directory.close()
d = self.client.realPath(directory.name)
d.addCallback(self._cbCurDir)
return d
def _cbCurDir(self, path):
self.currentDirectory = path
def cmd_CHGRP(self, rest):
grp, rest = rest.split(None, 1)
path, rest = self._getFilename(rest)
grp = int(grp)
d = self.client.getAttrs(path)
d.addCallback(self._cbSetUsrGrp, path, grp=grp)
return d
def cmd_CHMOD(self, rest):
mod, rest = rest.split(None, 1)
path, rest = self._getFilename(rest)
mod = int(mod, 8)
d = self.client.setAttrs(path, {'permissions':mod})
d.addCallback(_ignore)
return d
def cmd_CHOWN(self, rest):
usr, rest = rest.split(None, 1)
path, rest = self._getFilename(rest)
usr = int(usr)
d = self.client.getAttrs(path)
d.addCallback(self._cbSetUsrGrp, path, usr=usr)
return d
def _cbSetUsrGrp(self, attrs, path, usr=None, grp=None):
new = {}
new['uid'] = (usr is not None) and usr or attrs['uid']
new['gid'] = (grp is not None) and grp or attrs['gid']
d = self.client.setAttrs(path, new)
d.addCallback(_ignore)
return d
def cmd_GET(self, rest):
remote, rest = self._getFilename(rest)
if '*' in remote or '?' in remote: # wildcard
if rest:
local, rest = self._getFilename(rest)
if not os.path.isdir(local):
return "Wildcard get with non-directory target."
else:
local = ''
d = self._remoteGlob(remote)
d.addCallback(self._cbGetMultiple, local)
return d
if rest:
local, rest = self._getFilename(rest)
else:
local = os.path.split(remote)[1]
log.msg((remote, local))
lf = file(local, 'w', 0)
path = os.path.join(self.currentDirectory, remote)
d = self.client.openFile(path, filetransfer.FXF_READ, {})
d.addCallback(self._cbGetOpenFile, lf)
d.addErrback(self._ebCloseLf, lf)
return d
def _cbGetMultiple(self, files, local):
#if self._useProgressBar: # one at a time
# XXX this can be optimized for times w/o progress bar
return self._cbGetMultipleNext(None, files, local)
def _cbGetMultipleNext(self, res, files, local):
if isinstance(res, failure.Failure):
self._printFailure(res)
elif res:
self.transport.write(res)
if not res.endswith('\n'):
self.transport.write('\n')
if not files:
return
f = files.pop(0)[0]
lf = file(os.path.join(local, os.path.split(f)[1]), 'w', 0)
path = os.path.join(self.currentDirectory, f)
d = self.client.openFile(path, filetransfer.FXF_READ, {})
d.addCallback(self._cbGetOpenFile, lf)
d.addErrback(self._ebCloseLf, lf)
d.addBoth(self._cbGetMultipleNext, files, local)
return d
def _ebCloseLf(self, f, lf):
lf.close()
return f
def _cbGetOpenFile(self, rf, lf):
return rf.getAttrs().addCallback(self._cbGetFileSize, rf, lf)
def _cbGetFileSize(self, attrs, rf, lf):
if not stat.S_ISREG(attrs['permissions']):
rf.close()
lf.close()
return "Can't get non-regular file: %s" % rf.name
rf.size = attrs['size']
bufferSize = self.client.transport.conn.options['buffersize']
numRequests = self.client.transport.conn.options['requests']
rf.total = 0.0
dList = []
chunks = []
startTime = time.time()
for i in range(numRequests):
d = self._cbGetRead('', rf, lf, chunks, 0, bufferSize, startTime)
dList.append(d)
dl = defer.DeferredList(dList, fireOnOneErrback=1)
dl.addCallback(self._cbGetDone, rf, lf)
return dl
def _getNextChunk(self, chunks):
end = 0
for chunk in chunks:
if end == 'eof':
return # nothing more to get
if end != chunk[0]:
i = chunks.index(chunk)
chunks.insert(i, (end, chunk[0]))
return (end, chunk[0] - end)
end = chunk[1]
bufSize = int(self.client.transport.conn.options['buffersize'])
chunks.append((end, end + bufSize))
return (end, bufSize)
def _cbGetRead(self, data, rf, lf, chunks, start, size, startTime):
if data and isinstance(data, failure.Failure):
log.msg('get read err: %s' % data)
reason = data
reason.trap(EOFError)
i = chunks.index((start, start + size))
del chunks[i]
chunks.insert(i, (start, 'eof'))
elif data:
log.msg('get read data: %i' % len(data))
lf.seek(start)
lf.write(data)
if len(data) != size:
log.msg('got less than we asked for: %i < %i' %
(len(data), size))
i = chunks.index((start, start + size))
del chunks[i]
chunks.insert(i, (start, start + len(data)))
rf.total += len(data)
if self.useProgressBar:
self._printProgessBar(rf, startTime)
chunk = self._getNextChunk(chunks)
if not chunk:
return
else:
start, length = chunk
log.msg('asking for %i -> %i' % (start, start+length))
d = rf.readChunk(start, length)
d.addBoth(self._cbGetRead, rf, lf, chunks, start, length, startTime)
return d
def _cbGetDone(self, ignored, rf, lf):
log.msg('get done')
rf.close()
lf.close()
if self.useProgressBar:
self.transport.write('\n')
return "Transferred %s to %s" % (rf.name, lf.name)
def cmd_PUT(self, rest):
local, rest = self._getFilename(rest)
if '*' in local or '?' in local: # wildcard
if rest:
remote, rest = self._getFilename(rest)
path = os.path.join(self.currentDirectory, remote)
d = self.client.getAttrs(path)
d.addCallback(self._cbPutTargetAttrs, remote, local)
return d
else:
remote = ''
files = glob.glob(local)
return self._cbPutMultipleNext(None, files, remote)
if rest:
remote, rest = self._getFilename(rest)
else:
remote = os.path.split(local)[1]
lf = file(local, 'r')
path = os.path.join(self.currentDirectory, remote)
d = self.client.openFile(path, filetransfer.FXF_WRITE|filetransfer.FXF_CREAT, {})
d.addCallback(self._cbPutOpenFile, lf)
d.addErrback(self._ebCloseLf, lf)
return d
def _cbPutTargetAttrs(self, attrs, path, local):
if not stat.S_ISDIR(attrs['permissions']):
return "Wildcard put with non-directory target."
return self._cbPutMultipleNext(None, files, path)
def _cbPutMultipleNext(self, res, files, path):
if isinstance(res, failure.Failure):
self._printFailure(res)
elif res:
self.transport.write(res)
if not res.endswith('\n'):
self.transport.write('\n')
f = None
while files and not f:
try:
f = files.pop(0)
lf = file(f, 'r')
except:
self._printFailure(failure.Failure())
f = None
if not f:
return
name = os.path.split(f)[1]
remote = os.path.join(self.currentDirectory, path, name)
log.msg((name, remote, path))
d = self.client.openFile(remote, filetransfer.FXF_WRITE|filetransfer.FXF_CREAT, {})
d.addCallback(self._cbPutOpenFile, lf)
d.addErrback(self._ebCloseLf, lf)
d.addBoth(self._cbPutMultipleNext, files, path)
return d
def _cbPutOpenFile(self, rf, lf):
numRequests = self.client.transport.conn.options['requests']
if self.useProgressBar:
lf = FileWrapper(lf)
dList = []
chunks = []
startTime = time.time()
for i in range(numRequests):
d = self._cbPutWrite(None, rf, lf, chunks, startTime)
if d:
dList.append(d)
dl = defer.DeferredList(dList, fireOnOneErrback=1)
dl.addCallback(self._cbPutDone, rf, lf)
return dl
def _cbPutWrite(self, ignored, rf, lf, chunks, startTime):
chunk = self._getNextChunk(chunks)
start, size = chunk
lf.seek(start)
data = lf.read(size)
if self.useProgressBar:
lf.total += len(data)
self._printProgessBar(lf, startTime)
if data:
d = rf.writeChunk(start, data)
d.addCallback(self._cbPutWrite, rf, lf, chunks, startTime)
return d
else:
return
def _cbPutDone(self, ignored, rf, lf):
lf.close()
rf.close()
if self.useProgressBar:
self.transport.write('\n')
return 'Transferred %s to %s' % (lf.name, rf.name)
def cmd_LCD(self, path):
os.chdir(path)
def cmd_LN(self, rest):
linkpath, rest = self._getFilename(rest)
targetpath, rest = self._getFilename(rest)
linkpath, targetpath = map(
lambda x: os.path.join(self.currentDirectory, x),
(linkpath, targetpath))
return self.client.makeLink(linkpath, targetpath).addCallback(_ignore)
def cmd_LS(self, rest):
# possible lines:
# ls current directory
# ls name_of_file that file
# ls name_of_directory that directory
# ls some_glob_string current directory, globbed for that string
options = []
rest = rest.split()
while rest and rest[0] and rest[0][0] == '-':
opts = rest.pop(0)[1:]
for o in opts:
if o == 'l':
options.append('verbose')
elif o == 'a':
options.append('all')
rest = ' '.join(rest)
path, rest = self._getFilename(rest)
if not path:
fullPath = self.currentDirectory + '/'
else:
fullPath = os.path.join(self.currentDirectory, path)
d = self._remoteGlob(fullPath)
d.addCallback(self._cbDisplayFiles, options)
return d
def _cbDisplayFiles(self, files, options):
files.sort()
if 'all' not in options:
files = [f for f in files if not f[0].startswith('.')]
if 'verbose' in options:
lines = [f[1] for f in files]
else:
lines = [f[0] for f in files]
if not lines:
return None
else:
return '\n'.join(lines)
def cmd_MKDIR(self, path):
path, rest = self._getFilename(path)
path = os.path.join(self.currentDirectory, path)
return self.client.makeDirectory(path, {}).addCallback(_ignore)
def cmd_RMDIR(self, path):
path, rest = self._getFilename(path)
path = os.path.join(self.currentDirectory, path)
return self.client.removeDirectory(path).addCallback(_ignore)
def cmd_LMKDIR(self, path):
os.system("mkdir %s" % path)
def cmd_RM(self, path):
path, rest = self._getFilename(path)
path = os.path.join(self.currentDirectory, path)
return self.client.removeFile(path).addCallback(_ignore)
def cmd_LLS(self, rest):
os.system("ls %s" % rest)
def cmd_RENAME(self, rest):
oldpath, rest = self._getFilename(rest)
newpath, rest = self._getFilename(rest)
oldpath, newpath = map (
lambda x: os.path.join(self.currentDirectory, x),
(oldpath, newpath))
return self.client.renameFile(oldpath, newpath).addCallback(_ignore)
def cmd_EXIT(self, ignored):
self.client.transport.loseConnection()
cmd_QUIT = cmd_EXIT
def cmd_VERSION(self, ignored):
return "SFTP version %i" % self.client.version
def cmd_HELP(self, ignored):
return """Available commands:
cd path Change remote directory to 'path'.
chgrp gid path Change gid of 'path' to 'gid'.
chmod mode path Change mode of 'path' to 'mode'.
chown uid path Change uid of 'path' to 'uid'.
exit Disconnect from the server.
get remote-path [local-path] Get remote file.
help Get a list of available commands.
lcd path Change local directory to 'path'.
lls [ls-options] [path] Display local directory listing.
lmkdir path Create local directory.
ln linkpath targetpath Symlink remote file.
lpwd Print the local working directory.
ls [-l] [path] Display remote directory listing.
mkdir path Create remote directory.
progress Toggle progress bar.
put local-path [remote-path] Put local file.
pwd Print the remote working directory.
quit Disconnect from the server.
rename oldpath newpath Rename remote file.
rmdir path Remove remote directory.
rm path Remove remote file.
version Print the SFTP version.
? Synonym for 'help'.
"""
def cmd_PWD(self, ignored):
return self.currentDirectory
def cmd_LPWD(self, ignored):
return os.getcwd()
def cmd_PROGRESS(self, ignored):
self.useProgressBar = not self.useProgressBar
return "%ssing progess bar." % (self.useProgressBar and "U" or "Not u")
def cmd_EXEC(self, rest):
shell = pwd.getpwnam(getpass.getuser())[6]
print repr(rest)
if rest:
cmds = ['-c', rest]
return utils.getProcessOutput(shell, cmds, errortoo=1)
else:
os.system(shell)
# accessory functions
def _remoteGlob(self, fullPath):
log.msg('looking up %s' % fullPath)
head, tail = os.path.split(fullPath)
if '*' in tail or '?' in tail:
glob = 1
else:
glob = 0
if tail and not glob: # could be file or directory
# try directory first
d = self.client.openDirectory(fullPath)
d.addCallback(self._cbOpenList, '')
d.addErrback(self._ebNotADirectory, head, tail)
else:
d = self.client.openDirectory(head)
d.addCallback(self._cbOpenList, tail)
return d
def _cbOpenList(self, directory, glob):
files = []
d = directory.read()
d.addBoth(self._cbReadFile, files, directory, glob)
return d
def _ebNotADirectory(self, reason, path, glob):
d = self.client.openDirectory(path)
d.addCallback(self._cbOpenList, glob)
return d
def _cbReadFile(self, files, l, directory, glob):
if not isinstance(files, failure.Failure):
if glob:
l.extend([f for f in files if fnmatch.fnmatch(f[0], glob)])
else:
l.extend(files)
d = directory.read()
d.addBoth(self._cbReadFile, l, directory, glob)
return d
else:
reason = files
reason.trap(EOFError)
directory.close()
return l
def _abbrevSize(self, size):
# from http://mail.python.org/pipermail/python-list/1999-December/018395.html
_abbrevs = [
(1<<50L, 'PB'),
(1<<40L, 'TB'),
(1<<30L, 'GB'),
(1<<20L, 'MB'),
(1<<10L, 'kb'),
(1, '')
]
for factor, suffix in _abbrevs:
if size > factor:
break
return '%.1f' % (size/factor) + suffix
def _abbrevTime(self, t):
if t > 3600: # 1 hour
hours = int(t / 3600)
t -= (3600 * hours)
mins = int(t / 60)
t -= (60 * mins)
return "%i:%02i:%02i" % (hours, mins, t)
else:
mins = int(t/60)
t -= (60 * mins)
return "%02i:%02i" % (mins, t)
def _printProgessBar(self, f, startTime):
diff = time.time() - startTime
total = f.total
try:
winSize = struct.unpack('4H',
fcntl.ioctl(0, tty.TIOCGWINSZ, '12345679'))
except IOError:
winSize = [None, 80]
speed = total/diff
if speed:
timeLeft = (f.size - total) / speed
else:
timeLeft = 0
front = f.name
back = '%3i%% %s %sps %s ' % ((total/f.size)*100, self._abbrevSize(total),
self._abbrevSize(total/diff), self._abbrevTime(timeLeft))
spaces = (winSize[1] - (len(front) + len(back) + 1)) * ' '
self.transport.write('\r%s%s%s' % (front, spaces, back))
def _getFilename(self, line):
line.lstrip()
if not line:
return None, ''
if line[0] in '\'"':
ret = []
line = list(line)
try:
for i in range(1,len(line)):
c = line[i]
if c == line[0]:
return ''.join(ret), ''.join(line[i+1:]).lstrip()
elif c == '\\': # quoted character
del line[i]
if line[i] not in '\'"\\':
raise IndexError, "bad quote: \\%s" % line[i]
ret.append(line[i])
else:
ret.append(line[i])
except IndexError:
raise IndexError, "unterminated quote"
ret = line.split(None, 1)
if len(ret) == 1:
return ret[0], ''
else:
return ret
StdioClient.__dict__['cmd_?'] = StdioClient.cmd_HELP
class SSHConnection(connection.SSHConnection):
def serviceStarted(self):
self.openChannel(SSHSession())
class SSHSession(channel.SSHChannel):
name = 'session'
def channelOpen(self, foo):
log.msg('session %s open' % self.id)
if self.conn.options['subsystem'].startswith('/'):
request = 'exec'
else:
request = 'subsystem'
d = self.conn.sendRequest(self, request, \
common.NS(self.conn.options['subsystem']), wantReply=1)
d.addCallback(self._cbSubsystem)
d.addErrback(_ebExit)
def _cbSubsystem(self, result):
self.client = filetransfer.FileTransferClient()
self.client.makeConnection(self)
self.dataReceived = self.client.dataReceived
f = None
if self.conn.options['batchfile']:
fn = self.conn.options['batchfile']
if fn != '-':
f = file(fn)
self.stdio = stdio.StandardIO(StdioClient(self.client, f))
def extReceived(self, t, data):
if t==connection.EXTENDED_DATA_STDERR:
log.msg('got %s stderr data' % len(data))
sys.stderr.write(data)
sys.stderr.flush()
def eofReceived(self):
log.msg('got eof')
self.stdio.closeStdin()
def closeReceived(self):
log.msg('remote side closed %s' % self)
self.conn.sendClose(self)
def closed(self):
try:
reactor.stop()
except:
pass
def stopWriting(self):
self.stdio.pauseProducing()
def startWriting(self):
self.stdio.resumeProducing()
if __name__ == '__main__':
run() | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/scripts/cftp.py | cftp.py |
#
from twisted.conch.error import ConchError
from twisted.conch.ssh import common, keys, userauth, agent
from twisted.internet import defer, protocol, reactor
from twisted.python import log
import agent
import os, sys, base64, getpass
def verifyHostKey(transport, host, pubKey, fingerprint):
goodKey = isInKnownHosts(host, pubKey, transport.factory.options)
if goodKey == 1: # good key
return defer.succeed(1)
elif goodKey == 2: # AAHHHHH changed
return defer.fail(ConchError('changed host key'))
else:
oldout, oldin = sys.stdout, sys.stdin
sys.stdin = sys.stdout = open('/dev/tty','r+')
if host == transport.transport.getPeer().host:
khHost = host
else:
host = '%s (%s)' % (host,
transport.transport.getPeer().host)
khHost = '%s,%s' % (host,
transport.transport.getPeer().host)
keyType = common.getNS(pubKey)[0]
print """The authenticity of host '%s' can't be established.
%s key fingerprint is %s.""" % (host,
{'ssh-dss':'DSA', 'ssh-rsa':'RSA'}[keyType],
fingerprint)
try:
ans = raw_input('Are you sure you want to continue connecting (yes/no)? ')
except KeyboardInterrupt:
return defer.fail(ConchError("^C"))
while ans.lower() not in ('yes', 'no'):
ans = raw_input("Please type 'yes' or 'no': ")
sys.stdout,sys.stdin=oldout,oldin
if ans == 'no':
print 'Host key verification failed.'
return defer.fail(ConchError('bad host key'))
print "Warning: Permanently added '%s' (%s) to the list of known hosts." % (khHost, {'ssh-dss':'DSA', 'ssh-rsa':'RSA'}[keyType])
known_hosts = open(os.path.expanduser('~/.ssh/known_hosts'), 'r+')
known_hosts.seek(-1, 2)
if known_hosts.read(1) != '\n':
known_hosts.write('\n')
encodedKey = base64.encodestring(pubKey).replace('\n', '')
known_hosts.write('%s %s %s\n' % (khHost, keyType, encodedKey))
known_hosts.close()
return defer.succeed(1)
def isInKnownHosts(host, pubKey, options):
"""checks to see if host is in the known_hosts file for the user.
returns 0 if it isn't, 1 if it is and is the same, 2 if it's changed.
"""
keyType = common.getNS(pubKey)[0]
retVal = 0
if not options['known-hosts'] and not os.path.exists(os.path.expanduser('~/.ssh/')):
print 'Creating ~/.ssh directory...'
os.mkdir(os.path.expanduser('~/.ssh'))
kh_file = options['known-hosts'] or '~/.ssh/known_hosts'
try:
known_hosts = open(os.path.expanduser(kh_file))
except IOError:
return 0
for line in known_hosts.xreadlines():
split = line.split()
if len(split) < 3:
continue
hosts, hostKeyType, encodedKey = split[:3]
if host not in hosts.split(','): # incorrect host
continue
if hostKeyType != keyType: # incorrect type of key
continue
try:
decodedKey = base64.decodestring(encodedKey)
except:
continue
if decodedKey == pubKey:
return 1
else:
retVal = 2
return retVal
class SSHUserAuthClient(userauth.SSHUserAuthClient):
def __init__(self, user, options, *args):
userauth.SSHUserAuthClient.__init__(self, user, *args)
self.keyAgent = None
self.options = options
self.usedFiles = []
if not options.identitys:
options.identitys = ['~/.ssh/id_rsa', '~/.ssh/id_dsa']
def serviceStarted(self):
if 'SSH_AUTH_SOCK' in os.environ and not self.options['noagent']:
log.msg('using agent')
cc = protocol.ClientCreator(reactor, agent.SSHAgentClient)
d = cc.connectUNIX(os.environ['SSH_AUTH_SOCK'])
d.addCallback(self._setAgent)
d.addErrback(self._ebSetAgent)
else:
userauth.SSHUserAuthClient.serviceStarted(self)
def serviceStopped(self):
if self.keyAgent:
self.keyAgent.transport.loseConnection()
self.keyAgent = None
def _setAgent(self, a):
self.keyAgent = a
d = self.keyAgent.getPublicKeys()
d.addBoth(self._ebSetAgent)
return d
def _ebSetAgent(self, f):
userauth.SSHUserAuthClient.serviceStarted(self)
def _getPassword(self, prompt):
try:
oldout, oldin = sys.stdout, sys.stdin
sys.stdin = sys.stdout = open('/dev/tty','r+')
p=getpass.getpass(prompt)
sys.stdout,sys.stdin=oldout,oldin
return p
except (KeyboardInterrupt, IOError):
print
raise ConchError('PEBKAC')
def getPassword(self, prompt = None):
if not prompt:
prompt = "%s@%s's password: " % (self.user, self.transport.transport.getPeer().host)
try:
p = self._getPassword(prompt)
return defer.succeed(p)
except ConchError:
return defer.fail()
def getPublicKey(self):
if self.keyAgent:
blob = self.keyAgent.getPublicKey()
if blob:
return blob
files = [x for x in self.options.identitys if x not in self.usedFiles]
log.msg(str(self.options.identitys))
log.msg(str(files))
if not files:
return None
file = files[0]
log.msg(file)
self.usedFiles.append(file)
file = os.path.expanduser(file)
file += '.pub'
if not os.path.exists(file):
return self.getPublicKey() # try again
try:
return keys.getPublicKeyString(file)
except:
return self.getPublicKey() # try again
def signData(self, publicKey, signData):
if not self.usedFiles: # agent key
return self.keyAgent.signData(publicKey, signData)
else:
return userauth.SSHUserAuthClient.signData(self, publicKey, signData)
def getPrivateKey(self):
file = os.path.expanduser(self.usedFiles[-1])
if not os.path.exists(file):
return None
try:
return defer.succeed(keys.getPrivateKeyObject(file))
except keys.BadKeyError, e:
if e.args[0] == 'encrypted key with no passphrase':
for i in range(3):
prompt = "Enter passphrase for key '%s': " % \
self.usedFiles[-1]
try:
p = self._getPassword(prompt)
return defer.succeed(keys.getPrivateKeyObject(file, passphrase = p))
except (keys.BadKeyError, ConchError):
pass
return defer.fail(ConchError('bad password'))
raise
except KeyboardInterrupt:
print
reactor.stop()
def getGenericAnswers(self, name, instruction, prompts):
responses = []
try:
oldout, oldin = sys.stdout, sys.stdin
sys.stdin = sys.stdout = open('/dev/tty','r+')
if name:
print name
if instruction:
print instruction
for prompt, echo in prompts:
if echo:
responses.append(raw_input(prompt))
else:
responses.append(getpass.getpass(prompt))
finally:
sys.stdout,sys.stdin=oldout,oldin
return defer.succeed(responses) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/client/default.py | default.py |
#
from twisted.internet import defer, protocol, reactor
from twisted.conch import error
from twisted.conch.ssh import transport
from twisted.python import log
import unix
import os
class SSHClientFactory(protocol.ClientFactory):
# noisy = 1
def __init__(self, d, options, verifyHostKey, userAuthObject):
self.d = d
self.options = options
self.verifyHostKey = verifyHostKey
self.userAuthObject = userAuthObject
def clientConnectionLost(self, connector, reason):
if self.options['reconnect']:
connector.connect()
def clientConnectionFailed(self, connector, reason):
if not self.d: return
d = self.d
self.d = None
d.errback(reason)
def buildProtocol(self, addr):
trans = SSHClientTransport(self)
if self.options['ciphers']:
trans.supportedCiphers = self.options['ciphers']
if self.options['macs']:
trans.supportedMACs = self.options['macs']
if self.options['compress']:
trans.supportedCompressions[0:1] = ['zlib']
if self.options['host-key-algorithms']:
trans.supportedPublicKeys = self.options['host-key-algorithms']
return trans
class SSHClientTransport(transport.SSHClientTransport):
def __init__(self, factory):
self.factory = factory
self.unixServer = None
def connectionLost(self, reason):
transport.SSHClientTransport.connectionLost(self, reason)
if self.unixServer:
self.unixServer.stopListening()
self.unixServer = None
def receiveError(self, code, desc):
if not self.factory.d: return
d = self.factory.d
self.factory.d = None
d.errback(error.ConchError(desc, code))
def sendDisconnect(self, code, reason):
if not self.factory.d: return
d = self.factory.d
self.factory.d = None
transport.SSHClientTransport.sendDisconnect(self, code, reason)
d.errback(error.ConchError(reason, code))
def receiveDebug(self, alwaysDisplay, message, lang):
log.msg('Received Debug Message: %s' % message)
if alwaysDisplay: # XXX what should happen here?
print message
def verifyHostKey(self, pubKey, fingerprint):
return self.factory.verifyHostKey(self, self.transport.getPeer().host, pubKey,
fingerprint)
def setService(self, service):
log.msg('setting client server to %s' % service)
transport.SSHClientTransport.setService(self, service)
if service.name != 'ssh-userauth' and self.factory.d:
d = self.factory.d
self.factory.d = None
d.callback(None)
if service.name == 'ssh-connection':
# listen for UNIX
if not self.factory.options['nocache']:
user = self.factory.userAuthObject.user
peer = self.transport.getPeer()
filename = os.path.expanduser("~/.conch-%s-%s-%i" % (user, peer.host, peer.port))
try:
u = unix.SSHUnixServerFactory(service)
try:
os.unlink(filename)
except OSError:
pass
self.unixServer = reactor.listenUNIX(filename, u, mode=0600, wantPID=1)
except Exception, e:
log.msg('error trying to listen on %s' % filename)
log.err(e)
def connectionSecure(self):
self.requestService(self.factory.userAuthObject)
def connect(host, port, options, verifyHostKey, userAuthObject):
d = defer.Deferred()
factory = SSHClientFactory(d, options, verifyHostKey, userAuthObject)
reactor.connectTCP(host, port, factory)
return d | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/client/direct.py | direct.py |
#
from twisted.conch.error import ConchError
from twisted.conch.ssh import channel, connection
from twisted.internet import defer, protocol, reactor
from twisted.python import log
from twisted.spread import banana
import os, stat, pickle
import types # this is for evil
class SSHUnixClientFactory(protocol.ClientFactory):
# noisy = 1
def __init__(self, d, options, userAuthObject):
self.d = d
self.options = options
self.userAuthObject = userAuthObject
def clientConnectionLost(self, connector, reason):
if self.options['reconnect']:
connector.connect()
#log.err(reason)
if not self.d: return
d = self.d
self.d = None
d.errback(reason)
def clientConnectionFailed(self, connector, reason):
#try:
# os.unlink(connector.transport.addr)
#except:
# pass
#log.err(reason)
if not self.d: return
d = self.d
self.d = None
d.errback(reason)
#reactor.connectTCP(options['host'], options['port'], SSHClientFactory())
def startedConnecting(self, connector):
fd = connector.transport.fileno()
stats = os.fstat(fd)
try:
filestats = os.stat(connector.transport.addr)
except:
connector.stopConnecting()
return
if stat.S_IMODE(filestats[0]) != 0600:
log.msg("socket mode is not 0600: %s" % oct(stat.S_IMODE(stats[0])))
elif filestats[4] != os.getuid():
log.msg("socket not owned by us: %s" % stats[4])
elif filestats[5] != os.getgid():
log.msg("socket not owned by our group: %s" % stats[5])
# XXX reenable this when i can fix it for cygwin
#elif filestats[-3:] != stats[-3:]:
# log.msg("socket doesn't have same create times")
else:
log.msg('conecting OK')
return
connector.stopConnecting()
def buildProtocol(self, addr):
# here comes the EVIL
obj = self.userAuthObject.instance
bases = []
for base in obj.__class__.__bases__:
if base == connection.SSHConnection:
bases.append(SSHUnixClientProtocol)
else:
bases.append(base)
newClass = types.ClassType(obj.__class__.__name__, tuple(bases), obj.__class__.__dict__)
obj.__class__ = newClass
SSHUnixClientProtocol.__init__(obj)
log.msg('returning %s' % obj)
if self.d:
d = self.d
self.d = None
d.callback(None)
return obj
class SSHUnixServerFactory(protocol.Factory):
def __init__(self, conn):
self.conn = conn
def buildProtocol(self, addr):
return SSHUnixServerProtocol(self.conn)
class SSHUnixProtocol(banana.Banana):
knownDialects = ['none']
def __init__(self):
banana.Banana.__init__(self)
self.deferredQueue = []
self.deferreds = {}
self.deferredID = 0
def connectionMade(self):
log.msg('connection made %s' % self)
banana.Banana.connectionMade(self)
def expressionReceived(self, lst):
vocabName = lst[0]
fn = "msg_%s" % vocabName
func = getattr(self, fn)
func(lst[1:])
def sendMessage(self, vocabName, *tup):
self.sendEncoded([vocabName] + list(tup))
def returnDeferredLocal(self):
d = defer.Deferred()
self.deferredQueue.append(d)
return d
def returnDeferredWire(self, d):
di = self.deferredID
self.deferredID += 1
self.sendMessage('returnDeferred', di)
d.addCallback(self._cbDeferred, di)
d.addErrback(self._ebDeferred, di)
def _cbDeferred(self, result, di):
self.sendMessage('callbackDeferred', di, pickle.dumps(result))
def _ebDeferred(self, reason, di):
self.sendMessage('errbackDeferred', di, pickle.dumps(reason))
def msg_returnDeferred(self, lst):
deferredID = lst[0]
self.deferreds[deferredID] = self.deferredQueue.pop(0)
def msg_callbackDeferred(self, lst):
deferredID, result = lst
d = self.deferreds[deferredID]
del self.deferreds[deferredID]
d.callback(pickle.loads(result))
def msg_errbackDeferred(self, lst):
deferredID, result = lst
d = self.deferreds[deferredID]
del self.deferreds[deferredID]
d.errback(pickle.loads(result))
class SSHUnixClientProtocol(SSHUnixProtocol):
def __init__(self):
SSHUnixProtocol.__init__(self)
self.isClient = 1
self.channelQueue = []
self.channels = {}
def logPrefix(self):
return "SSHUnixClientProtocol (%i) on %s" % (id(self), self.transport.logPrefix())
def connectionReady(self):
log.msg('connection ready')
self.serviceStarted()
def connectionLost(self, reason):
self.serviceStopped()
def requestRemoteForwarding(self, remotePort, hostport):
self.sendMessage('requestRemoteForwarding', remotePort, hostport)
def cancelRemoteForwarding(self, remotePort):
self.sendMessage('cancelRemoteForwarding', remotePort)
def sendGlobalRequest(self, request, data, wantReply = 0):
self.sendMessage('sendGlobalRequest', request, data, wantReply)
if wantReply:
return self.returnDeferredLocal()
def openChannel(self, channel, extra = ''):
self.channelQueue.append(channel)
channel.conn = self
self.sendMessage('openChannel', channel.name,
channel.localWindowSize,
channel.localMaxPacket, extra)
def sendRequest(self, channel, requestType, data, wantReply = 0):
self.sendMessage('sendRequest', channel.id, requestType, data, wantReply)
if wantReply:
return self.returnDeferredLocal()
def adjustWindow(self, channel, bytesToAdd):
self.sendMessage('adjustWindow', channel.id, bytesToAdd)
def sendData(self, channel, data):
self.sendMessage('sendData', channel.id, data)
def sendExtendedData(self, channel, dataType, data):
self.sendMessage('sendExtendedData', channel.id, data)
def sendEOF(self, channel):
self.sendMessage('sendEOF', channel.id)
def sendClose(self, channel):
self.sendMessage('sendClose', channel.id)
def msg_channelID(self, lst):
channelID = lst[0]
self.channels[channelID] = self.channelQueue.pop(0)
self.channels[channelID].id = channelID
def msg_channelOpen(self, lst):
channelID, remoteWindow, remoteMax, specificData = lst
channel = self.channels[channelID]
channel.remoteWindowLeft = remoteWindow
channel.remoteMaxPacket = remoteMax
channel.channelOpen(specificData)
def msg_openFailed(self, lst):
channelID, reason = lst
self.channels[channelID].openFailed(pickle.loads(reason))
del self.channels[channelID]
def msg_addWindowBytes(self, lst):
channelID, bytes = lst
self.channels[channelID].addWindowBytes(bytes)
def msg_requestReceived(self, lst):
channelID, requestType, data = lst
d = defer.maybeDeferred(self.channels[channelID].requestReceived, requestType, data)
self.returnDeferredWire(d)
def msg_dataReceived(self, lst):
channelID, data = lst
self.channels[channelID].dataReceived(data)
def msg_extReceived(self, lst):
channelID, dataType, data = lst
self.channels[channelID].extReceived(dataType, data)
def msg_eofReceived(self, lst):
channelID = lst[0]
self.channels[channelID].eofReceived()
def msg_closeReceived(self, lst):
channelID = lst[0]
channel = self.channels[channelID]
channel.remoteClosed = 1
channel.closeReceived()
def msg_closed(self, lst):
channelID = lst[0]
channel = self.channels[channelID]
self.channelClosed(channel)
def channelClosed(self, channel):
channel.localClosed = channel.remoteClosed = 1
del self.channels[channel.id]
log.callWithLogger(channel, channel.closed)
# just in case the user doesn't override
def serviceStarted(self):
pass
def serviceStopped(self):
pass
class SSHUnixServerProtocol(SSHUnixProtocol):
def __init__(self, conn):
SSHUnixProtocol.__init__(self)
self.isClient = 0
self.conn = conn
def connectionLost(self, reason):
for channel in self.conn.channels.values():
if isinstance(channel, SSHUnixChannel) and channel.unix == self:
log.msg('forcibly closing %s' % channel)
try:
self.conn.sendClose(channel)
except:
pass
def haveChannel(self, channelID):
return self.conn.channels.has_key(channelID)
def getChannel(self, channelID):
channel = self.conn.channels[channelID]
if not isinstance(channel, SSHUnixChannel):
raise ConchError('nice try bub')
return channel
def msg_requestRemoteForwarding(self, lst):
remotePort, hostport = lst
hostport = tuple(hostport)
self.conn.requestRemoteForwarding(remotePort, hostport)
def msg_cancelRemoteForwarding(self, lst):
[remotePort] = lst
self.conn.cancelRemoteForwarding(remotePort)
def msg_sendGlobalRequest(self, lst):
requestName, data, wantReply = lst
d = self.conn.sendGlobalRequest(requestName, data, wantReply)
if wantReply:
self.returnDeferredWire(d)
def msg_openChannel(self, lst):
name, windowSize, maxPacket, extra = lst
channel = SSHUnixChannel(self, name, windowSize, maxPacket)
self.conn.openChannel(channel, extra)
self.sendMessage('channelID', channel.id)
def msg_sendRequest(self, lst):
cn, requestType, data, wantReply = lst
if not self.haveChannel(cn):
if wantReply:
self.returnDeferredWire(defer.fail(ConchError("no channel")))
channel = self.getChannel(cn)
d = self.conn.sendRequest(channel, requestType, data, wantReply)
if wantReply:
self.returnDeferredWire(d)
def msg_adjustWindow(self, lst):
cn, bytesToAdd = lst
if not self.haveChannel(cn): return
channel = self.getChannel(cn)
self.conn.adjustWindow(channel, bytesToAdd)
def msg_sendData(self, lst):
cn, data = lst
if not self.haveChannel(cn): return
channel = self.getChannel(cn)
self.conn.sendData(channel, data)
def msg_sendExtended(self, lst):
cn, dataType, data = lst
if not self.haveChannel(cn): return
channel = self.getChannel(cn)
self.conn.sendExtendedData(channel, dataType, data)
def msg_sendEOF(self, lst):
(cn, ) = lst
if not self.haveChannel(cn): return
channel = self.getChannel(cn)
self.conn.sendEOF(channel)
def msg_sendClose(self, lst):
(cn, ) = lst
if not self.haveChannel(cn): return
channel = self.getChannel(cn)
self.conn.sendClose(channel)
class SSHUnixChannel(channel.SSHChannel):
def __init__(self, unix, name, windowSize, maxPacket):
channel.SSHChannel.__init__(self, windowSize, maxPacket, conn = unix.conn)
self.unix = unix
self.name = name
def channelOpen(self, specificData):
self.unix.sendMessage('channelOpen', self.id, self.remoteWindowLeft,
self.remoteMaxPacket, specificData)
def openFailed(self, reason):
self.unix.sendMessage('openFailed', self.id, pickle.dumps(reason))
def addWindowBytes(self, bytes):
self.unix.sendMessage('addWindowBytes', self.id, bytes)
def dataReceived(self, data):
self.unix.sendMessage('dataReceived', self.id, data)
def requestReceived(self, reqType, data):
self.unix.sendMessage('requestReceived', self.id, reqType, data)
return self.unix.returnDeferredLocal()
def extReceived(self, dataType, data):
self.unix.sendMessage('extReceived', self.id, dataType, data)
def eofReceived(self):
self.unix.sendMessage('eofReceived', self.id)
def closeReceived(self):
self.unix.sendMessage('closeReceived', self.id)
def closed(self):
self.unix.sendMessage('closed', self.id)
def connect(host, port, options, verifyHostKey, userAuthObject):
if options['nocache']:
return defer.fail(ConchError('not using connection caching'))
d = defer.Deferred()
filename = os.path.expanduser("~/.conch-%s-%s-%i" % (userAuthObject.user, host, port))
factory = SSHUnixClientFactory(d, options, userAuthObject)
reactor.connectUNIX(filename, factory, timeout=2, checkPID=1)
return d | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/client/unix.py | unix.py |
#
from twisted.conch.ssh.transport import SSHClientTransport, SSHCiphers
from twisted.python import usage
import connect
import sys
class ConchOptions(usage.Options):
optParameters = [['user', 'l', None, 'Log in using this user name.'],
['identity', 'i', None],
['ciphers', 'c', None],
['macs', 'm', None],
['connection-usage', 'K', None],
['port', 'p', None, 'Connect to this port. Server must be on the same port.'],
['option', 'o', None, 'Ignored OpenSSH options'],
['host-key-algorithms', '', None],
['known-hosts', '', None, 'File to check for host keys'],
['user-authentications', '', None, 'Types of user authentications to use.'],
['logfile', '', None, 'File to log to, or - for stdout'],
]
optFlags = [['version', 'V', 'Display version number only.'],
['compress', 'C', 'Enable compression.'],
['log', 'v', 'Enable logging (defaults to stderr)'],
['nocache', 'I', 'Do not allow connection sharing over this connection.'],
['nox11', 'x', 'Disable X11 connection forwarding (default)'],
['agent', 'A', 'Enable authentication agent forwarding'],
['noagent', 'a', 'Disable authentication agent forwarding (default)'],
['reconnect', 'r', 'Reconnect to the server if the connection is lost.'],
]
zsh_altArgDescr = {"connection-usage":"Connection types to use"}
#zsh_multiUse = ["foo", "bar"]
zsh_mutuallyExclusive = [("agent", "noagent")]
zsh_actions = {"user":"_users",
"ciphers":"_values -s , 'ciphers to choose from' %s" %
" ".join(SSHCiphers.cipherMap.keys()),
"macs":"_values -s , 'macs to choose from' %s" %
" ".join(SSHCiphers.macMap.keys()),
"host-key-algorithms":"_values -s , 'host key algorithms to choose from' %s" %
" ".join(SSHClientTransport.supportedPublicKeys),
"connection-usage":"_values -s , 'connection types to choose from' %s" %
" ".join(connect.connectTypes.keys()),
#"user-authentications":"_values -s , 'user authentication types to choose from' %s" %
# " ".join(???),
}
#zsh_actionDescr = {"logfile":"log file name", "random":"random seed"}
# user, host, or user@host completion similar to zsh's ssh completion
zsh_extras = ['1:host | user@host:{_ssh;if compset -P "*@"; then _wanted hosts expl "remote host name" _ssh_hosts && ret=0 elif compset -S "@*"; then _wanted users expl "login name" _ssh_users -S "" && ret=0 else if (( $+opt_args[-l] )); then tmp=() else tmp=( "users:login name:_ssh_users -qS@" ) fi; _alternative "hosts:remote host name:_ssh_hosts" "$tmp[@]" && ret=0 fi}']
def __init__(self, *args, **kw):
usage.Options.__init__(self, *args, **kw)
self.identitys = []
self.conns = None
def opt_identity(self, i):
"""Identity for public-key authentication"""
self.identitys.append(i)
def opt_ciphers(self, ciphers):
"Select encryption algorithms"
ciphers = ciphers.split(',')
for cipher in ciphers:
if not SSHCiphers.cipherMap.has_key(cipher):
sys.exit("Unknown cipher type '%s'" % cipher)
self['ciphers'] = ciphers
def opt_macs(self, macs):
"Specify MAC algorithms"
macs = macs.split(',')
for mac in macs:
if not SSHCiphers.macMap.has_key(mac):
sys.exit("Unknown mac type '%s'" % mac)
self['macs'] = macs
def opt_host_key_algorithms(self, hkas):
"Select host key algorithms"
hkas = hkas.split(',')
for hka in hkas:
if hka not in SSHClientTransport.supportedPublicKeys:
sys.exit("Unknown host key type '%s'" % hka)
self['host-key-algorithms'] = hkas
def opt_user_authentications(self, uas):
"Choose how to authenticate to the remote server"
self['user-authentications'] = uas.split(',')
def opt_connection_usage(self, conns):
conns = conns.split(',')
connTypes = connect.connectTypes.keys()
for conn in conns:
if conn not in connTypes:
sys.exit("Unknown connection type '%s'" % conn)
self.conns = conns
# def opt_compress(self):
# "Enable compression"
# self.enableCompression = 1
# SSHClientTransport.supportedCompressions[0:1] = ['zlib'] | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/client/options.py | options.py |
#
"""Common functions for the SSH classes.
This module is unstable.
Maintainer: U{Paul Swartz<mailto:[email protected]>}
"""
import struct
try:
from Crypto import Util
from Crypto.Util import randpool
except ImportError:
import warnings
warnings.warn("PyCrypto not installed, but continuing anyways!",
RuntimeWarning)
else:
entropy = randpool.RandomPool()
entropy.stir()
def NS(t):
"""
net string
"""
return struct.pack('!L',len(t)) + t
def getNS(s, count=1):
"""
get net string
"""
ns = []
c = 0
for i in range(count):
l, = struct.unpack('!L',s[c:c+4])
ns.append(s[c+4:4+l+c])
c += 4 + l
return tuple(ns) + (s[c:],)
def MP(number):
if number==0: return '\000'*4
assert number>0
bn = Util.number.long_to_bytes(number)
if ord(bn[0])&128:
bn = '\000' + bn
return struct.pack('>L',len(bn)) + bn
def getMP(data):
"""
get multiple precision integer
"""
length=struct.unpack('>L',data[:4])[0]
return Util.number.bytes_to_long(data[4:4+length]),data[4+length:]
def _MPpow(x, y, z):
"""return the MP version of (x**y)%z
"""
return MP(pow(x,y,z))
def ffs(c, s):
"""
first from second
goes through the first list, looking for items in the second, returns the first one
"""
for i in c:
if i in s: return i
getMP_py = getMP
MP_py = MP
_MPpow_py = _MPpow
pyPow = pow
def _fastgetMP(i):
l = struct.unpack('!L', i[:4])[0]
n = i[4:l+4][::-1]
return long(gmpy.mpz(n+'\x00', 256)), i[4+l:]
def _fastMP(i):
i2 = gmpy.mpz(i).binary()[::-1]
return struct.pack('!L', len(i2)) + i2
def _fastMPpow(x, y, z=None):
r = pyPow(gmpy.mpz(x),y,z).binary()[::-1]
return struct.pack('!L', len(r)) + r
def _fastpow(x, y, z=None):
return pyPow(gmpy.mpz(x), y, z)
def install():
global getMP, MP, _MPpow
getMP = _fastgetMP
MP = _fastMP
_MPpow = _fastMPpow
__builtins__['pow'] = _fastpow # evil evil
try:
import gmpy
install()
except ImportError:
pass | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/ssh/common.py | common.py |
#
import struct, errno
from twisted.internet import defer, protocol
from twisted.python import failure, log
from common import NS, getNS
from twisted.conch.interfaces import ISFTPServer, ISFTPFile
from zope import interface
class FileTransferBase(protocol.Protocol):
versions = (3, )
packetTypes = {}
def __init__(self):
self.buf = ''
self.otherVersion = None # this gets set
def sendPacket(self, kind, data):
self.transport.write(struct.pack('!LB', len(data)+1, kind) + data)
def dataReceived(self, data):
self.buf += data
while len(self.buf) > 5:
length, kind = struct.unpack('!LB', self.buf[:5])
if len(self.buf) < 4 + length:
return
data, self.buf = self.buf[5:4+length], self.buf[4+length:]
packetType = self.packetTypes.get(kind, None)
if not packetType:
log.msg('no packet type for', kind)
continue
f = getattr(self, 'packet_%s' % packetType, None)
if not f:
log.msg('not implemented: %s' % packetType)
log.msg(repr(data[4:]))
reqId, = struct.unpack('!L', data[:4])
self._sendStatus(reqId, FX_OP_UNSUPPORTED,
"don't understand %s" % packetType)
#XXX not implemented
continue
try:
f(data)
except:
log.err()
continue
reqId ,= struct.unpack('!L', data[:4])
self._ebStatus(failure.Failure(e), reqId)
def _parseAttributes(self, data):
flags ,= struct.unpack('!L', data[:4])
attrs = {}
data = data[4:]
if flags & FILEXFER_ATTR_SIZE == FILEXFER_ATTR_SIZE:
size ,= struct.unpack('!Q', data[:8])
attrs['size'] = size
data = data[8:]
if flags & FILEXFER_ATTR_OWNERGROUP == FILEXFER_ATTR_OWNERGROUP:
uid, gid = struct.unpack('!2L', data[:8])
attrs['uid'] = uid
attrs['gid'] = gid
data = data[8:]
if flags & FILEXFER_ATTR_PERMISSIONS == FILEXFER_ATTR_PERMISSIONS:
perms ,= struct.unpack('!L', data[:4])
attrs['permissions'] = perms
data = data[4:]
if flags & FILEXFER_ATTR_ACMODTIME == FILEXFER_ATTR_ACMODTIME:
atime, mtime = struct.unpack('!2L', data[:8])
attrs['atime'] = atime
attrs['mtime'] = mtime
data = data[8:]
if flags & FILEXFER_ATTR_EXTENDED == FILEXFER_ATTR_EXTENDED:
extended_count ,= struct.unpack('!L', data[4:])
data = data[4:]
for i in xrange(extended_count):
extended_type, data = getNS(data)
extended_data, data = getNS(data)
attrs['ext_%s' % extended_type] = extended_data
return attrs, data
def _packAttributes(self, attrs):
flags = 0
data = ''
if 'size' in attrs:
data += struct.pack('!Q', attrs['size'])
flags |= FILEXFER_ATTR_SIZE
if 'uid' in attrs and 'gid' in attrs:
data += struct.pack('!2L', attrs['uid'], attrs['gid'])
flags |= FILEXFER_ATTR_OWNERGROUP
if 'permissions' in attrs:
data += struct.pack('!L', attrs['permissions'])
flags |= FILEXFER_ATTR_PERMISSIONS
if 'atime' in attrs and 'mtime' in attrs:
data += struct.pack('!2L', attrs['atime'], attrs['mtime'])
flags |= FILEXFER_ATTR_ACMODTIME
extended = []
for k in attrs:
if k.startswith('ext_'):
ext_type = NS(k[4:])
ext_data = NS(attrs[k])
extended.append(ext_type+ext_data)
if extended:
data += struct.pack('!L', len(extended))
data += ''.join(extended)
flags |= FILEXFER_ATTR_EXTENDED
return struct.pack('!L', flags) + data
class FileTransferServer(FileTransferBase):
def __init__(self, data=None, avatar=None):
FileTransferBase.__init__(self)
self.client = ISFTPServer(avatar) # yay interfaces
self.openFiles = {}
self.openDirs = {}
def packet_INIT(self, data):
version ,= struct.unpack('!L', data[:4])
self.version = min(list(self.versions) + [version])
data = data[4:]
ext = {}
while data:
ext_name, data = getNS(data)
ext_data, data = getNS(data)
ext[ext_name] = ext_data
our_ext = self.client.gotVersion(version, ext)
our_ext_data = ""
for (k,v) in our_ext.items():
our_ext_data += NS(k) + NS(v)
self.sendPacket(FXP_VERSION, struct.pack('!L', self.version) + \
our_ext_data)
def packet_OPEN(self, data):
requestId = data[:4]
data = data[4:]
filename, data = getNS(data)
flags ,= struct.unpack('!L', data[:4])
data = data[4:]
attrs, data = self._parseAttributes(data)
assert data == '', 'still have data in OPEN: %s' % repr(data)
d = defer.maybeDeferred(self.client.openFile, filename, flags, attrs)
d.addCallback(self._cbOpenFile, requestId)
d.addErrback(self._ebStatus, requestId, "open failed")
def _cbOpenFile(self, fileObj, requestId):
fileId = str(hash(fileObj))
if fileId in self.openFiles:
raise KeyError, 'id already open'
self.openFiles[fileId] = fileObj
self.sendPacket(FXP_HANDLE, requestId + NS(fileId))
def packet_CLOSE(self, data):
requestId = data[:4]
data = data[4:]
handle, data = getNS(data)
assert data == '', 'still have data in CLOSE: %s' % repr(data)
if handle in self.openFiles:
fileObj = self.openFiles[handle]
d = defer.maybeDeferred(fileObj.close)
d.addCallback(self._cbClose, handle, requestId)
d.addErrback(self._ebStatus, requestId, "close failed")
elif handle in self.openDirs:
dirObj = self.openDirs[handle][0]
d = defer.maybeDeferred(dirObj.close)
d.addCallback(self._cbClose, handle, requestId, 1)
d.addErrback(self._ebStatus, requestId, "close failed")
else:
self._ebClose(failure.Failure(KeyError()), requestId)
def _cbClose(self, result, handle, requestId, isDir = 0):
if isDir:
del self.openDirs[handle]
else:
del self.openFiles[handle]
self._sendStatus(requestId, FX_OK, 'file closed')
def packet_READ(self, data):
requestId = data[:4]
data = data[4:]
handle, data = getNS(data)
(offset, length), data = struct.unpack('!QL', data[:12]), data[12:]
assert data == '', 'still have data in READ: %s' % repr(data)
if handle not in self.openFiles:
self._ebRead(failure.Failure(KeyError()), requestId)
else:
fileObj = self.openFiles[handle]
d = defer.maybeDeferred(fileObj.readChunk, offset, length)
d.addCallback(self._cbRead, requestId)
d.addErrback(self._ebStatus, requestId, "read failed")
def _cbRead(self, result, requestId):
if result == '': # python's read will return this for EOF
raise EOFError()
self.sendPacket(FXP_DATA, requestId + NS(result))
def packet_WRITE(self, data):
requestId = data[:4]
data = data[4:]
handle, data = getNS(data)
offset, = struct.unpack('!Q', data[:8])
data = data[8:]
writeData, data = getNS(data)
assert data == '', 'still have data in WRITE: %s' % repr(data)
if handle not in self.openFiles:
self._ebWrite(failure.Failure(KeyError()), requestId)
else:
fileObj = self.openFiles[handle]
d = defer.maybeDeferred(fileObj.writeChunk, offset, writeData)
d.addCallback(self._cbStatus, requestId, "write succeeded")
d.addErrback(self._ebStatus, requestId, "write failed")
def packet_REMOVE(self, data):
requestId = data[:4]
data = data[4:]
filename, data = getNS(data)
assert data == '', 'still have data in REMOVE: %s' % repr(data)
d = defer.maybeDeferred(self.client.removeFile, filename)
d.addCallback(self._cbStatus, requestId, "remove succeeded")
d.addErrback(self._ebStatus, requestId, "remove failed")
def packet_RENAME(self, data):
requestId = data[:4]
data = data[4:]
oldPath, data = getNS(data)
newPath, data = getNS(data)
assert data == '', 'still have data in RENAME: %s' % repr(data)
d = defer.maybeDeferred(self.client.renameFile, oldPath, newPath)
d.addCallback(self._cbStatus, requestId, "rename succeeded")
d.addErrback(self._ebStatus, requestId, "rename failed")
def packet_MKDIR(self, data):
requestId = data[:4]
data = data[4:]
path, data = getNS(data)
attrs, data = self._parseAttributes(data)
assert data == '', 'still have data in MKDIR: %s' % repr(data)
d = defer.maybeDeferred(self.client.makeDirectory, path, attrs)
d.addCallback(self._cbStatus, requestId, "mkdir succeeded")
d.addErrback(self._ebStatus, requestId, "mkdir failed")
def packet_RMDIR(self, data):
requestId = data[:4]
data = data[4:]
path, data = getNS(data)
assert data == '', 'still have data in RMDIR: %s' % repr(data)
d = defer.maybeDeferred(self.client.removeDirectory, path)
d.addCallback(self._cbStatus, requestId, "rmdir succeeded")
d.addErrback(self._ebStatus, requestId, "rmdir failed")
def packet_OPENDIR(self, data):
requestId = data[:4]
data = data[4:]
path, data = getNS(data)
assert data == '', 'still have data in OPENDIR: %s' % repr(data)
d = defer.maybeDeferred(self.client.openDirectory, path)
d.addCallback(self._cbOpenDirectory, requestId)
d.addErrback(self._ebStatus, requestId, "opendir failed")
def _cbOpenDirectory(self, dirObj, requestId):
handle = str(hash(dirObj))
if handle in self.openDirs:
raise KeyError, "already opened this directory"
self.openDirs[handle] = [dirObj, iter(dirObj)]
self.sendPacket(FXP_HANDLE, requestId + NS(handle))
def packet_READDIR(self, data):
requestId = data[:4]
data = data[4:]
handle, data = getNS(data)
assert data == '', 'still have data in READDIR: %s' % repr(data)
if handle not in self.openDirs:
self._ebStatus(failure.Failure(KeyError()), requestId)
else:
dirObj, dirIter = self.openDirs[handle]
d = defer.maybeDeferred(self._scanDirectory, dirIter, [])
d.addCallback(self._cbSendDirectory, requestId)
d.addErrback(self._ebStatus, requestId, "scan directory failed")
def _scanDirectory(self, dirIter, f):
while len(f) < 250:
try:
info = dirIter.next()
except StopIteration:
if not f:
raise EOFError
return f
if isinstance(info, defer.Deferred):
info.addCallback(self._cbScanDirectory, dirIter, f)
return
else:
f.append(info)
return f
def _cbScanDirectory(self, result, dirIter, f):
f.append(result)
return self._scanDirectory(dirIter, f)
def _cbSendDirectory(self, result, requestId):
data = ''
for (filename, longname, attrs) in result:
data += NS(filename)
data += NS(longname)
data += self._packAttributes(attrs)
self.sendPacket(FXP_NAME, requestId +
struct.pack('!L', len(result))+data)
def packet_STAT(self, data, followLinks = 1):
requestId = data[:4]
data = data[4:]
path, data = getNS(data)
assert data == '', 'still have data in STAT/LSTAT: %s' % repr(data)
d = defer.maybeDeferred(self.client.getAttrs, path, followLinks)
d.addCallback(self._cbStat, requestId)
d.addErrback(self._ebStatus, requestId, 'stat/lstat failed')
def packet_LSTAT(self, data):
self.packet_STAT(data, 0)
def packet_FSTAT(self, data):
requestId = data[:4]
data = data[4:]
handle, data = getNS(data)
assert data == '', 'still have data in FSTAT: %s' % repr(data)
if handle not in self.openFiles:
self._ebStatus(failure.Failure(KeyError('%s not in self.openFiles'
% handle)), requestId)
else:
fileObj = self.openFiles[handle]
d = defer.maybeDeferred(fileObj.getAttrs)
d.addCallback(self._cbStat, requestId)
d.addErrback(self._ebStatus, requestId, 'fstat failed')
def _cbStat(self, result, requestId):
data = requestId + self._packAttributes(result)
self.sendPacket(FXP_ATTRS, data)
def packet_SETSTAT(self, data):
requestId = data[:4]
data = data[4:]
path, data = getNS(data)
attrs, data = self._parseAttributes(data)
if data != '':
log.msg('WARN: still have data in SETSTAT: %s' % repr(data))
d = defer.maybeDeferred(self.client.setAttrs, path, attrs)
d.addCallback(self._cbStatus, requestId, 'setstat succeeded')
d.addErrback(self._ebStatus, requestId, 'setstat failed')
def packet_FSETSTAT(self, data):
requestId = data[:4]
data = data[4:]
handle, data = getNS(data)
attrs, data = self._parseAttributes(data)
assert data == '', 'still have data in FSETSTAT: %s' % repr(data)
if handle not in self.openFiles:
self._ebStatus(failure.Failure(KeyError()), requestId)
else:
fileObj = self.openFiles[handle]
d = defer.maybeDeferred(fileObj.setAttrs, attrs)
d.addCallback(self._cbStatus, requestId, 'fsetstat succeeded')
d.addErrback(self._ebStatus, requestId, 'fsetstat failed')
def packet_READLINK(self, data):
requestId = data[:4]
data = data[4:]
path, data = getNS(data)
assert data == '', 'still have data in READLINK: %s' % repr(data)
d = defer.maybeDeferred(self.client.readLink, path)
d.addCallback(self._cbReadLink, requestId)
d.addErrback(self._ebStatus, requestId, 'readlink failed')
def _cbReadLink(self, result, requestId):
self._cbSendDirectory([(result, '', {})], requestId)
def packet_SYMLINK(self, data):
requestId = data[:4]
data = data[4:]
linkPath, data = getNS(data)
targetPath, data = getNS(data)
d = defer.maybeDeferred(self.client.makeLink, linkPath, targetPath)
d.addCallback(self._cbStatus, requestId, 'symlink succeeded')
d.addErrback(self._ebStatus, requestId, 'symlink failed')
def packet_REALPATH(self, data):
requestId = data[:4]
data = data[4:]
path, data = getNS(data)
assert data == '', 'still have data in REALPATH: %s' % repr(data)
d = defer.maybeDeferred(self.client.realPath, path)
d.addCallback(self._cbReadLink, requestId) # same return format
d.addErrback(self._ebStatus, requestId, 'realpath failed')
def packet_EXTENDED(self, data):
requestId = data[:4]
data = data[4:]
extName, extData = getNS(data)
d = defer.maybeDeferred(self.client.extendedRequest, extName, extData)
d.addCallback(self._cbExtended, requestId)
d.addErrback(self._ebStatus, requestId, 'extended %s failed' % extName)
def _cbExtended(self, data, requestId):
self.sendPacket(FXP_EXTENDED_REPLY, requestId + data)
def _cbStatus(self, result, requestId, msg = "request succeeded"):
self._sendStatus(requestId, FX_OK, msg)
def _ebStatus(self, reason, requestId, msg = "request failed"):
code = FX_FAILURE
message = msg
if reason.type in (IOError, OSError):
if reason.value.errno == errno.ENOENT: # no such file
code = FX_NO_SUCH_FILE
message = reason.value.strerror
elif reason.value.errno == errno.EACCES: # permission denied
code = FX_PERMISSION_DENIED
message = reason.value.strerror
else:
log.err(reason)
elif reason.type == EOFError: # EOF
code = FX_EOF
if reason.value.args:
message = reason.value.args[0]
elif reason.type == NotImplementedError:
code = FX_OP_UNSUPPORTED
if reason.value.args:
message = reason.value.args[0]
elif reason.type == SFTPError:
code = reason.value.code
message = reason.value.message
else:
log.err(reason)
self._sendStatus(requestId, code, message)
def _sendStatus(self, requestId, code, message, lang = ''):
"""
Helper method to send a FXP_STATUS message.
"""
data = requestId + struct.pack('!L', code)
data += NS(message)
data += NS(lang)
self.sendPacket(FXP_STATUS, data)
class FileTransferClient(FileTransferBase):
def __init__(self, extData = {}):
"""
@param extData: a dict of extended_name : extended_data items
to be sent to the server.
"""
FileTransferBase.__init__(self)
self.extData = {}
self.counter = 0
self.openRequests = {} # id -> Deferred
self.wasAFile = {} # Deferred -> 1 TERRIBLE HACK
def connectionMade(self):
data = struct.pack('!L', max(self.versions))
for k,v in self.extData.itervalues():
data += NS(k) + NS(v)
self.sendPacket(FXP_INIT, data)
def _sendRequest(self, msg, data):
data = struct.pack('!L', self.counter) + data
d = defer.Deferred()
self.openRequests[self.counter] = d
self.counter += 1
self.sendPacket(msg, data)
return d
def _parseRequest(self, data):
(id,) = struct.unpack('!L', data[:4])
d = self.openRequests[id]
del self.openRequests[id]
return d, data[4:]
def openFile(self, filename, flags, attrs):
"""
Open a file.
This method returns a L{Deferred} that is called back with an object
that provides the L{ISFTPFile} interface.
@param filename: a string representing the file to open.
@param flags: a integer of the flags to open the file with, ORed together.
The flags and their values are listed at the bottom of this file.
@param attrs: a list of attributes to open the file with. It is a
dictionary, consisting of 0 or more keys. The possible keys are::
size: the size of the file in bytes
uid: the user ID of the file as an integer
gid: the group ID of the file as an integer
permissions: the permissions of the file with as an integer.
the bit representation of this field is defined by POSIX.
atime: the access time of the file as seconds since the epoch.
mtime: the modification time of the file as seconds since the epoch.
ext_*: extended attributes. The server is not required to
understand this, but it may.
NOTE: there is no way to indicate text or binary files. it is up
to the SFTP client to deal with this.
"""
data = NS(filename) + struct.pack('!L', flags) + self._packAttributes(attrs)
d = self._sendRequest(FXP_OPEN, data)
self.wasAFile[d] = (1, filename) # HACK
return d
def removeFile(self, filename):
"""
Remove the given file.
This method returns a Deferred that is called back when it succeeds.
@param filename: the name of the file as a string.
"""
return self._sendRequest(FXP_REMOVE, NS(filename))
def renameFile(self, oldpath, newpath):
"""
Rename the given file.
This method returns a Deferred that is called back when it succeeds.
@param oldpath: the current location of the file.
@param newpath: the new file name.
"""
return self._sendRequest(FXP_RENAME, NS(oldpath)+NS(newpath))
def makeDirectory(self, path, attrs):
"""
Make a directory.
This method returns a Deferred that is called back when it is
created.
@param path: the name of the directory to create as a string.
@param attrs: a dictionary of attributes to create the directory
with. Its meaning is the same as the attrs in the openFile method.
"""
return self._sendRequest(FXP_MKDIR, NS(path)+self._packAttributes(attrs))
def removeDirectory(self, path):
"""
Remove a directory (non-recursively)
It is an error to remove a directory that has files or directories in
it.
This method returns a Deferred that is called back when it is removed.
@param path: the directory to remove.
"""
return self._sendRequest(FXP_RMDIR, NS(path))
def openDirectory(self, path):
"""
Open a directory for scanning.
This method returns a Deferred that is called back with an iterable
object that has a close() method.
The close() method is called when the client is finished reading
from the directory. At this point, the iterable will no longer
be used.
The iterable returns triples of the form (filename, longname, attrs)
or a Deferred that returns the same. The sequence must support
__getitem__, but otherwise may be any 'sequence-like' object.
filename is the name of the file relative to the directory.
logname is an expanded format of the filename. The recommended format
is:
-rwxr-xr-x 1 mjos staff 348911 Mar 25 14:29 t-filexfer
1234567890 123 12345678 12345678 12345678 123456789012
The first line is sample output, the second is the length of the field.
The fields are: permissions, link count, user owner, group owner,
size in bytes, modification time.
attrs is a dictionary in the format of the attrs argument to openFile.
@param path: the directory to open.
"""
d = self._sendRequest(FXP_OPENDIR, NS(path))
self.wasAFile[d] = (0, path)
return d
def getAttrs(self, path, followLinks=0):
"""
Return the attributes for the given path.
This method returns a dictionary in the same format as the attrs
argument to openFile or a Deferred that is called back with same.
@param path: the path to return attributes for as a string.
@param followLinks: a boolean. if it is True, follow symbolic links
and return attributes for the real path at the base. if it is False,
return attributes for the specified path.
"""
if followLinks: m = FXP_STAT
else: m = FXP_LSTAT
return self._sendRequest(m, NS(path))
def setAttrs(self, path, attrs):
"""
Set the attributes for the path.
This method returns when the attributes are set or a Deferred that is
called back when they are.
@param path: the path to set attributes for as a string.
@param attrs: a dictionary in the same format as the attrs argument to
openFile.
"""
data = NS(path) + self._packAttributes(attrs)
return self._sendRequest(FXP_SETSTAT, data)
def readLink(self, path):
"""
Find the root of a set of symbolic links.
This method returns the target of the link, or a Deferred that
returns the same.
@param path: the path of the symlink to read.
"""
d = self._sendRequest(FXP_READLINK, NS(path))
return d.addCallback(self._cbRealPath)
def makeLink(self, linkPath, targetPath):
"""
Create a symbolic link.
This method returns when the link is made, or a Deferred that
returns the same.
@param linkPath: the pathname of the symlink as a string
@param targetPath: the path of the target of the link as a string.
"""
return self._sendRequest(FXP_SYMLINK, NS(linkPath)+NS(targetPath))
def realPath(self, path):
"""
Convert any path to an absolute path.
This method returns the absolute path as a string, or a Deferred
that returns the same.
@param path: the path to convert as a string.
"""
d = self._sendRequest(FXP_REALPATH, NS(path))
return d.addCallback(self._cbRealPath)
def _cbRealPath(self, result):
name, longname, attrs = result[0]
return name
def extendedRequest(self, request, data):
"""
Make an extended request of the server.
The method returns a Deferred that is called back with
the result of the extended request.
@param request: the name of the extended request to make.
@param data: any other data that goes along with the request.
"""
return self._sendRequest(FXP_EXTENDED, NS(request) + data)
def packet_VERSION(self, data):
version, = struct.unpack('!L', data[:4])
data = data[4:]
d = {}
while data:
k, data = getNS(data)
v, data = getNS(data)
d[k]=v
self.version = version
self.gotServerVersion(version, d)
def packet_STATUS(self, data):
d, data = self._parseRequest(data)
code, = struct.unpack('!L', data[:4])
data = data[4:]
msg, data = getNS(data)
lang = getNS(data)
if code == FX_OK:
d.callback((msg, lang))
elif code == FX_EOF:
d.errback(EOFError(msg))
elif code == FX_OP_UNSUPPORTED:
d.errback(NotImplementedError(msg))
else:
d.errback(SFTPError(code, msg, lang))
def packet_HANDLE(self, data):
d, data = self._parseRequest(data)
isFile, name = self.wasAFile.pop(d)
if isFile:
cb = ClientFile(self, getNS(data)[0])
else:
cb = ClientDirectory(self, getNS(data)[0])
cb.name = name
d.callback(cb)
def packet_DATA(self, data):
d, data = self._parseRequest(data)
d.callback(getNS(data)[0])
def packet_NAME(self, data):
d, data = self._parseRequest(data)
count, = struct.unpack('!L', data[:4])
data = data[4:]
files = []
for i in range(count):
filename, data = getNS(data)
longname, data = getNS(data)
attrs, data = self._parseAttributes(data)
files.append((filename, longname, attrs))
d.callback(files)
def packet_ATTRS(self, data):
d, data = self._parseRequest(data)
d.callback(self._parseAttributes(data)[0])
def packet_EXTENDED_REPLY(self, data):
d, data = self._parseRequest(data)
d.callback(data)
def gotServerVersion(self, serverVersion, extData):
"""
Called when the client sends their version info.
@param otherVersion: an integer representing the version of the SFTP
protocol they are claiming.
@param extData: a dictionary of extended_name : extended_data items.
These items are sent by the client to indicate additional features.
"""
class ClientFile:
interface.implements(ISFTPFile)
def __init__(self, parent, handle):
self.parent = parent
self.handle = NS(handle)
def close(self):
return self.parent._sendRequest(FXP_CLOSE, self.handle)
def readChunk(self, offset, length):
data = self.handle + struct.pack("!QL", offset, length)
return self.parent._sendRequest(FXP_READ, data)
def writeChunk(self, offset, chunk):
data = self.handle + struct.pack("!Q", offset) + NS(chunk)
return self.parent._sendRequest(FXP_WRITE, data)
def getAttrs(self):
return self.parent._sendRequest(FXP_FSTAT, self.handle)
def setAttrs(self, attrs):
data = self.handle + self.parent._packAttributes(attrs)
return self.parent._sendRequest(FXP_FSTAT, data)
class ClientDirectory:
def __init__(self, parent, handle):
self.parent = parent
self.handle = NS(handle)
self.filesCache = []
def read(self):
d = self.parent._sendRequest(FXP_READDIR, self.handle)
return d
def close(self):
return self.parent._sendRequest(FXP_CLOSE, self.handle)
def __iter__(self):
return self
def next(self):
if self.filesCache:
return self.filesCache.pop(0)
d = self.read()
d.addCallback(self._cbReadDir)
d.addErrback(self._ebReadDir)
return d
def _cbReadDir(self, names):
self.filesCache = names[1:]
return names[0]
def _ebReadDir(self, reason):
reason.trap(EOFError)
def _():
raise StopIteration
self.next = _
return reason
class SFTPError(Exception):
def __init__(self, errorCode, errorMessage, lang = ''):
Exception.__init__(self)
self.code = errorCode
self.message = errorMessage
self.lang = lang
def __str__(self):
return 'SFTPError %s: %s' % (self.code, self.message)
FXP_INIT = 1
FXP_VERSION = 2
FXP_OPEN = 3
FXP_CLOSE = 4
FXP_READ = 5
FXP_WRITE = 6
FXP_LSTAT = 7
FXP_FSTAT = 8
FXP_SETSTAT = 9
FXP_FSETSTAT = 10
FXP_OPENDIR = 11
FXP_READDIR = 12
FXP_REMOVE = 13
FXP_MKDIR = 14
FXP_RMDIR = 15
FXP_REALPATH = 16
FXP_STAT = 17
FXP_RENAME = 18
FXP_READLINK = 19
FXP_SYMLINK = 20
FXP_STATUS = 101
FXP_HANDLE = 102
FXP_DATA = 103
FXP_NAME = 104
FXP_ATTRS = 105
FXP_EXTENDED = 200
FXP_EXTENDED_REPLY = 201
FILEXFER_ATTR_SIZE = 0x00000001
FILEXFER_ATTR_OWNERGROUP = 0x00000002
FILEXFER_ATTR_PERMISSIONS = 0x00000004
FILEXFER_ATTR_ACMODTIME = 0x00000009
FILEXFER_ATTR_EXTENDED = 0x+80000000
FILEXFER_TYPE_REGULAR = 1
FILEXFER_TYPE_DIRECTORY = 2
FILEXFER_TYPE_SYMLINK = 3
FILEXFER_TYPE_SPECIAL = 4
FILEXFER_TYPE_UNKNOWN = 5
FXF_READ = 0x00000001
FXF_WRITE = 0x00000002
FXF_APPEND = 0x00000004
FXF_CREAT = 0x00000008
FXF_TRUNC = 0x00000010
FXF_EXCL = 0x00000020
FXF_TEXT = 0x00000040
FX_OK = 0
FX_EOF = 1
FX_NO_SUCH_FILE = 2
FX_PERMISSION_DENIED = 3
FX_FAILURE = 4
FX_BAD_MESSAGE = 5
FX_NO_CONNECTION = 6
FX_CONNECTION_LOST = 7
FX_OP_UNSUPPORTED = 8
# http://www.ietf.org/internet-drafts/draft-ietf-secsh-filexfer-12.txt defines
# more useful error codes, but so far OpenSSH doesn't implement them. We use
# them internally for clarity, but for now define them all as FX_FAILURE to be
# compatible with existing software.
FX_FILE_ALREADY_EXISTS = FX_FAILURE
FX_NOT_A_DIRECTORY = FX_FAILURE
FX_FILE_IS_A_DIRECTORY = FX_FAILURE
# initialize FileTransferBase.packetTypes:
g = globals()
for name in g.keys():
if name.startswith('FXP_'):
value = g[name]
FileTransferBase.packetTypes[value] = name[4:]
del g, name, value | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/ssh/filetransfer.py | filetransfer.py |
#
"""This module contains the implementation of the TCP forwarding, which allows
clients and servers to forward arbitrary TCP data across the connection.
This module is unstable.
Maintainer: U{Paul Swartz<mailto:[email protected]>}
"""
import struct
from twisted.internet import protocol, reactor
from twisted.python import log
import common, channel
class SSHListenForwardingFactory(protocol.Factory):
def __init__(self, connection, hostport, klass):
self.conn = connection
self.hostport = hostport # tuple
self.klass = klass
def buildProtocol(self, addr):
channel = self.klass(conn = self.conn)
client = SSHForwardingClient(channel)
channel.client = client
addrTuple = (addr.host, addr.port)
channelOpenData = packOpen_direct_tcpip(self.hostport, addrTuple)
self.conn.openChannel(channel, channelOpenData)
return client
class SSHListenForwardingChannel(channel.SSHChannel):
def channelOpen(self, specificData):
log.msg('opened forwarding channel %s' % self.id)
if len(self.client.buf)>1:
b = self.client.buf[1:]
self.write(b)
self.client.buf = ''
def openFailed(self, reason):
self.closed()
def dataReceived(self, data):
self.client.transport.write(data)
def eofReceived(self):
self.client.transport.loseConnection()
def closed(self):
if hasattr(self, 'client'):
log.msg('closing local forwarding channel %s' % self.id)
self.client.transport.loseConnection()
del self.client
class SSHListenClientForwardingChannel(SSHListenForwardingChannel):
name = 'direct-tcpip'
class SSHListenServerForwardingChannel(SSHListenForwardingChannel):
name = 'forwarded-tcpip'
class SSHConnectForwardingChannel(channel.SSHChannel):
def __init__(self, hostport, *args, **kw):
channel.SSHChannel.__init__(self, *args, **kw)
self.hostport = hostport
self.client = None
self.clientBuf = ''
def channelOpen(self, specificData):
cc = protocol.ClientCreator(reactor, SSHForwardingClient, self)
log.msg("connecting to %s:%i" % self.hostport)
cc.connectTCP(*self.hostport).addCallbacks(self._setClient, self._close)
def _setClient(self, client):
self.client = client
log.msg("connected to %s:%i" % self.hostport)
if self.clientBuf:
self.client.transport.write(self.clientBuf)
self.clientBuf = None
if self.client.buf[1:]:
self.write(self.client.buf[1:])
self.client.buf = ''
def _close(self, reason):
log.msg("failed to connect: %s" % reason)
self.loseConnection()
def dataReceived(self, data):
if self.client:
self.client.transport.write(data)
else:
self.clientBuf += data
def closed(self):
if self.client:
log.msg('closed remote forwarding channel %s' % self.id)
if self.client.channel:
self.loseConnection()
self.client.transport.loseConnection()
del self.client
def openConnectForwardingClient(remoteWindow, remoteMaxPacket, data, avatar):
remoteHP, origHP = unpackOpen_direct_tcpip(data)
return SSHConnectForwardingChannel(remoteHP,
remoteWindow=remoteWindow,
remoteMaxPacket=remoteMaxPacket,
avatar=avatar)
class SSHForwardingClient(protocol.Protocol):
def __init__(self, channel):
self.channel = channel
self.buf = '\000'
def dataReceived(self, data):
if self.buf:
self.buf += data
else:
self.channel.write(data)
def connectionLost(self, reason):
if self.channel:
self.channel.loseConnection()
self.channel = None
def packOpen_direct_tcpip((connHost, connPort), (origHost, origPort)):
"""Pack the data suitable for sending in a CHANNEL_OPEN packet.
"""
conn = common.NS(connHost) + struct.pack('>L', connPort)
orig = common.NS(origHost) + struct.pack('>L', origPort)
return conn + orig
packOpen_forwarded_tcpip = packOpen_direct_tcpip
def unpackOpen_direct_tcpip(data):
"""Unpack the data to a usable format.
"""
connHost, rest = common.getNS(data)
connPort = int(struct.unpack('>L', rest[:4])[0])
origHost, rest = common.getNS(rest[4:])
origPort = int(struct.unpack('>L', rest[:4])[0])
return (connHost, connPort), (origHost, origPort)
unpackOpen_forwarded_tcpip = unpackOpen_direct_tcpip
def packGlobal_tcpip_forward((host, port)):
return common.NS(host) + struct.pack('>L', port)
def unpackGlobal_tcpip_forward(data):
host, rest = common.getNS(data)
port = int(struct.unpack('>L', rest[:4])[0])
return host, port
"""This is how the data -> eof -> close stuff /should/ work.
debug3: channel 1: waiting for connection
debug1: channel 1: connected
debug1: channel 1: read<=0 rfd 7 len 0
debug1: channel 1: read failed
debug1: channel 1: close_read
debug1: channel 1: input open -> drain
debug1: channel 1: ibuf empty
debug1: channel 1: send eof
debug1: channel 1: input drain -> closed
debug1: channel 1: rcvd eof
debug1: channel 1: output open -> drain
debug1: channel 1: obuf empty
debug1: channel 1: close_write
debug1: channel 1: output drain -> closed
debug1: channel 1: rcvd close
debug3: channel 1: will not send data after close
debug1: channel 1: send close
debug1: channel 1: is dead
""" | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/ssh/forwarding.py | forwarding.py |
#
"""Handling of RSA and DSA keys.
This module is unstable.
Maintainer: U{Paul Swartz<mailto:[email protected]>}
"""
# base library imports
import base64
import string
import sha, md5
# external library imports
from Crypto.Cipher import DES3
from Crypto.PublicKey import RSA, DSA
from Crypto import Util
#twisted
from twisted.python import log
# sibling imports
import asn1, common, sexpy
class BadKeyError(Exception):
"""
raised when a key isn't what we expected from it.
XXX: we really need to check for bad keys
"""
def getPublicKeyString(filename = None, line = 0, data = ''):
"""
Return a public key string given a filename or data of a public key.
Currently handles OpenSSH and LSH keys.
@type filename: C{str}
@type line: C{int}
@type data: C{str}
@rtype: C{str}
"""
if filename:
lines = open(filename).readlines()
data = lines[line]
if data[0] == '{': # lsh key
return getPublicKeyString_lsh(data)
elif data.startswith('ssh-'): # openssh key
return getPublicKeyString_openssh(data)
else:
raise BadKeyError('unknown type of key')
def getPublicKeyString_lsh(data):
sexp = sexpy.parse(base64.decodestring(data[1:-1]))
assert sexp[0] == 'public-key'
kd = {}
for name, data in sexp[1][1:]:
kd[name] = common.NS(data)
if sexp[1][0] == 'dsa':
assert len(kd) == 4, len(kd)
return '\x00\x00\x00\x07ssh-dss' + kd['p'] + kd['q'] + kd['g'] + kd['y']
elif sexp[1][0] == 'rsa-pkcs1-sha1':
assert len(kd) == 2, len(kd)
return '\x00\x00\x00\x07ssh-rsa' + kd['e'] + kd['n']
else:
raise BadKeyError('unknown lsh key type %s' % sexp[1][0])
def getPublicKeyString_openssh(data):
fileKind, fileData = data.split()[:2]
# if fileKind != kind:
# raise BadKeyError, 'key should be %s but instead is %s' % (kind, fileKind)
return base64.decodestring(fileData)
def makePublicKeyString(obj, comment = '', kind = 'openssh'):
"""
Return an public key given a C{Crypto.PublicKey.pubkey.pubkey}
object.
kind is one of ('openssh', 'lsh')
@type obj: C{Crypto.PublicKey.pubkey.pubkey}
@type comment: C{str}
@type kind: C{str}
@rtype: C{str}
"""
if kind == 'lsh':
return makePublicKeyString_lsh(obj) # no comment
elif kind == 'openssh':
return makePublicKeyString_openssh(obj, comment)
else:
raise BadKeyError('bad kind %s' % kind)
def makePublicKeyString_lsh(obj):
keyType = objectType(obj)
if keyType == 'ssh-rsa':
keyData = sexpy.pack([['public-key', ['rsa-pkcs1-sha1',
['n', common.MP(obj.n)[4:]],
['e', common.MP(obj.e)[4:]]]]])
elif keyType == 'ssh-dss':
keyData = sexpy.pack([['public-key', ['dsa',
['p', common.MP(obj.p)[4:]],
['q', common.MP(obj.q)[4:]],
['g', common.MP(obj.g)[4:]],
['y', common.MP(obj.y)[4:]]]]])
else:
raise BadKeyError('bad keyType %s' % keyType)
return '{' + base64.encodestring(keyData).replace('\n','') + '}'
def makePublicKeyString_openssh(obj, comment):
keyType = objectType(obj)
if keyType == 'ssh-rsa':
keyData = common.MP(obj.e) + common.MP(obj.n)
elif keyType == 'ssh-dss':
keyData = common.MP(obj.p)
keyData += common.MP(obj.q)
keyData += common.MP(obj.g)
keyData += common.MP(obj.y)
else:
raise BadKeyError('unknown key type %s' % keyType)
b64Data = base64.encodestring(common.NS(keyType)+keyData).replace('\n', '')
return '%s %s %s' % (keyType, b64Data, comment)
def getPublicKeyObject(data):
"""
Return a C{Crypto.PublicKey.pubkey.pubkey} corresponding to the SSHv2
public key data. data is in the over-the-wire public key format.
@type data: C{str}
@rtype: C{Crypto.PublicKey.pubkey.pubkey}
"""
keyKind, rest = common.getNS(data)
if keyKind == 'ssh-rsa':
e, rest = common.getMP(rest)
n, rest = common.getMP(rest)
return RSA.construct((n, e))
elif keyKind == 'ssh-dss':
p, rest = common.getMP(rest)
q, rest = common.getMP(rest)
g, rest = common.getMP(rest)
y, rest = common.getMP(rest)
return DSA.construct((y, g, p, q))
else:
raise BadKeyError('unknown key type %s' % keyKind)
def getPrivateKeyObject(filename = None, data = '', passphrase = ''):
"""
Return a C{Crypto.PublicKey.pubkey.pubkey} object corresponding to the
private key file/data. If the private key is encrypted, passphrase B{must}
be specified, other wise a L{BadKeyError} will be raised.
@type filename: C{str}
@type data: C{str}
@type passphrase: C{str}
@raises BadKeyError: if the key is invalid or a passphrase is not specified
"""
if filename:
data = open(filename).readlines()
else:
data = [x+'\n' for x in data.split('\n')]
if data[0][0] == '(': # lsh key
return getPrivateKeyObject_lsh(data, passphrase)
elif data[0].startswith('-----'): # openssh key
return getPrivateKeyObject_openssh(data, passphrase)
elif data[0].startswith('ssh-'): # agent v3 private key
return getPrivateKeyObject_agentv3(data, passphrase)
else:
raise BadKeyError('unknown private key type')
def getPrivateKeyObject_lsh(data, passphrase):
#assert passphrase == ''
data = ''.join(data)
sexp = sexpy.parse(data)
assert sexp[0] == 'private-key'
kd = {}
for name, data in sexp[1][1:]:
kd[name] = common.getMP(common.NS(data))[0]
if sexp[1][0] == 'dsa':
assert len(kd) == 5, len(kd)
return DSA.construct((kd['y'], kd['g'], kd['p'], kd['q'], kd['x']))
elif sexp[1][0] == 'rsa-pkcs1':
assert len(kd) == 8, len(kd)
return RSA.construct((kd['n'], kd['e'], kd['d'], kd['p'], kd['q']))
else:
raise BadKeyError('unknown lsh key type %s' % sexp[1][0])
def getPrivateKeyObject_openssh(data, passphrase):
kind = data[0][11: 14]
if data[1].startswith('Proc-Type: 4,ENCRYPTED'): # encrypted key
ivdata = data[2].split(',')[1][:-1]
iv = ''.join([chr(int(ivdata[i:i+2],16)) for i in range(0, len(ivdata), 2)])
if not passphrase:
raise BadKeyError, 'encrypted key with no passphrase'
ba = md5.new(passphrase + iv).digest()
bb = md5.new(ba + passphrase + iv).digest()
decKey = (ba + bb)[:24]
b64Data = base64.decodestring(''.join(data[4:-1]))
keyData = DES3.new(decKey, DES3.MODE_CBC, iv).decrypt(b64Data)
removeLen = ord(keyData[-1])
keyData = keyData[:-removeLen]
else:
keyData = base64.decodestring(''.join(data[1:-1]))
try:
decodedKey = asn1.parse(keyData)
except Exception, e:
raise BadKeyError, 'something wrong with decode'
if type(decodedKey[0]) == type([]):
decodedKey = decodedKey[0] # this happens with encrypted keys
if kind == 'RSA':
n,e,d,p,q=decodedKey[1:6]
return RSA.construct((n,e,d,p,q))
elif kind == 'DSA':
p, q, g, y, x = decodedKey[1: 6]
return DSA.construct((y, g, p, q, x))
def getPrivateKeyObject_agentv3(data, passphrase):
if passphrase:
raise BadKeyError("agent v3 key should not be encrypted")
keyType, data = common.getNS(data)
if keyType == 'ssh-dss':
p, data = common.getMP(data)
q, data = common.getMP(data)
g, data = common.getMP(data)
y, data = common.getMP(data)
x, data = common.getMP(data)
return DSA.construct((y,g,p,q,x))
elif keyType == 'ssh-rsa':
e, data = common.getMP(data)
d, data = common.getMP(data)
n, data = common.getMP(data)
u, data = common.getMP(data)
p, data = common.getMP(data)
q, data = common.getMP(data)
return RSA.construct((n,e,d,p,q,u))
else:
raise BadKeyError("unknown key type %s" % keyType)
def makePrivateKeyString(obj, passphrase = None, kind = 'openssh'):
"""
Return an OpenSSH-style private key for a
C{Crypto.PublicKey.pubkey.pubkey} object. If passphrase is given, encrypt
the private key with it.
kind is one of ('openssh', 'lsh', 'agentv3')
@type obj: C{Crypto.PublicKey.pubkey.pubkey}
@type passphrase: C{str}/C{None}
@type kind: C{str}
@rtype: C{str}
"""
if kind == 'lsh':
return makePrivateKeyString_lsh(obj, passphrase)
elif kind == 'openssh':
return makePrivateKeyString_openssh(obj, passphrase)
elif kind == 'agentv3':
return makePrivateKeyString_agentv3(obj, passphrase)
else:
raise BadKeyError('bad kind %s' % kind)
def makePrivateKeyString_lsh(obj, passphrase):
if passphrase:
raise BadKeyError("cannot encrypt to lsh format")
keyType = objectType(obj)
if keyType == 'ssh-rsa':
p,q=obj.p,obj.q
if p > q:
(p,q)=(q,p)
return sexpy.pack([['private-key', ['rsa-pkcs1',
['n', common.MP(obj.n)[4:]],
['e', common.MP(obj.e)[4:]],
['d', common.MP(obj.d)[4:]],
['p', common.MP(q)[4:]],
['q', common.MP(p)[4:]],
['a', common.MP(obj.d%(q-1))[4:]],
['b', common.MP(obj.d%(p-1))[4:]],
['c', common.MP(Util.number.inverse(p, q))[4:]]]]])
elif keyType == 'ssh-dss':
return sexpy.pack([['private-key', ['dsa',
['p', common.MP(obj.p)[4:]],
['q', common.MP(obj.q)[4:]],
['g', common.MP(obj.g)[4:]],
['y', common.MP(obj.y)[4:]],
['x', common.MP(obj.x)[4:]]]]])
else:
raise BadKeyError('bad keyType %s' % keyType)
def makePrivateKeyString_openssh(obj, passphrase):
keyType = objectType(obj)
if keyType == 'ssh-rsa':
keyData = '-----BEGIN RSA PRIVATE KEY-----\n'
p,q=obj.p,obj.q
if p > q:
(p,q) = (q,p)
# p is less than q
objData = [0, obj.n, obj.e, obj.d, q, p, obj.d%(q-1), obj.d%(p-1),Util.number.inverse(p, q)]
elif keyType == 'ssh-dss':
keyData = '-----BEGIN DSA PRIVATE KEY-----\n'
objData = [0, obj.p, obj.q, obj.g, obj.y, obj.x]
else:
raise BadKeyError('unknown key type %s' % keyType)
if passphrase:
iv = common.entropy.get_bytes(8)
hexiv = ''.join(['%02X' % ord(x) for x in iv])
keyData += 'Proc-Type: 4,ENCRYPTED\n'
keyData += 'DEK-Info: DES-EDE3-CBC,%s\n\n' % hexiv
ba = md5.new(passphrase + iv).digest()
bb = md5.new(ba + passphrase + iv).digest()
encKey = (ba + bb)[:24]
asn1Data = asn1.pack([objData])
if passphrase:
padLen = 8 - (len(asn1Data) % 8)
asn1Data += (chr(padLen) * padLen)
asn1Data = DES3.new(encKey, DES3.MODE_CBC, iv).encrypt(asn1Data)
b64Data = base64.encodestring(asn1Data).replace('\n','')
b64Data = '\n'.join([b64Data[i:i+64] for i in range(0,len(b64Data),64)])
keyData += b64Data + '\n'
if keyType == 'ssh-rsa':
keyData += '-----END RSA PRIVATE KEY-----'
elif keyType == 'ssh-dss':
keyData += '-----END DSA PRIVATE KEY-----'
return keyData
def makePrivateKeyString_agentv3(obj, passphrase):
if passphrase:
raise BadKeyError("cannot encrypt to agent v3 format")
keyType = objectType(obj)
if keyType == 'ssh-rsa':
values = (obj.e, obj.d, obj.n, obj.u, obj.p, obj.q)
elif keyType == 'ssh-dss':
values = (obj.p, obj.q, obj.g, obj.y, obj.x)
return common.NS(keytype) + ''.join(map(common.MP, values))
def makePublicKeyBlob(obj):
keyType = objectType(obj)
if keyType == 'ssh-rsa':
keyData = common.MP(obj.e) + common.MP(obj.n)
elif keyType == 'ssh-dss':
keyData = common.MP(obj.p)
keyData += common.MP(obj.q)
keyData += common.MP(obj.g)
keyData += common.MP(obj.y)
return common.NS(keyType)+keyData
def makePrivateKeyBlob(obj):
keyType = objectType(obj)
if keyType == 'ssh-rsa':
return common.NS(keyType) + common.MP(obj.n) + common.MP(obj.e) + \
common.MP(obj.d) + common.MP(obj.u) + common.MP(obj.q) + \
common.MP(obj.p)
elif keyType == 'ssh-dss':
return common.NS(keyType) + common.MP(obj.p) + common.MP(obj.q) + \
common.MP(obj.g) + common.MP(obj.y) + common.MP(obj.x)
else:
raise ValueError('trying to get blob for invalid key type: %s' % keyType)
def objectType(obj):
"""
Return the SSH key type corresponding to a C{Crypto.PublicKey.pubkey.pubkey}
object.
@type obj: C{Crypto.PublicKey.pubkey.pubkey}
@rtype: C{str}
"""
keyDataMapping = {
('n', 'e', 'd', 'p', 'q'): 'ssh-rsa',
('n', 'e', 'd', 'p', 'q', 'u'): 'ssh-rsa',
('y', 'g', 'p', 'q', 'x'): 'ssh-dss'
}
return keyDataMapping[tuple(obj.keydata)]
def pkcs1Pad(data, lMod):
lenPad = lMod-2-len(data)
return '\x01'+('\xff'*lenPad)+'\x00'+data
def pkcs1Digest(data, lMod):
digest = sha.new(data).digest()
return pkcs1Pad(ID_SHA1+digest, lMod)
def lenSig(obj):
return obj.size()/8
def signData(obj, data):
"""
Sign the data with the given C{Crypto.PublicKey.pubkey.pubkey} object.
@type obj: C{Crypto.PublicKey.pubkey.pubkey}
@type data: C{str}
@rtype: C{str}
"""
mapping = {
'ssh-rsa': signData_rsa,
'ssh-dss': signData_dsa
}
objType = objectType(obj)
return common.NS(objType)+mapping[objType](obj, data)
def signData_rsa(obj, data):
sigData = pkcs1Digest(data, lenSig(obj))
sig = obj.sign(sigData, '')[0]
return common.NS(Util.number.long_to_bytes(sig)) # get around adding the \x00 byte
def signData_dsa(obj, data):
sigData = sha.new(data).digest()
randData = common.entropy.get_bytes(19)
sig = obj.sign(sigData, randData)
# SSH insists that the DSS signature blob be two 160-bit integers
# concatenated together. The sig[0], [1] numbers from obj.sign are just
# numbers, and could be any length from 0 to 160 bits. Make sure they
# are padded out to 160 bits (20 bytes each)
return common.NS(Util.number.long_to_bytes(sig[0], 20) +
Util.number.long_to_bytes(sig[1], 20))
def verifySignature(obj, sig, data):
"""
Verify that the signature for the data is valid.
@type obj: C{Crypto.PublicKey.pubkey.pubkey}
@type sig: C{str}
@type data: C{str}
@rtype: C{bool}
"""
mapping = {
'ssh-rsa': verifySignature_rsa,
'ssh-dss': verifySignature_dsa,
}
objType = objectType(obj)
sigType, sigData = common.getNS(sig)
if objType != sigType: # object and signature are not of same type
return 0
return mapping[objType](obj, sigData, data)
def verifySignature_rsa(obj, sig, data):
sigTuple = [common.getMP(sig)[0]]
return obj.verify(pkcs1Digest(data, lenSig(obj)), sigTuple)
def verifySignature_dsa(obj, sig, data):
sig = common.getNS(sig)[0]
assert(len(sig) == 40)
l = len(sig)/2
sigTuple = map(Util.number.bytes_to_long, [sig[: l], sig[l:]])
return obj.verify(sha.new(data).digest(), sigTuple)
def printKey(obj):
"""
Pretty print a C{Crypto.PublicKey.pubkey.pubkey} object.
@type obj: C{Crypto.PublicKey.pubkey.pubkey}
"""
print '%s %s (%s bits)'%(objectType(obj),
obj.hasprivate()and 'Private Key'or 'Public Key',
obj.size())
for k in obj.keydata:
if hasattr(obj, k):
print 'attr', k
by = common.MP(getattr(obj, k))[4:]
while by:
m = by[: 15]
by = by[15:]
o = ''
for c in m:
o = o+'%02x:'%ord(c)
if len(m) < 15:
o = o[:-1]
print '\t'+o
ID_SHA1 = '\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14' | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/ssh/keys.py | keys.py |
#
"""This module contains the implementation of the ssh-connection service, which
allows access to the shell and port-forwarding.
This module is unstable.
Maintainer: U{Paul Swartz<mailto:[email protected]>}
"""
import struct, types
from twisted.internet import protocol, reactor, defer
from twisted.python import log
from twisted.conch import error
import service, common, session, forwarding
class SSHConnection(service.SSHService):
name = 'ssh-connection'
def __init__(self):
self.localChannelID = 0 # this is the current # to use for channel ID
self.localToRemoteChannel = {} # local channel ID -> remote channel ID
self.channels = {} # local channel ID -> subclass of SSHChannel
self.channelsToRemoteChannel = {} # subclass of SSHChannel ->
# remote channel ID
self.deferreds = {} # local channel -> list of deferreds for pending
# requests or 'global' -> list of deferreds for
# global requests
self.transport = None # gets set later
def serviceStarted(self):
if hasattr(self.transport, 'avatar'):
self.transport.avatar.conn = self
def serviceStopped(self):
map(self.channelClosed, self.channels.values())
# packet methods
def ssh_GLOBAL_REQUEST(self, packet):
requestType, rest = common.getNS(packet)
wantReply, rest = ord(rest[0]), rest[1:]
reply = MSG_REQUEST_FAILURE
data = ''
ret = self.gotGlobalRequest(requestType, rest)
if ret:
reply = MSG_REQUEST_SUCCESS
if type(ret) in (types.TupleType, types.ListType):
data = ret[1]
else:
reply = MSG_REQUEST_FAILURE
if wantReply:
self.transport.sendPacket(reply, data)
def ssh_REQUEST_SUCCESS(self, packet):
data = packet
log.msg('RS')
self.deferreds['global'].pop(0).callback(data)
def ssh_REQUEST_FAILURE(self, packet):
log.msg('RF')
self.deferreds['global'].pop(0).errback(
error.ConchError('global request failed', packet))
def ssh_CHANNEL_OPEN(self, packet):
channelType, rest = common.getNS(packet)
senderChannel, windowSize, maxPacket = struct.unpack('>3L', rest[: 12])
packet = rest[12:]
try:
channel = self.getChannel(channelType, windowSize, maxPacket, packet)
localChannel = self.localChannelID
self.localChannelID+=1
channel.id = localChannel
self.channels[localChannel] = channel
self.channelsToRemoteChannel[channel] = senderChannel
self.localToRemoteChannel[localChannel] = senderChannel
self.transport.sendPacket(MSG_CHANNEL_OPEN_CONFIRMATION,
struct.pack('>4L', senderChannel, localChannel,
channel.localWindowSize,
channel.localMaxPacket)+channel.specificData)
log.callWithLogger(channel, channel.channelOpen, '')
except Exception, e:
log.msg('channel open failed')
log.err(e)
if isinstance(e, error.ConchError):
reason, textualInfo = e.args[0], e.data
else:
reason = OPEN_CONNECT_FAILED
textualInfo = "unknown failure"
self.transport.sendPacket(MSG_CHANNEL_OPEN_FAILURE,
struct.pack('>2L', senderChannel, reason)+ \
common.NS(textualInfo)+common.NS(''))
def ssh_CHANNEL_OPEN_CONFIRMATION(self, packet):
localChannel, remoteChannel, windowSize, maxPacket = struct.unpack('>4L', packet[: 16])
specificData = packet[16:]
channel = self.channels[localChannel]
channel.conn = self
self.localToRemoteChannel[localChannel] = remoteChannel
self.channelsToRemoteChannel[channel] = remoteChannel
channel.remoteWindowLeft = windowSize
channel.remoteMaxPacket = maxPacket
log.callWithLogger(channel, channel.channelOpen, specificData)
def ssh_CHANNEL_OPEN_FAILURE(self, packet):
localChannel, reasonCode = struct.unpack('>2L', packet[: 8])
reasonDesc = common.getNS(packet[8:])[0]
channel = self.channels[localChannel]
del self.channels[localChannel]
channel.conn = self
reason = error.ConchError(reasonDesc, reasonCode)
log.callWithLogger(channel, channel.openFailed, reason)
def ssh_CHANNEL_WINDOW_ADJUST(self, packet):
localChannel, bytesToAdd = struct.unpack('>2L', packet[: 8])
channel = self.channels[localChannel]
log.callWithLogger(channel, channel.addWindowBytes, bytesToAdd)
def ssh_CHANNEL_DATA(self, packet):
localChannel, dataLength = struct.unpack('>2L', packet[: 8])
channel = self.channels[localChannel]
# XXX should this move to dataReceived to put client in charge?
if dataLength > channel.localWindowLeft or \
dataLength > channel.localMaxPacket: # more data than we want
log.callWithLogger(channel, lambda s=self,c=channel:
log.msg('too much data') and s.sendClose(c))
return
#packet = packet[:channel.localWindowLeft+4]
data = common.getNS(packet[4:])[0]
channel.localWindowLeft-=dataLength
if channel.localWindowLeft < channel.localWindowSize/2:
self.adjustWindow(channel, channel.localWindowSize - \
channel.localWindowLeft)
#log.msg('local window left: %s/%s' % (channel.localWindowLeft,
# channel.localWindowSize))
log.callWithLogger(channel, channel.dataReceived, data)
def ssh_CHANNEL_EXTENDED_DATA(self, packet):
localChannel, typeCode, dataLength = struct.unpack('>3L', packet[: 12])
channel = self.channels[localChannel]
if dataLength > channel.localWindowLeft or \
dataLength > channel.localMaxPacket:
log.callWithLogger(channel, lambda s=self,c=channel:
log.msg('too much extdata') and s.sendClose(c))
return
data = common.getNS(packet[8:])[0]
channel.localWindowLeft -= dataLength
if channel.localWindowLeft < channel.localWindowSize/2:
self.adjustWindow(channel, channel.localWindowSize - \
channel.localWindowLeft)
log.callWithLogger(channel, channel.extReceived, typeCode, data)
def ssh_CHANNEL_EOF(self, packet):
localChannel = struct.unpack('>L', packet[: 4])[0]
channel = self.channels[localChannel]
log.callWithLogger(channel, channel.eofReceived)
def ssh_CHANNEL_CLOSE(self, packet):
localChannel = struct.unpack('>L', packet[: 4])[0]
channel = self.channels[localChannel]
if channel.remoteClosed:
return
log.callWithLogger(channel, channel.closeReceived)
channel.remoteClosed = 1
if channel.localClosed and channel.remoteClosed:
self.channelClosed(channel)
def ssh_CHANNEL_REQUEST(self, packet):
localChannel = struct.unpack('>L', packet[: 4])[0]
requestType, rest = common.getNS(packet[4:])
wantReply = ord(rest[0])
channel = self.channels[localChannel]
d = log.callWithLogger(channel, channel.requestReceived, requestType, rest[1:])
if wantReply:
if isinstance(d, defer.Deferred):
d.addCallback(self._cbChannelRequest, localChannel)
d.addErrback(self._ebChannelRequest, localChannel)
elif d:
self._cbChannelRequest(None, localChannel)
else:
self._ebChannelRequest(None, localChannel)
def _cbChannelRequest(self, result, localChannel):
self.transport.sendPacket(MSG_CHANNEL_SUCCESS, struct.pack('>L',
self.localToRemoteChannel[localChannel]))
def _ebChannelRequest(self, result, localChannel):
self.transport.sendPacket(MSG_CHANNEL_FAILURE, struct.pack('>L',
self.localToRemoteChannel[localChannel]))
def ssh_CHANNEL_SUCCESS(self, packet):
localChannel = struct.unpack('>L', packet[: 4])[0]
if self.deferreds.get(localChannel):
d = self.deferreds[localChannel].pop(0)
log.callWithLogger(self.channels[localChannel],
d.callback, packet[4:])
def ssh_CHANNEL_FAILURE(self, packet):
localChannel = struct.unpack('>L', packet[: 4])[0]
if self.deferreds.get(localChannel):
d = self.deferreds[localChannel].pop(0)
log.callWithLogger(self.channels[localChannel],
d.errback,
error.ConchError('channel request failed'))
# methods for users of the connection to call
def sendGlobalRequest(self, request, data, wantReply = 0):
"""
Send a global request for this connection. Current this is only used
for remote->local TCP forwarding.
@type request: C{str}
@type data: C{str}
@type wantReply: C{bool}
@rtype C{Deferred}/C{None}
"""
self.transport.sendPacket(MSG_GLOBAL_REQUEST,
common.NS(request)
+ (wantReply and '\xff' or '\x00')
+ data)
if wantReply:
d = defer.Deferred()
self.deferreds.setdefault('global', []).append(d)
return d
def openChannel(self, channel, extra = ''):
"""
Open a new channel on this connection.
@type channel: subclass of C{SSHChannel}
@type extra: C{str}
"""
log.msg('opening channel %s with %s %s'%(self.localChannelID,
channel.localWindowSize, channel.localMaxPacket))
self.transport.sendPacket(MSG_CHANNEL_OPEN, common.NS(channel.name)
+struct.pack('>3L', self.localChannelID,
channel.localWindowSize, channel.localMaxPacket)
+extra)
channel.id = self.localChannelID
self.channels[self.localChannelID] = channel
self.localChannelID+=1
def sendRequest(self, channel, requestType, data, wantReply = 0):
"""
Send a request to a channel.
@type channel: subclass of C{SSHChannel}
@type requestType: C{str}
@type data: C{str}
@type wantReply: C{bool}
@rtype C{Deferred}/C{None}
"""
if channel.localClosed:
return
log.msg('sending request %s' % requestType)
self.transport.sendPacket(MSG_CHANNEL_REQUEST, struct.pack('>L',
self.channelsToRemoteChannel[channel])
+ common.NS(requestType)+chr(wantReply)
+ data)
if wantReply:
d = defer.Deferred()
self.deferreds.setdefault(channel.id, []).append(d)
return d
def adjustWindow(self, channel, bytesToAdd):
"""
Tell the other side that we will receive more data. This should not
normally need to be called as it is managed automatically.
@type channel: subclass of L{SSHChannel}
@type bytesToAdd: C{int}
"""
if channel.localClosed:
return # we're already closed
self.transport.sendPacket(MSG_CHANNEL_WINDOW_ADJUST, struct.pack('>2L',
self.channelsToRemoteChannel[channel],
bytesToAdd))
log.msg('adding %i to %i in channel %i' % (bytesToAdd, channel.localWindowLeft, channel.id))
channel.localWindowLeft+=bytesToAdd
def sendData(self, channel, data):
"""
Send data to a channel. This should not normally be used: instead use
channel.write(data) as it manages the window automatically.
@type channel: subclass of L{SSHChannel}
@type data: C{str}
"""
if channel.localClosed:
return # we're already closed
self.transport.sendPacket(MSG_CHANNEL_DATA, struct.pack('>L',
self.channelsToRemoteChannel[channel])+ \
common.NS(data))
def sendExtendedData(self, channel, dataType, data):
"""
Send extended data to a channel. This should not normally be used:
instead use channel.writeExtendedData(data, dataType) as it manages
the window automatically.
@type channel: subclass of L{SSHChannel}
@type dataType: C{int}
@type data: C{str}
"""
if channel.localClosed:
return # we're already closed
self.transport.sendPacket(MSG_CHANNEL_EXTENDED_DATA, struct.pack('>2L',
self.channelsToRemoteChannel[channel],dataType) \
+ common.NS(data))
def sendEOF(self, channel):
"""
Send an EOF (End of File) for a channel.
@type channel: subclass of L{SSHChannel}
"""
if channel.localClosed:
return # we're already closed
log.msg('sending eof')
self.transport.sendPacket(MSG_CHANNEL_EOF, struct.pack('>L',
self.channelsToRemoteChannel[channel]))
def sendClose(self, channel):
"""
Close a channel.
@type channel: subclass of L{SSHChannel}
"""
if channel.localClosed:
return # we're already closed
log.msg('sending close %i' % channel.id)
self.transport.sendPacket(MSG_CHANNEL_CLOSE, struct.pack('>L',
self.channelsToRemoteChannel[channel]))
channel.localClosed = 1
if channel.localClosed and channel.remoteClosed:
self.channelClosed(channel)
# methods to override
def getChannel(self, channelType, windowSize, maxPacket, data):
"""
The other side requested a channel of some sort.
channelType is the type of channel being requested,
windowSize is the initial size of the remote window,
maxPacket is the largest packet we should send,
data is any other packet data (often nothing).
We return a subclass of L{SSHChannel}.
By default, this dispatches to a method 'channel_channelType' with any
non-alphanumerics in the channelType replace with _'s. If it cannot
find a suitable method, it returns an OPEN_UNKNOWN_CHANNEL_TYPE error.
The method is called with arguments of windowSize, maxPacket, data.
@type channelType: C{str}
@type windowSize: C{int}
@type maxPacket: C{int}
@type data: C{str}
@rtype: subclass of L{SSHChannel}/C{tuple}
"""
log.msg('got channel %s request' % channelType)
if hasattr(self.transport, "avatar"): # this is a server!
chan = self.transport.avatar.lookupChannel(channelType,
windowSize,
maxPacket,
data)
chan.conn = self
return chan
else:
channelType = channelType.translate(TRANSLATE_TABLE)
f = getattr(self, 'channel_%s' % channelType, None)
if not f:
return OPEN_UNKNOWN_CHANNEL_TYPE, "don't know that channel"
return f(windowSize, maxPacket, data)
def gotGlobalRequest(self, requestType, data):
"""
We got a global request. pretty much, this is just used by the client
to request that we forward a port from the server to the client.
Returns either:
- 1: request accepted
- 1, <data>: request accepted with request specific data
- 0: request denied
By default, this dispatches to a method 'global_requestType' with
-'s in requestType replaced with _'s. The found method is passed data.
If this method cannot be found, this method returns 0. Otherwise, it
returns the return value of that method.
@type requestType: C{str}
@type data: C{str}
@rtype: C{int}/C{tuple}
"""
log.msg('got global %s request' % requestType)
if hasattr(self.transport, 'avatar'): # this is a server!
return self.transport.avatar.gotGlobalRequest(requestType, data)
requestType = requestType.replace('-','_')
f = getattr(self, 'global_%s' % requestType, None)
if not f:
return 0
return f(data)
def channelClosed(self, channel):
"""
Called when a channel is closed.
It clears the local state related to the channel, and calls
channel.closed().
MAKE SURE YOU CALL THIS METHOD, even if you subclass L{SSHConnection}.
If you don't, things will break mysteriously.
"""
channel.localClosed = channel.remoteClosed = 1
del self.localToRemoteChannel[channel.id]
del self.channels[channel.id]
del self.channelsToRemoteChannel[channel]
self.deferreds[channel.id] = []
log.callWithLogger(channel, channel.closed)
MSG_GLOBAL_REQUEST = 80
MSG_REQUEST_SUCCESS = 81
MSG_REQUEST_FAILURE = 82
MSG_CHANNEL_OPEN = 90
MSG_CHANNEL_OPEN_CONFIRMATION = 91
MSG_CHANNEL_OPEN_FAILURE = 92
MSG_CHANNEL_WINDOW_ADJUST = 93
MSG_CHANNEL_DATA = 94
MSG_CHANNEL_EXTENDED_DATA = 95
MSG_CHANNEL_EOF = 96
MSG_CHANNEL_CLOSE = 97
MSG_CHANNEL_REQUEST = 98
MSG_CHANNEL_SUCCESS = 99
MSG_CHANNEL_FAILURE = 100
OPEN_ADMINISTRATIVELY_PROHIBITED = 1
OPEN_CONNECT_FAILED = 2
OPEN_UNKNOWN_CHANNEL_TYPE = 3
OPEN_RESOURCE_SHORTAGE = 4
EXTENDED_DATA_STDERR = 1
messages = {}
import connection
for v in dir(connection):
if v[: 4] == 'MSG_':
messages[getattr(connection, v)] = v # doesn't handle doubles
import string
alphanums = string.letters + string.digits
TRANSLATE_TABLE = ''.join([chr(i) in alphanums and chr(i) or '_' for i in range(256)])
SSHConnection.protocolMessages = messages | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/ssh/connection.py | connection.py |
#
"""The parent class for all the SSH Channels. Currently implemented channels
are session. direct-tcp, and forwarded-tcp.
This module is unstable.
Maintainer: U{Paul Swartz<mailto:[email protected]>}
"""
from twisted.python import log, context
class SSHChannel(log.Logger):
name = None # only needed for client channels
def __init__(self, localWindow = 0, localMaxPacket = 0,
remoteWindow = 0, remoteMaxPacket = 0,
conn = None, data=None, avatar = None):
self.localWindowSize = localWindow or 131072
self.localWindowLeft = self.localWindowSize
self.localMaxPacket = localMaxPacket or 32768
self.remoteWindowLeft = remoteWindow
self.remoteMaxPacket = remoteMaxPacket
self.areWriting = 1
self.conn = conn
self.data = data
self.avatar = avatar
self.specificData = ''
self.buf = ''
self.extBuf = []
self.closing = 0
self.localClosed = 0
self.remoteClosed = 0
self.id = None # gets set later by SSHConnection
def __str__(self):
return '%s (lw %i rw %i)' % (self.name, self.localWindowLeft, self.remoteWindowLeft)
def logPrefix(self):
id = (self.id is not None and str(self.id)) or "unknown"
return "SSHChannel %s (%s) on %s" % (self.name, id, self.conn.logPrefix())
def channelOpen(self, specificData):
"""
Called when the channel is opened. specificData is any data that the
other side sent us when opening the channel.
@type specificData: C{str}
"""
log.msg('channel open')
def openFailed(self, reason):
"""
Called when the the open failed for some reason.
reason.desc is a string descrption, reason.code the the SSH error code.
@type reason: L{error.ConchError}
"""
log.msg('other side refused open\nreason: %s'% reason)
def addWindowBytes(self, bytes):
"""
Called when bytes are added to the remote window. By default it clears
the data buffers.
@type bytes: C{int}
"""
self.remoteWindowLeft = self.remoteWindowLeft+bytes
if not self.areWriting and not self.closing:
self.areWriting = 0
self.startWriting()
if self.buf:
b = self.buf
self.buf = ''
self.write(b)
if self.extBuf:
b = self.extBuf
self.extBuf = []
for i in b:
self.writeExtended(*i)
def requestReceived(self, requestType, data):
"""
Called when a request is sent to this channel. By default it delegates
to self.request_<requestType>.
If this function returns true, the request succeeded, otherwise it
failed.
@type requestType: C{str}
@type data: C{str}
@rtype: C{bool}
"""
foo = requestType.replace('-', '_')
f = getattr(self, 'request_%s'%foo, None)
if f:
return f(data)
log.msg('unhandled request for %s'%requestType)
return 0
def dataReceived(self, data):
"""
Called when we receive data.
@type data: C{str}
"""
log.msg('got data %s'%repr(data))
def extReceived(self, dataType, data):
"""
Called when we receive extended data (usually standard error).
@type dataType: C{int}
@type data: C{str}
"""
log.msg('got extended data %s %s'%(dataType, repr(data)))
def eofReceived(self):
"""
Called when the other side will send no more data.
"""
log.msg('remote eof')
def closeReceived(self):
"""
Called when the other side has closed the channel.
"""
log.msg('remote close')
self.loseConnection()
def closed(self):
"""
Called when the channel is closed. This means that both our side and
the remote side have closed the channel.
"""
log.msg('closed')
# transport stuff
def write(self, data):
"""
Write some data to the channel. If there is not enough remote window
available, buffer until it is.
@type data: C{str}
"""
#if not data: return
if self.buf:
self.buf += data
return
top = len(data)
if top > self.remoteWindowLeft:
data, self.buf = data[:self.remoteWindowLeft], data[self.remoteWindowLeft:]
self.areWriting = 0
self.stopWriting()
top = self.remoteWindowLeft
rmp = self.remoteMaxPacket
write = self.conn.sendData
r = range(0, top, rmp)
for offset in r:
write(self, data[offset: offset+rmp])
self.remoteWindowLeft-=top
if self.closing and not self.buf:
self.loseConnection() # try again
def writeExtended(self, dataType, data):
"""
Send extended data to this channel. If there is not enough remote
window available, buffer until there is.
@type dataType: C{int}
@type data: C{str}
"""
if self.extBuf:
if self.extBuf[-1][0] == dataType:
self.extBuf[-1][1]+=data
else:
self.extBuf.append([dataType, data])
return
if len(data) > self.remoteWindowLeft:
data, self.extBuf = data[:self.remoteWindowLeft], \
[[dataType, data[self.remoteWindowLeft:]]]
self.areWriting = 0
self.stopWriting()
if not data: return
while len(data) > self.remoteMaxPacket:
self.conn.sendExtendedData(self, dataType,
data[:self.remoteMaxPacket])
data = data[self.remoteMaxPacket:]
self.remoteWindowLeft-=self.remoteMaxPacket
if data:
self.conn.sendExtendedData(self, dataType, data)
self.remoteWindowLeft-=len(data)
if self.closing:
self.loseConnection() # try again
def writeSequence(self, data):
"""
Part of the Transport interface. Write a list of strings to the
channel.
@type data: C{list} of C{str}
"""
self.write(''.join(data))
def loseConnection(self):
"""
Close the channel.
"""
self.closing = 1
if not self.buf and not self.extBuf:
self.conn.sendClose(self)
def getPeer(self):
"""
Return a tuple describing the other side of the connection.
@rtype: C{tuple}
"""
return('SSH', )+self.conn.transport.getPeer()
def getHost(self):
"""
Return a tuple describing our side of the connection.
@rtype: C{tuple}
"""
return('SSH', )+self.conn.transport.getHost()
def stopWriting(self):
"""
Called when the remote buffer is full, as a hint to stop writing.
This can be ignored, but it can be helpful.
"""
def startWriting(self):
"""
Called when the remote buffer has more room, as a hint to continue
writing.
""" | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/ssh/channel.py | channel.py |
#
"""The lowest level SSH protocol. This handles the key negotiation, the encryption and the compression.
This module is unstable.
Maintainer: U{Paul Swartz<mailto:[email protected]>}
"""
from __future__ import nested_scopes
# base library imports
import struct
import md5
import sha
import zlib
import math # for math.log
import array
# external library imports
from Crypto import Util
from Crypto.Cipher import XOR
from Crypto.PublicKey import RSA
from Crypto.Util import randpool
# twisted imports
from twisted.conch import error
from twisted.internet import protocol, defer
from twisted.python import log
# sibling importsa
from common import NS, getNS, MP, getMP, _MPpow, ffs, entropy # ease of use
import keys
class SSHTransportBase(protocol.Protocol):
protocolVersion = '2.0'
version = 'Twisted'
comment = ''
ourVersionString = ('SSH-'+protocolVersion+'-'+version+' '+comment).strip()
supportedCiphers = ['aes256-ctr', 'aes256-cbc', 'aes192-ctr', 'aes192-cbc',
'aes128-ctr', 'aes128-cbc', 'cast128-ctr',
'cast128-cbc', 'blowfish-ctr', 'blowfish', 'idea-ctr'
'idea-cbc', '3des-ctr', '3des-cbc'] # ,'none']
supportedMACs = ['hmac-sha1', 'hmac-md5'] # , 'none']
# both of the above support 'none', but for security are disabled by
# default. to enable them, subclass this class and add it, or do:
# SSHTransportBase.supportedCiphers.append('none')
supportedKeyExchanges = ['diffie-hellman-group-exchange-sha1',
'diffie-hellman-group1-sha1']
supportedPublicKeys = ['ssh-rsa', 'ssh-dss']
supportedCompressions = ['none', 'zlib']
supportedLanguages = ()
gotVersion = 0
ignoreNextPacket = 0
buf = ''
outgoingPacketSequence = 0
incomingPacketSequence = 0
currentEncryptions = None
outgoingCompression = None
incomingCompression = None
sessionID = None
isAuthorized = 0
service = None
def connectionLost(self, reason):
if self.service:
self.service.serviceStopped()
if hasattr(self, 'avatar'):
self.logoutFunction()
log.msg('connection lost')
def connectionMade(self):
self.transport.write('%s\r\n'%(self.ourVersionString))
self.sendKexInit()
def sendKexInit(self):
self.ourKexInitPayload = chr(MSG_KEXINIT)+entropy.get_bytes(16)+ \
NS(','.join(self.supportedKeyExchanges))+ \
NS(','.join(self.supportedPublicKeys))+ \
NS(','.join(self.supportedCiphers))+ \
NS(','.join(self.supportedCiphers))+ \
NS(','.join(self.supportedMACs))+ \
NS(','.join(self.supportedMACs))+ \
NS(','.join(self.supportedCompressions))+ \
NS(','.join(self.supportedCompressions))+ \
NS(','.join(self.supportedLanguages))+ \
NS(','.join(self.supportedLanguages))+ \
'\000'+'\000\000\000\000'
self.sendPacket(MSG_KEXINIT, self.ourKexInitPayload[1:])
def sendPacket(self, messageType, payload):
payload = chr(messageType)+payload
if self.outgoingCompression:
payload = self.outgoingCompression.compress(payload) + self.outgoingCompression.flush(2)
if self.currentEncryptions:
bs = self.currentEncryptions.enc_block_size
else:
bs = 8
totalSize = 5+len(payload)
lenPad = bs-(totalSize%bs)
if lenPad < 4:
lenPad = lenPad+bs
packet = struct.pack('!LB', totalSize+lenPad-4, lenPad)+ \
payload+entropy.get_bytes(lenPad)
assert len(packet)%bs == 0, '%s extra bytes in packet'%(len(packet)%bs)
if self.currentEncryptions:
encPacket = self.currentEncryptions.encrypt(packet) + self.currentEncryptions.makeMAC(self.outgoingPacketSequence, packet)
else:
encPacket = packet
self.transport.write(encPacket)
self.outgoingPacketSequence+=1
def getPacket(self):
bs = self.currentEncryptions and self.currentEncryptions.dec_block_size or 8
ms = self.currentEncryptions and self.currentEncryptions.verify_digest_size or 0
if len(self.buf) < bs: return # not enough data
if not hasattr(self, 'first'):
if self.currentEncryptions:
first = self.currentEncryptions.decrypt(self.buf[: bs])
else:
first = self.buf[: bs]
else:
first = self.first
del self.first
packetLen, randomLen = struct.unpack('!LB', first[: 5])
if packetLen > 1048576: # 1024 ** 2
self.sendDisconnect(DISCONNECT_PROTOCOL_ERROR, 'bad packet length %s'%packetLen)
return
if len(self.buf) < packetLen+4+ms:
self.first = first
return # not enough packet
if(packetLen+4)%bs != 0:
self.sendDisconnect(DISCONNECT_PROTOCOL_ERROR, 'bad packet mod (%s%%%s == %s'%(packetLen+4, bs, (packetLen+4)%bs))
return
encData, self.buf = self.buf[: 4+packetLen], self.buf[4+packetLen:]
if self.currentEncryptions:
packet = first+self.currentEncryptions.decrypt(encData[bs:])
else:
packet = encData
if len(packet) != 4+packetLen:
self.sendDisconnect(DISCONNECT_PROTOCOL_ERROR, 'bad packet length')
return
if ms:
macData, self.buf = self.buf[:ms], self.buf[ms:]
if not self.currentEncryptions.verify(self.incomingPacketSequence, packet, macData):
self.sendDisconnect(DISCONNECT_MAC_ERROR, 'bad MAC')
return
payload = packet[5: 4+packetLen-randomLen]
if self.incomingCompression:
try:
payload = self.incomingCompression.decompress(payload)
except zlib.error:
self.sendDisconnect(DISCONNECT_COMPRESSION_ERROR, 'compression error')
return
self.incomingPacketSequence+=1
return payload
def dataReceived(self, data):
self.buf = self.buf+data
if not self.gotVersion:
parts = self.buf.split('\n')
for p in parts:
if p[: 4] == 'SSH-':
self.gotVersion = 1
self.otherVersionString = p.strip()
if p.split('-')[1]not in('1.99', '2.0'): # bad version
self.sendDisconnect(DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED, 'bad version %s'%p.split('-')[1])
return
i = parts.index(p)
self.buf = '\n'.join(parts[i+1:])
packet = self.getPacket()
while packet:
messageNum = ord(packet[0])
if messageNum < 50:
messageType = messages[messageNum][4:]
f = getattr(self, 'ssh_%s'%messageType, None)
if f:
f(packet[1:])
else:
log.msg("couldn't handle %s"%messageType)
log.msg(repr(packet[1:]))
self.sendUnimplemented()
elif self.service:
log.callWithLogger(self.service, self.service.packetReceived,
ord(packet[0]), packet[1:])
else:
log.msg("couldn't handle %s"%messageNum)
log.msg(repr(packet[1:]))
self.sendUnimplemented()
packet = self.getPacket()
def ssh_DISCONNECT(self, packet):
reasonCode = struct.unpack('>L', packet[: 4])[0]
description, foo = getNS(packet[4:])
self.receiveError(reasonCode, description)
self.transport.loseConnection()
def ssh_IGNORE(self, packet): pass
def ssh_UNIMPLEMENTED(self, packet):
seqnum = struct.unpack('>L', packet)
self.receiveUnimplemented(seqnum)
def ssh_DEBUG(self, packet):
alwaysDisplay = ord(packet[0])
message, lang, foo = getNS(packet, 2)
self.receiveDebug(alwaysDisplay, message, lang)
def setService(self, service):
log.msg('starting service %s'%service.name)
if self.service:
self.service.serviceStopped()
self.service = service
service.transport = self
self.service.serviceStarted()
def sendDebug(self, message, alwaysDisplay = 0, language = ''):
self.sendPacket(MSG_DEBUG, chr(alwaysDisplay)+NS(message)+NS(language))
def sendIgnore(self, message):
self.sendPacket(MSG_IGNORE, NS(message))
def sendUnimplemented(self):
seqnum = self.incomingPacketSequence
self.sendPacket(MSG_UNIMPLEMENTED, struct.pack('!L', seqnum))
def sendDisconnect(self, reason, desc):
self.sendPacket(MSG_DISCONNECT, struct.pack('>L', reason)+NS(desc)+NS(''))
log.msg('Disconnecting with error, code %s\nreason: %s'%(reason, desc))
self.transport.loseConnection()
# client methods
def receiveError(self, reasonCode, description):
log.msg('Got remote error, code %s\nreason: %s'%(reasonCode, description))
def receiveUnimplemented(self, seqnum):
log.msg('other side unimplemented packet #%s'%seqnum)
def receiveDebug(self, alwaysDisplay, message, lang):
if alwaysDisplay:
log.msg('Remote Debug Message:', message)
def isEncrypted(self, direction = "out"):
"""direction must be in ["out", "in", "both"]
"""
if self.currentEncryptions == None:
return 0
elif direction == "out":
return bool(self.currentEncryptions.enc_block_size)
elif direction == "in":
return bool(self.currentEncryptions.dec_block_size)
elif direction == "both":
return self.isEncrypted("in") and self.isEncrypted("out")
else:
raise TypeError, 'direction must be "out", "in", or "both"'
def isVerified(self, direction = "out"):
"""direction must be in ["out", "in", "both"]
"""
if self.currentEncryptions == None:
return 0
elif direction == "out":
return self.currentEncryptions.outMAC != None
elif direction == "in":
return self.currentEncryptions.outCMAC != None
elif direction == "both":
return self.isVerified("in")and self.isVerified("out")
else:
raise TypeError, 'direction must be "out", "in", or "both"'
def loseConnection(self):
self.sendDisconnect(DISCONNECT_CONNECTION_LOST, "user closed connection")
class SSHServerTransport(SSHTransportBase):
isClient = 0
def ssh_KEXINIT(self, packet):
self.clientKexInitPayload = chr(MSG_KEXINIT)+packet
#cookie = packet[: 16] # taking this is useless
k = getNS(packet[16:], 10)
strings, rest = k[:-1], k[-1]
kexAlgs, keyAlgs, encCS, encSC, macCS, macSC, compCS, compSC, langCS, langSC = \
[s.split(',')for s in strings]
if ord(rest[0]): # first_kex_packet_follows
if kexAlgs[0] != self.supportedKeyExchanges[0]or \
keyAlgs[0] != self.supportedPublicKeys[0]or \
not ffs(encSC, self.supportedCiphers)or \
not ffs(encCS, self.supportedCiphers)or \
not ffs(macSC, self.supportedMACs)or \
not ffs(macCS, self.supportedMACs)or \
not ffs(compCS, self.supportedCompressions)or \
not ffs(compSC, self.supportedCompressions):
self.ignoreNextPacket = 1 # guess was wrong
self.kexAlg = ffs(kexAlgs, self.supportedKeyExchanges)
self.keyAlg = ffs(keyAlgs, self.supportedPublicKeys)
self.nextEncryptions = SSHCiphers(
ffs(encSC, self.supportedCiphers),
ffs(encCS, self.supportedCiphers),
ffs(macSC, self.supportedMACs),
ffs(macCS, self.supportedMACs),
)
self.outgoingCompressionType = ffs(compSC, self.supportedCompressions)
self.incomingCompressionType = ffs(compCS, self.supportedCompressions)
if None in(self.kexAlg, self.keyAlg, self.outgoingCompressionType, self.incomingCompressionType):
self.sendDisconnect(DISCONNECT_KEY_EXCHANGE_FAILED, "couldn't match all kex parts")
return
if None in self.nextEncryptions.__dict__.values():
self.sendDisconnect(DISCONNECT_KEY_EXCHANGE_FAILED, "couldn't match all kex parts")
return
log.msg('kex alg, key alg: %s %s'%(self.kexAlg, self.keyAlg))
log.msg('server->client: %s %s %s'%(self.nextEncryptions.outCipType,
self.nextEncryptions.outMacType,
self.outgoingCompressionType))
log.msg('client->server: %s %s %s'%(self.nextEncryptions.inCipType,
self.nextEncryptions.inMacType,
self.incomingCompressionType))
def ssh_KEX_DH_GEX_REQUEST_OLD(self, packet):
if self.ignoreNextPacket:
self.ignoreNextPacket = 0
return
if self.kexAlg == 'diffie-hellman-group1-sha1': # this is really KEXDH_INIT
clientDHPubKey, foo = getMP(packet)
y = Util.number.getRandomNumber(16, entropy.get_bytes)
f = pow(DH_GENERATOR, y, DH_PRIME)
sharedSecret = _MPpow(clientDHPubKey, y, DH_PRIME)
h = sha.new()
h.update(NS(self.otherVersionString))
h.update(NS(self.ourVersionString))
h.update(NS(self.clientKexInitPayload))
h.update(NS(self.ourKexInitPayload))
h.update(NS(self.factory.publicKeys[self.keyAlg]))
h.update(MP(clientDHPubKey))
h.update(MP(f))
h.update(sharedSecret)
exchangeHash = h.digest()
self.sendPacket(MSG_KEXDH_REPLY, NS(self.factory.publicKeys[self.keyAlg])+ \
MP(f)+NS(keys.signData(self.factory.privateKeys[self.keyAlg], exchangeHash)))
self._keySetup(sharedSecret, exchangeHash)
elif self.kexAlg == 'diffie-hellman-group-exchange-sha1':
self.kexAlg = 'diffie-hellman-group-exchange-sha1-old'
self.ideal = struct.unpack('>L', packet)[0]
self.g, self.p = self.factory.getDHPrime(self.ideal)
self.sendPacket(MSG_KEX_DH_GEX_GROUP, MP(self.p)+MP(self.g))
else:
raise error.ConchError('bad kexalg: %s'%self.kexAlg)
def ssh_KEX_DH_GEX_REQUEST(self, packet):
if self.ignoreNextPacket:
self.ignoreNextPacket = 0
return
self.min, self.ideal, self.max = struct.unpack('>3L', packet)
self.g, self.p = self.factory.getDHPrime(self.ideal)
self.sendPacket(MSG_KEX_DH_GEX_GROUP, MP(self.p)+MP(self.g))
def ssh_KEX_DH_GEX_INIT(self, packet):
clientDHPubKey, foo = getMP(packet)
# if y < 1024, openssh will reject us: "bad server public DH value".
# y<1024 means f will be short, and of the form 2^y, so an observer
# could trivially derive our secret y from f. Openssh detects this
# and complains, so avoid creating such values by requiring y to be
# larger than ln2(self.p)
# TODO: we should also look at the value they send to us and reject
# insecure values of f (if g==2 and f has a single '1' bit while the
# rest are '0's, then they must have used a small y also).
# TODO: This could be computed when self.p is set up
# or do as openssh does and scan f for a single '1' bit instead
minimum = long(math.floor(math.log(self.p) / math.log(2)) + 1)
tries = 0
pSize = Util.number.size(self.p)
y = Util.number.getRandomNumber(pSize, entropy.get_bytes)
while tries < 10 and y < minimum:
tries += 1
y = Util.number.getRandomNumber(pSize, entropy.get_bytes)
assert(y >= minimum) # TODO: test_conch just hangs if this is hit
# the chance of it being hit are really really low
f = pow(self.g, y, self.p)
sharedSecret = _MPpow(clientDHPubKey, y, self.p)
h = sha.new()
h.update(NS(self.otherVersionString))
h.update(NS(self.ourVersionString))
h.update(NS(self.clientKexInitPayload))
h.update(NS(self.ourKexInitPayload))
h.update(NS(self.factory.publicKeys[self.keyAlg]))
if self.kexAlg == 'diffie-hellman-group-exchange-sha1':
h.update(struct.pack('>3L', self.min, self.ideal, self.max))
else:
h.update(struct.pack('>L', self.ideal))
h.update(MP(self.p))
h.update(MP(self.g))
h.update(MP(clientDHPubKey))
h.update(MP(f))
h.update(sharedSecret)
exchangeHash = h.digest()
self.sendPacket(MSG_KEX_DH_GEX_REPLY, NS(self.factory.publicKeys[self.keyAlg])+ \
MP(f)+NS(keys.signData(self.factory.privateKeys[self.keyAlg], exchangeHash)))
self._keySetup(sharedSecret, exchangeHash)
def ssh_NEWKEYS(self, packet):
if packet != '':
self.sendDisconnect(DISCONNECT_PROTOCOL_ERROR, "NEWKEYS takes no data")
self.currentEncryptions = self.nextEncryptions
if self.outgoingCompressionType == 'zlib':
self.outgoingCompression = zlib.compressobj(6)
#self.outgoingCompression.compress = lambda x: self.outgoingCompression.compress(x) + self.outgoingCompression.flush(zlib.Z_SYNC_FLUSH)
if self.incomingCompressionType == 'zlib':
self.incomingCompression = zlib.decompressobj()
def ssh_SERVICE_REQUEST(self, packet):
service, rest = getNS(packet)
cls = self.factory.getService(self, service)
if not cls:
self.sendDisconnect(DISCONNECT_SERVICE_NOT_AVAILABLE, "don't have service %s"%service)
return
else:
self.sendPacket(MSG_SERVICE_ACCEPT, NS(service))
self.setService(cls())
def _keySetup(self, sharedSecret, exchangeHash):
if not self.sessionID:
self.sessionID = exchangeHash
initIVCS = self._getKey('A', sharedSecret, exchangeHash)
initIVSC = self._getKey('B', sharedSecret, exchangeHash)
encKeyCS = self._getKey('C', sharedSecret, exchangeHash)
encKeySC = self._getKey('D', sharedSecret, exchangeHash)
integKeyCS = self._getKey('E', sharedSecret, exchangeHash)
integKeySC = self._getKey('F', sharedSecret, exchangeHash)
self.nextEncryptions.setKeys(initIVSC, encKeySC, initIVCS, encKeyCS, integKeySC, integKeyCS)
self.sendPacket(MSG_NEWKEYS, '')
def _getKey(self, c, sharedSecret, exchangeHash):
k1 = sha.new(sharedSecret+exchangeHash+c+self.sessionID).digest()
k2 = sha.new(sharedSecret+exchangeHash+k1).digest()
return k1+k2
class SSHClientTransport(SSHTransportBase):
isClient = 1
def connectionMade(self):
SSHTransportBase.connectionMade(self)
self._gotNewKeys = 0
def ssh_KEXINIT(self, packet):
self.serverKexInitPayload = chr(MSG_KEXINIT)+packet
#cookie = packet[: 16] # taking this is unimportant
k = getNS(packet[16:], 10)
strings, rest = k[:-1], k[-1]
kexAlgs, keyAlgs, encCS, encSC, macCS, macSC, compCS, compSC, langCS, langSC = \
[s.split(',')for s in strings]
self.kexAlg = ffs(self.supportedKeyExchanges, kexAlgs)
self.keyAlg = ffs(self.supportedPublicKeys, keyAlgs)
self.nextEncryptions = SSHCiphers(
ffs(self.supportedCiphers, encCS),
ffs(self.supportedCiphers, encSC),
ffs(self.supportedMACs, macCS),
ffs(self.supportedMACs, macSC),
)
self.outgoingCompressionType = ffs(self.supportedCompressions, compCS)
self.incomingCompressionType = ffs(self.supportedCompressions, compSC)
if None in(self.kexAlg, self.keyAlg, self.outgoingCompressionType, self.incomingCompressionType):
self.sendDisconnect(DISCONNECT_KEY_EXCHANGE_FAILED, "couldn't match all kex parts")
return
if None in self.nextEncryptions.__dict__.values():
self.sendDisconnect(DISCONNECT_KEY_EXCHANGE_FAILED, "couldn't match all kex parts")
return
log.msg('kex alg, key alg: %s %s'%(self.kexAlg, self.keyAlg))
log.msg('client->server: %s %s %s'%(self.nextEncryptions.outCipType,
self.nextEncryptions.outMacType,
self.outgoingCompressionType))
log.msg('server->client: %s %s %s'%(self.nextEncryptions.inCipType,
self.nextEncryptions.inMacType,
self.incomingCompressionType))
if self.kexAlg == 'diffie-hellman-group1-sha1':
self.x = Util.number.getRandomNumber(512, entropy.get_bytes)
self.DHpubKey = pow(DH_GENERATOR, self.x, DH_PRIME)
self.sendPacket(MSG_KEXDH_INIT, MP(self.DHpubKey))
else:
self.sendPacket(MSG_KEX_DH_GEX_REQUEST_OLD, '\x00\x00\x08\x00')
def ssh_KEX_DH_GEX_GROUP(self, packet):
if self.kexAlg == 'diffie-hellman-group1-sha1':
pubKey, packet = getNS(packet)
f, packet = getMP(packet)
signature, packet = getNS(packet)
fingerprint = ':'.join(map(lambda c: '%02x'%ord(c), md5.new(pubKey).digest()))
d = self.verifyHostKey(pubKey, fingerprint)
d.addCallback(self._continueGEX_GROUP, pubKey, f, signature)
d.addErrback(lambda unused,self=self:self.sendDisconnect(DISCONNECT_HOST_KEY_NOT_VERIFIABLE, 'bad host key'))
else:
self.p, rest = getMP(packet)
self.g, rest = getMP(rest)
self.x = getMP('\x00\x00\x00\x40'+entropy.get_bytes(64))[0]
self.DHpubKey = pow(self.g, self.x, self.p)
self.sendPacket(MSG_KEX_DH_GEX_INIT, MP(self.DHpubKey))
def _continueGEX_GROUP(self, ignored, pubKey, f, signature):
serverKey = keys.getPublicKeyObject(pubKey)
sharedSecret = _MPpow(f, self.x, DH_PRIME)
h = sha.new()
h.update(NS(self.ourVersionString))
h.update(NS(self.otherVersionString))
h.update(NS(self.ourKexInitPayload))
h.update(NS(self.serverKexInitPayload))
h.update(NS(pubKey))
h.update(MP(self.DHpubKey))
h.update(MP(f))
h.update(sharedSecret)
exchangeHash = h.digest()
if not keys.verifySignature(serverKey, signature, exchangeHash):
self.sendDisconnect(DISCONNECT_KEY_EXCHANGE_FAILED, 'bad signature')
return
self._keySetup(sharedSecret, exchangeHash)
def ssh_KEX_DH_GEX_REPLY(self, packet):
pubKey, packet = getNS(packet)
f, packet = getMP(packet)
signature, packet = getNS(packet)
fingerprint = ':'.join(map(lambda c: '%02x'%ord(c), md5.new(pubKey).digest()))
d = self.verifyHostKey(pubKey, fingerprint)
d.addCallback(self._continueGEX_REPLY, pubKey, f, signature)
d.addErrback(lambda unused, self=self: self.sendDisconnect(DISCONNECT_HOST_KEY_NOT_VERIFIABLE, 'bad host key'))
def _continueGEX_REPLY(self, ignored, pubKey, f, signature):
serverKey = keys.getPublicKeyObject(pubKey)
sharedSecret = _MPpow(f, self.x, self.p)
h = sha.new()
h.update(NS(self.ourVersionString))
h.update(NS(self.otherVersionString))
h.update(NS(self.ourKexInitPayload))
h.update(NS(self.serverKexInitPayload))
h.update(NS(pubKey))
h.update('\x00\x00\x08\x00')
h.update(MP(self.p))
h.update(MP(self.g))
h.update(MP(self.DHpubKey))
h.update(MP(f))
h.update(sharedSecret)
exchangeHash = h.digest()
if not keys.verifySignature(serverKey, signature, exchangeHash):
self.sendDisconnect(DISCONNECT_KEY_EXCHANGE_FAILED, 'bad signature')
return
self._keySetup(sharedSecret, exchangeHash)
def _keySetup(self, sharedSecret, exchangeHash):
if not self.sessionID:
self.sessionID = exchangeHash
initIVCS = self._getKey('A', sharedSecret, exchangeHash)
initIVSC = self._getKey('B', sharedSecret, exchangeHash)
encKeyCS = self._getKey('C', sharedSecret, exchangeHash)
encKeySC = self._getKey('D', sharedSecret, exchangeHash)
integKeyCS = self._getKey('E', sharedSecret, exchangeHash)
integKeySC = self._getKey('F', sharedSecret, exchangeHash)
self.nextEncryptions.setKeys(initIVCS, encKeyCS, initIVSC, encKeySC, integKeyCS, integKeySC)
self.sendPacket(MSG_NEWKEYS, '')
if self._gotNewKeys:
self.ssh_NEWKEYS('')
def _getKey(self, c, sharedSecret, exchangeHash):
k1 = sha.new(sharedSecret+exchangeHash+c+self.sessionID).digest()
k2 = sha.new(sharedSecret+exchangeHash+k1).digest()
return k1+k2
def ssh_NEWKEYS(self, packet):
if packet != '':
self.sendDisconnect(DISCONNECT_PROTOCOL_ERROR, "NEWKEYS takes no data")
if not self.nextEncryptions.enc_block_size:
self._gotNewKeys = 1
return
self.currentEncryptions = self.nextEncryptions
if self.outgoingCompressionType == 'zlib':
self.outgoingCompression = zlib.compressobj(6)
#self.outgoingCompression.compress = lambda x: self.outgoingCompression.compress(x) + self.outgoingCompression.flush(zlib.Z_SYNC_FLUSH)
if self.incomingCompressionType == 'zlib':
self.incomingCompression = zlib.decompressobj()
self.connectionSecure()
def ssh_SERVICE_ACCEPT(self, packet):
name = getNS(packet)[0]
if name != self.instance.name:
self.sendDisconnect(DISCONNECT_PROTOCOL_ERROR, "received accept for service we did not request")
self.setService(self.instance)
def requestService(self, instance):
"""
Request that a service be run over this transport.
@type instance: subclass of L{twisted.conch.ssh.service.SSHService}
"""
self.sendPacket(MSG_SERVICE_REQUEST, NS(instance.name))
self.instance = instance
# client methods
def verifyHostKey(self, hostKey, fingerprint):
"""Returns a Deferred that gets a callback if it is a valid key, or
an errback if not.
@type hostKey: C{str}
@type fingerprint: C{str}
@rtype: L{Deferred}
"""
# return if it's good
return defer.fail(NotImplementedError)
def connectionSecure(self):
"""
Called when the encryption has been set up. Generally,
requestService() is called to run another service over the transport.
"""
raise NotImplementedError
class _DummyCipher:
block_size = 1
def encrypt(self, x):
return x
decrypt = encrypt
class SSHCiphers:
cipherMap = {
'3des-cbc':('DES3', 24, 0),
'blowfish-cbc':('Blowfish', 16,0 ),
'aes256-cbc':('AES', 32, 0),
'aes192-cbc':('AES', 24, 0),
'aes128-cbc':('AES', 16, 0),
'arcfour':('ARC4', 16, 0),
'idea-cbc':('IDEA', 16, 0),
'cast128-cbc':('CAST', 16, 0),
'aes128-ctr':('AES', 16, 1),
'aes192-ctr':('AES', 24, 1),
'aes256-ctr':('AES', 32, 1),
'3des-ctr':('DES3', 24, 1),
'blowfish-ctr':('Blowfish', 16, 1),
'idea-ctr':('IDEA', 16, 1),
'cast128-ctr':('CAST', 16, 1),
'none':(None, 0, 0),
}
macMap = {
'hmac-sha1': 'sha',
'hmac-md5': 'md5',
'none':None
}
def __init__(self, outCip, inCip, outMac, inMac):
self.outCipType = outCip
self.inCipType = inCip
self.outMacType = outMac
self.inMacType = inMac
self.enc_block_size = 0
self.dec_block_size = 0
def setKeys(self, outIV, outKey, inIV, inKey, outInteg, inInteg):
o = self._getCipher(self.outCipType, outIV, outKey)
self.encrypt = o.encrypt
self.enc_block_size = o.block_size
o = self._getCipher(self.inCipType, inIV, inKey)
self.decrypt = o.decrypt
self.dec_block_size = o.block_size
self.outMAC = self._getMAC(self.outMacType, outInteg)
self.inMAC = self._getMAC(self.inMacType, inInteg)
self.verify_digest_size = self.inMAC[3]
def _getCipher(self, cip, iv, key):
modName, keySize, counterMode = self.cipherMap[cip]
if not modName: # no cipher
return _DummyCipher()
mod = __import__('Crypto.Cipher.%s'%modName, {}, {}, 'x')
if counterMode:
return mod.new(key[:keySize], mod.MODE_CTR, iv[:mod.block_size], counter=_Counter(iv, mod.block_size))
else:
return mod.new(key[: keySize], mod.MODE_CBC, iv[: mod.block_size])
def _getMAC(self, mac, key):
modName = self.macMap[mac]
if not modName:
return None
mod = __import__(modName, {}, {}, '')
if not hasattr(mod, 'digest_size'):
ds = len(mod.new().digest())
else:
ds = mod.digest_size
key = key[: ds]+'\x00'*(64-ds)
i = XOR.new('\x36').encrypt(key)
o = XOR.new('\x5c').encrypt(key)
return mod, i,o, ds
def encrypt(self, blocks):
return blocks
def decrypt(self, blocks):
return blocks
def makeMAC(self, seqid, data):
if not self.outMAC: return ''
data = struct.pack('>L', seqid)+data
mod, i, o, ds = self.outMAC
inner = mod.new(i+data)
outer = mod.new(o+inner.digest())
return outer.digest()
def verify(self, seqid, data, mac):
if not self.inMAC:
return mac == ''
data = struct.pack('>L', seqid)+data
mod, i,o, ds = self.inMAC
inner = mod.new(i+data)
outer = mod.new(o+inner.digest())
return mac == outer.digest()
class _Counter:
"""
Stateful counter which returns results packed in a byte string
"""
def __init__(self, initialVector, blockSize):
"""
@type initialVector: C{str}
@param initialVector: A byte string representing the initial counter value.
@type blockSize: C{int}
@param blockSize: The length of the output buffer, as well as the
number of bytes at the beginning of C{initialVector} to consider.
"""
initialVector = initialVector[:blockSize]
self.count = getMP('\xff\xff\xff\xff' + initialVector)[0]
self.blockSize = blockSize
self.count = Util.number.long_to_bytes(self.count - 1)
self.count = '\x00' * (self.blockSize - len(self.count)) + self.count
self.count = array.array('c', self.count)
self.len = len(self.count) - 1
def __call__(self):
"""
Increment the counter and return the new value.
"""
i = self.len
while i > -1:
self.count[i] = n = chr((ord(self.count[i]) + 1) % 256)
if n == '\x00':
i -= 1
else:
return self.count.tostring()
self.count = array.array('c', '\x00' * self.blockSize)
return self.count.tostring()
def buffer_dump(b, title = None):
r = title or ''
while b:
c, b = b[: 16], b[16:]
while c:
a, c = c[: 2], c[2:]
if len(a) == 2:
r = r+'%02x%02x '%(ord(a[0]), ord(a[1]))
else:
r = r+'%02x'%ord(a[0])
r = r+'\n'
return r
DH_PRIME = 179769313486231590770839156793787453197860296048756011706444423684197180216158519368947833795864925541502180565485980503646440548199239100050792877003355816639229553136239076508735759914822574862575007425302077447712589550957937778424442426617334727629299387668709205606050270810842907692932019128194467627007L
DH_GENERATOR = 2L
MSG_DISCONNECT = 1
MSG_IGNORE = 2
MSG_UNIMPLEMENTED = 3
MSG_DEBUG = 4
MSG_SERVICE_REQUEST = 5
MSG_SERVICE_ACCEPT = 6
MSG_KEXINIT = 20
MSG_NEWKEYS = 21
MSG_KEXDH_INIT = 30
MSG_KEXDH_REPLY = 31
MSG_KEX_DH_GEX_REQUEST_OLD = 30
MSG_KEX_DH_GEX_REQUEST = 34
MSG_KEX_DH_GEX_GROUP = 31
MSG_KEX_DH_GEX_INIT = 32
MSG_KEX_DH_GEX_REPLY = 33
DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT = 1
DISCONNECT_PROTOCOL_ERROR = 2
DISCONNECT_KEY_EXCHANGE_FAILED = 3
DISCONNECT_RESERVED = 4
DISCONNECT_MAC_ERROR = 5
DISCONNECT_COMPRESSION_ERROR = 6
DISCONNECT_SERVICE_NOT_AVAILABLE = 7
DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED = 8
DISCONNECT_HOST_KEY_NOT_VERIFIABLE = 9
DISCONNECT_CONNECTION_LOST = 10
DISCONNECT_BY_APPLICATION = 11
DISCONNECT_TOO_MANY_CONNECTIONS = 12
DISCONNECT_AUTH_CANCELLED_BY_USER = 13
DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE = 14
DISCONNECT_ILLEGAL_USER_NAME = 15
messages = {}
for name, value in globals().items():
if name.startswith('MSG_'):
messages[value] = name | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/ssh/transport.py | transport.py |
#
"""This module contains the implementation of SSHSession, which (by default)
allows access to a shell and a python interpreter over SSH.
This module is unstable.
Maintainer: U{Paul Swartz<mailto:[email protected]>}
"""
import struct
from twisted.internet import protocol, reactor
from twisted.python import log
from twisted.conch.interfaces import ISession
import common, channel
class SSHSession(channel.SSHChannel):
name = 'session'
def __init__(self, *args, **kw):
channel.SSHChannel.__init__(self, *args, **kw)
self.buf = ''
self.client = None
self.session = None
def request_subsystem(self, data):
subsystem, ignored= common.getNS(data)
log.msg('asking for subsystem "%s"' % subsystem)
client = self.avatar.lookupSubsystem(subsystem, data)
if client:
pp = SSHSessionProcessProtocol(self)
proto = wrapProcessProtocol(pp)
client.makeConnection(proto)
pp.makeConnection(wrapProtocol(client))
self.client = pp
return 1
else:
log.msg('failed to get subsystem')
return 0
def request_shell(self, data):
log.msg('getting shell')
if not self.session:
self.session = ISession(self.avatar)
try:
pp = SSHSessionProcessProtocol(self)
self.session.openShell(pp)
except:
log.deferr()
return 0
else:
self.client = pp
return 1
def request_exec(self, data):
if not self.session:
self.session = ISession(self.avatar)
f,data = common.getNS(data)
log.msg('executing command "%s"' % f)
try:
pp = SSHSessionProcessProtocol(self)
self.session.execCommand(pp, f)
except:
log.deferr()
return 0
else:
self.client = pp
return 1
def request_pty_req(self, data):
if not self.session:
self.session = ISession(self.avatar)
term, windowSize, modes = parseRequest_pty_req(data)
log.msg('pty request: %s %s' % (term, windowSize))
try:
self.session.getPty(term, windowSize, modes)
except:
log.err()
return 0
else:
return 1
def request_window_change(self, data):
if not self.session:
self.session = ISession(self.avatar)
import fcntl, tty
winSize = parseRequest_window_change(data)
try:
self.session.windowChanged(winSize)
except:
log.msg('error changing window size')
log.err()
return 0
else:
return 1
def dataReceived(self, data):
if not self.client:
#self.conn.sendClose(self)
self.buf += data
return
self.client.transport.write(data)
def extReceived(self, dataType, data):
if dataType == connection.EXTENDED_DATA_STDERR:
if self.client and hasattr(self.client.transport, 'writeErr'):
self.client.transport.writeErr(data)
else:
log.msg('weird extended data: %s'%dataType)
def eofReceived(self):
if self.session:
self.session.eofReceived()
elif self.client:
self.conn.sendClose(self)
def closed(self):
if self.session:
self.session.closed()
#def closeReceived(self):
# self.loseConnection() # don't know what to do with this
def loseConnection(self):
if self.client:
self.client.transport.loseConnection()
channel.SSHChannel.loseConnection(self)
class _ProtocolWrapper(protocol.ProcessProtocol):
"""
This class wraps a L{Protocol} instance in a L{ProcessProtocol} instance.
"""
def __init__(self, proto):
self.proto = proto
def connectionMade(self): self.proto.connectionMade()
def outReceived(self, data): self.proto.dataReceived(data)
def processEnded(self, reason): self.proto.connectionLost(reason)
class _DummyTransport:
def __init__(self, proto):
self.proto = proto
def dataReceived(self, data):
self.proto.transport.write(data)
def write(self, data):
self.proto.dataReceived(data)
def writeSequence(self, seq):
self.write(''.join(seq))
def loseConnection(self):
self.proto.connectionLost(protocol.connectionDone)
def wrapProcessProtocol(inst):
if isinstance(inst, protocol.Protocol):
return _ProtocolWrapper(inst)
else:
return inst
def wrapProtocol(proto):
return _DummyTransport(proto)
class SSHSessionProcessProtocol(protocol.ProcessProtocol):
# __implements__ = I
def __init__(self, session):
self.session = session
def connectionMade(self):
if self.session.buf:
self.transport.write(self.session.buf)
self.session.buf = None
def outReceived(self, data):
self.session.write(data)
def errReceived(self, err):
self.session.writeExtended(connection.EXTENDED_DATA_STDERR, err)
def inConnectionLost(self):
self.session.conn.sendEOF(self.session)
def connectionLost(self, reason = None):
self.session.loseConnection()
def processEnded(self, reason = None):
if reason and hasattr(reason.value, 'exitCode'):
log.msg('exitCode: %s' % repr(reason.value.exitCode))
self.session.conn.sendRequest(self.session, 'exit-status', struct.pack('!L', reason.value.exitCode))
self.session.loseConnection()
# transport stuff (we are also a transport!)
def write(self, data):
self.session.write(data)
def writeSequence(self, seq):
self.session.write(''.join(seq))
def loseConnection(self):
self.session.loseConnection()
class SSHSessionClient(protocol.Protocol):
def dataReceived(self, data):
if self.transport:
self.transport.write(data)
# methods factored out to make live easier on server writers
def parseRequest_pty_req(data):
"""Parse the data from a pty-req request into usable data.
@returns: a tuple of (terminal type, (rows, cols, xpixel, ypixel), modes)
"""
term, rest = common.getNS(data)
cols, rows, xpixel, ypixel = struct.unpack('>4L', rest[: 16])
modes, ignored= common.getNS(rest[16:])
winSize = (rows, cols, xpixel, ypixel)
modes = [(ord(modes[i]), struct.unpack('>L', modes[i+1: i+5])[0]) for i in range(0, len(modes)-1, 5)]
return term, winSize, modes
def packRequest_pty_req(term, (rows, cols, xpixel, ypixel), modes):
"""Pack a pty-req request so that it is suitable for sending.
NOTE: modes must be packed before being sent here.
"""
termPacked = common.NS(term)
winSizePacked = struct.pack('>4L', cols, rows, xpixel, ypixel)
modesPacked = common.NS(modes) # depend on the client packing modes
return termPacked + winSizePacked + modesPacked
def parseRequest_window_change(data):
"""Parse the data from a window-change request into usuable data.
@returns: a tuple of (rows, cols, xpixel, ypixel)
"""
cols, rows, xpixel, ypixel = struct.unpack('>4L', data)
return rows, cols, xpixel, ypixel
def packRequest_window_change((rows, cols, xpixel, ypixel)):
"""Pack a window-change request so that it is suitable for sending.
"""
return struct.pack('>4L', cols, rows, xpixel, ypixel)
import connection | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/ssh/session.py | session.py |
#
"""
Implements the old SSHv1 key agent protocol.
This module is unstable.
Maintainer: U{Paul Swartz<mailto:[email protected]>}
"""
import struct
from common import NS, getNS
from twisted.conch.error import ConchError
from twisted.internet import defer, protocol
class SSHAgentClient(protocol.Protocol):
def __init__(self):
self.buf = ''
self.deferreds = []
def dataReceived(self, data):
self.buf += data
while 1:
if len(self.buf) <= 4: return
packLen = struct.unpack('!L', self.buf[:4])[0]
if len(self.buf) < 4+packLen: return
packet, self.buf = self.buf[4:4+packLen], self.buf[4+packLen:]
reqType = ord(packet[0])
d = self.deferreds.pop(0)
if reqType == AGENT_FAILURE:
d.errback(ConchError('agent failure'))
elif reqType == AGENT_SUCCESS:
d.callback('')
else:
d.callback(packet)
def sendRequest(self, reqType, data):
pack = struct.pack('!LB',len(data)+1, reqType)+data
self.transport.write(pack)
d = defer.Deferred()
self.deferreds.append(d)
return d
def requestIdentities(self):
return self.sendRequest(AGENTC_REQUEST_IDENTITIES, '').addCallback(self._cbRequestIdentities)
def _cbRequestIdentities(self, data):
if ord(data[0]) != AGENT_IDENTITIES_ANSWER:
return ConchError('unexpected respone: %i' % ord(data[0]))
numKeys = struct.unpack('!L', data[1:5])[0]
keys = []
data = data[5:]
for i in range(numKeys):
blobLen = struct.unpack('!L', data[:4])[0]
blob, data = data[4:4+blobLen], data[4+blobLen:]
commLen = struct.unpack('!L', data[:4])[0]
comm, data = data[4:4+commLen], data[4+commLen:]
keys.append((blob, comm))
return keys
def addIdentity(self, blob, comment = ''):
req = blob
req += NS(comment)
co
return self.sendRequest(AGENTC_ADD_IDENTITY, req)
def signData(self, blob, data):
req = NS(blob)
req += NS(data)
req += '\000\000\000\000' # flags
return self.sendRequest(AGENTC_SIGN_REQUEST, req).addCallback(self._cbSignData)
def _cbSignData(self, data):
if data[0] != chr(AGENT_SIGN_RESPONSE):
return ConchError('unexpected data: %i' % ord(data[0]))
signature = getNS(data[1:])[0]
return signature
def removeIdentity(self, blob):
req = NS(blob)
return self.sendRequest(AGENTC_REMOVE_IDENTITY, req)
def removeAllIdentities(self):
return self.sendRequest(AGENTC_REMOVE_ALL_IDENTITIES, '')
class SSHAgentServer(protocol.Protocol):
def __init__(self):
self.buf = ''
def dataReceived(self, data):
self.buf += data
while 1:
if len(self.buf) <= 4: return
packLen = struct.unpack('!L', self.buf[:4])[0]
if len(self.buf) < 4+packLen: return
packet, self.buf = self.buf[4:4+packLen], self.buf[4+packLen:]
reqType = ord(packet[0])
reqName = messages.get(reqType, None)
if not reqName:
print 'bad request', reqType
f = getattr(self, 'agentc_%s' % reqName)
f(packet[1:])
def sendResponse(self, reqType, data):
pack = struct.pack('!LB', len(data)+1, reqType) + data
self.transport.write(pack)
def agentc_REQUEST_IDENTITIES(self, data):
assert data == ''
numKeys = len(self.keys)
s = struct.pack('!L', numKeys)
for k in self.keys:
s += struct.pack('!L', len(k)) + k
s += struct.pack('!L', len(self.keys[k][1])) + self.keys[k][1]
self.sendResponse(AGENT_IDENTITIES_ANSWER, s)
def agentc_SIGN_REQUEST(self, data):
blob, data = common.getNS(data)
if blob not in self.keys:
return self.sendResponse(AGENT_FAILURE, '')
signData, data = common.getNS(data)
assert data == '\000\000\000\000'
self.sendResponse(AGENT_SIGN_RESPONSE, common.NS(keys.signData(self.keys[blob][0], signData)))
def agentc_ADD_IDENTITY(self, data): pass
def agentc_REMOVE_IDENTITY(self, data): pass
def agentc_REMOVE_ALL_IDENTITIES(self, data): pass
AGENT_FAILURE = 5
AGENT_SUCCESS = 6
AGENTC_REQUEST_IDENTITIES = 11
AGENT_IDENTITIES_ANSWER = 12
AGENTC_SIGN_REQUEST = 13
AGENT_SIGN_RESPONSE = 14
AGENTC_ADD_IDENTITY = 17
AGENTC_REMOVE_IDENTITY = 18
AGENTC_REMOVE_ALL_IDENTITIES = 19
messages = {}
import agent
for v in dir(agent):
if v.startswith('AGENTC_'):
messages[getattr(agent, v)] = v[7:] | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/ssh/agent.py | agent.py |
#
"""A Factory for SSH servers, along with an OpenSSHFactory to use the same data sources as OpenSSH.
This module is unstable.
Maintainer: U{Paul Swartz<mailto:[email protected]>}
"""
import md5
try:
import resource
except ImportError:
resource = None
from twisted.internet import protocol
from twisted.python import log
from twisted.conch import error
import transport, userauth, connection
import random
class SSHFactory(protocol.Factory):
services = {
'ssh-userauth':userauth.SSHUserAuthServer,
'ssh-connection':connection.SSHConnection
}
def startFactory(self):
# disable coredumps
if resource:
resource.setrlimit(resource.RLIMIT_CORE, (0,0))
else:
log.msg('INSECURE: unable to disable core dumps.')
if not hasattr(self,'publicKeys'):
self.publicKeys = self.getPublicKeys()
if not hasattr(self,'privateKeys'):
self.privateKeys = self.getPrivateKeys()
if not self.publicKeys or not self.privateKeys:
raise error.ConchError('no host keys, failing')
if not hasattr(self,'primes'):
self.primes = self.getPrimes()
#if not self.primes:
# log.msg('disabling diffie-hellman-group-exchange because we cannot find moduli file')
# transport.SSHServerTransport.supportedKeyExchanges.remove('diffie-hellman-group-exchange-sha1')
if self.primes:
self.primesKeys = self.primes.keys()
def buildProtocol(self, addr):
t = transport.SSHServerTransport()
t.supportedPublicKeys = self.privateKeys.keys()
if not self.primes:
ske = t.supportedKeyExchanges[:]
ske.remove('diffie-hellman-group-exchange-sha1')
t.supportedKeyExchanges = ske
t.factory = self
return t
def getPublicKeys(self):
"""
Called when the factory is started to get the public portions of the
servers host keys. Returns a dictionary mapping SSH key types to
public key strings.
@rtype: C{dict}
"""
raise NotImplementedError
def getPrivateKeys(self):
"""
Called when the factory is started to get the private portions of the
servers host keys. Returns a dictionary mapping SSH key types to
C{Crypto.PublicKey.pubkey.pubkey} objects.
@rtype: C{dict}
"""
raise NotImplementedError
def getPrimes(self):
"""
Called when the factory is started to get Diffie-Hellman generators and
primes to use. Returns a dictionary mapping number of bits to lists
of tuple of (generator, prime).
@rtype: C{dict}
"""
def getDHPrime(self, bits):
"""
Return a tuple of (g, p) for a Diffe-Hellman process, with p being as
close to bits bits as possible.
@type bits: C{int}
@rtype: C{tuple}
"""
self.primesKeys.sort(lambda x,y,b=bits:cmp(abs(x-b), abs(x-b)))
realBits = self.primesKeys[0]
return random.choice(self.primes[realBits])
def getService(self, transport, service):
"""
Return a class to use as a service for the given transport.
@type transport: L{transport.SSHServerTransport}
@type service: C{stR}
@rtype: subclass of L{service.SSHService}
"""
if transport.isAuthorized or service == 'ssh-userauth':
return self.services[service] | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/ssh/factory.py | factory.py |
#
"""Implementation of the ssh-userauth service.
Currently implemented authentication types are public-key and password.
This module is unstable.
Maintainer: U{Paul Swartz<mailto:[email protected]>}
"""
import struct
from twisted.conch import error, interfaces
from twisted.cred import credentials
from twisted.internet import defer, reactor
from twisted.python import failure, log
from common import NS, getNS, MP
import keys, transport, service
class SSHUserAuthServer(service.SSHService):
name = 'ssh-userauth'
loginTimeout = 10 * 60 * 60 # 10 minutes before we disconnect them
attemptsBeforeDisconnect = 20 # number of attempts to allow before a disconnect
passwordDelay = 1 # number of seconds to delay on a failed password
protocolMessages = None # set later
interfaceToMethod = {
credentials.ISSHPrivateKey : 'publickey',
credentials.IUsernamePassword : 'password',
credentials.IPluggableAuthenticationModules : 'keyboard-interactive',
}
def serviceStarted(self):
self.authenticatedWith = []
self.loginAttempts = 0
self.user = None
self.nextService = None
self.portal = self.transport.factory.portal
self.supportedAuthentications = []
for i in self.portal.listCredentialsInterfaces():
if i in self.interfaceToMethod:
self.supportedAuthentications.append(self.interfaceToMethod[i])
if not self.transport.isEncrypted('out'):
if 'password' in self.supportedAuthentications:
self.supportedAuthentications.remove('password')
if 'keyboard-interactive' in self.supportedAuthentications:
self.supportedAuthentications.remove('keyboard-interactive')
# don't let us transport password in plaintext
self.cancelLoginTimeout = reactor.callLater(self.loginTimeout,
self.timeoutAuthentication)
def serviceStopped(self):
if self.cancelLoginTimeout:
self.cancelLoginTimeout.cancel()
self.cancelLoginTimeout = None
def timeoutAuthentication(self):
self.cancelLoginTimeout = None
self.transport.sendDisconnect(
transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
'you took too long')
def tryAuth(self, kind, user, data):
log.msg('%s trying auth %s' % (user, kind))
if kind not in self.supportedAuthentications:
return defer.fail(error.ConchError('unsupported authentication, failing'))
kind = kind.replace('-', '_')
f = getattr(self,'auth_%s'%kind, None)
if f:
ret = f(data)
if not ret:
return defer.fail(error.ConchError('%s return None instead of a Deferred' % kind))
else:
return ret
return defer.fail(error.ConchError('bad auth type: %s' % kind))
def ssh_USERAUTH_REQUEST(self, packet):
user, nextService, method, rest = getNS(packet, 3)
if user != self.user or nextService != self.nextService:
self.authenticatedWith = [] # clear auth state
self.user = user
self.nextService = nextService
self.method = method
d = self.tryAuth(method, user, rest)
if not d:
self._ebBadAuth(ConchError('auth returned none'))
d.addCallbacks(self._cbFinishedAuth)
d.addErrback(self._ebMaybeBadAuth)
d.addErrback(self._ebBadAuth)
def _cbFinishedAuth(self, (interface, avatar, logout)):
self.transport.isAuthorized = True
service = self.transport.factory.getService(self.transport,
self.nextService)
if not service:
raise error.ConchError('could not get next service: %s'
% self.nextService)
log.msg('%s authenticated with %s' % (self.user, self.method))
if self.cancelLoginTimeout:
self.cancelLoginTimeout.cancel()
self.cancelLoginTimeout = None
self.transport.sendPacket(MSG_USERAUTH_SUCCESS, '')
self.transport.avatar = avatar
self.transport.logoutFunction = logout
self.transport.setService(service())
def _ebMaybeBadAuth(self, reason):
reason.trap(error.NotEnoughAuthentication)
self.transport.sendPacket(MSG_USERAUTH_FAILURE, NS(','.join(self.supportedAuthentications))+'\xff')
def _ebBadAuth(self, reason):
if reason.type == error.IgnoreAuthentication:
return
if self.method != 'none':
log.msg('%s failed auth %s' % (self.user, self.method))
log.msg('reason:')
if reason.type == error.ConchError:
log.msg(str(reason))
else:
log.msg(reason.getTraceback())
self.loginAttempts += 1
if self.loginAttempts > self.attemptsBeforeDisconnect:
self.transport.sendDisconnect(transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
'too many bad auths')
self.transport.sendPacket(MSG_USERAUTH_FAILURE, NS(','.join(self.supportedAuthentications))+'\x00')
def auth_publickey(self, packet):
hasSig = ord(packet[0])
algName, blob, rest = getNS(packet[1:], 2)
pubKey = keys.getPublicKeyObject(data = blob)
signature = hasSig and getNS(rest)[0] or None
if hasSig:
b = NS(self.transport.sessionID) + chr(MSG_USERAUTH_REQUEST) + \
NS(self.user) + NS(self.nextService) + NS('publickey') + \
chr(hasSig) + NS(keys.objectType(pubKey)) + NS(blob)
c = credentials.SSHPrivateKey(self.user, algName, blob, b, signature)
return self.portal.login(c, None, interfaces.IConchUser)
else:
c = credentials.SSHPrivateKey(self.user, algName, blob, None, None)
return self.portal.login(c, None, interfaces.IConchUser).addErrback(
self._ebCheckKey,
packet[1:])
def _ebCheckKey(self, reason, packet):
reason.trap(error.ValidPublicKey)
# if we make it here, it means that the publickey is valid
self.transport.sendPacket(MSG_USERAUTH_PK_OK, packet)
return failure.Failure(error.IgnoreAuthentication())
def auth_password(self, packet):
password = getNS(packet[1:])[0]
c = credentials.UsernamePassword(self.user, password)
return self.portal.login(c, None, interfaces.IConchUser).addErrback(
self._ebPassword)
def _ebPassword(self, f):
d = defer.Deferred()
reactor.callLater(self.passwordDelay, lambda d,f:d.callback(f), d, f)
return d
def auth_keyboard_interactive(self, packet):
if hasattr(self, '_pamDeferred'):
self.transport.sendDisconnect(transport.DISCONNECT_PROTOCOL_ERROR, "only one keyboard interactive attempt at a time")
return failure.Failure(error.IgnoreAuthentication())
c = credentials.PluggableAuthenticationModules(self.user, self._pamConv)
return self.portal.login(c, None, interfaces.IConchUser)
def _pamConv(self, items):
resp = []
for message, kind in items:
if kind == 1: # password
resp.append((message, 0))
elif kind == 2: # text
resp.append((message, 1))
elif kind in (3, 4):
return defer.fail(error.ConchError('cannot handle PAM 3 or 4 messages'))
else:
return defer.fail(error.ConchError('bad PAM auth kind %i' % kind))
packet = NS('')+NS('')+NS('')
packet += struct.pack('>L', len(resp))
for prompt, echo in resp:
packet += NS(prompt)
packet += chr(echo)
self.transport.sendPacket(MSG_USERAUTH_INFO_REQUEST, packet)
self._pamDeferred = defer.Deferred()
return self._pamDeferred
def ssh_USERAUTH_INFO_RESPONSE(self, packet):
d = self._pamDeferred
del self._pamDeferred
try:
resp = []
numResps = struct.unpack('>L', packet[:4])[0]
packet = packet[4:]
while packet:
response, packet = getNS(packet)
resp.append((response, 0))
assert len(resp) == numResps
except:
d.errback(failure.Failure())
else:
d.callback(resp)
class SSHUserAuthClient(service.SSHService):
name = 'ssh-userauth'
protocolMessages = None # set later
preferredOrder = ['publickey', 'password', 'keyboard-interactive']
def __init__(self, user, instance):
self.user = user
self.instance = instance
def serviceStarted(self):
self.authenticatedWith = []
self.triedPublicKeys = []
self.lastPublicKey = None
self.askForAuth('none', '')
def askForAuth(self, kind, extraData):
self.lastAuth = kind
self.transport.sendPacket(MSG_USERAUTH_REQUEST, NS(self.user) + \
NS(self.instance.name) + NS(kind) + extraData)
def tryAuth(self, kind):
kind = kind.replace('-', '_')
log.msg('trying to auth with %s' % kind)
f= getattr(self,'auth_%s'%kind, None)
if f:
return f()
def _ebAuth(self, ignored, *args):
self.tryAuth('none')
def ssh_USERAUTH_SUCCESS(self, packet):
self.transport.setService(self.instance)
#self.ssh_USERAUTH_SUCCESS = lambda *a: None # ignore these
def ssh_USERAUTH_FAILURE(self, packet):
canContinue, partial = getNS(packet)
canContinue = canContinue.split(',')
partial = ord(partial)
if partial:
self.authenticatedWith.append(self.lastAuth)
def _(x, y):
try:
i1 = self.preferredOrder.index(x)
except ValueError:
return 1
try:
i2 = self.preferredOrder.index(y)
except ValueError:
return -1
return cmp(i1, i2)
canContinue.sort(_)
log.msg('can continue with: %s' % canContinue)
for method in canContinue:
if method not in self.authenticatedWith and self.tryAuth(method):
return
self.transport.sendDisconnect(transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE, 'no more authentication methods available')
def ssh_USERAUTH_PK_OK(self, packet):
if self.lastAuth == 'publickey':
# this is ok
publicKey = self.lastPublicKey
keyType = getNS(publicKey)[0]
b = NS(self.transport.sessionID) + chr(MSG_USERAUTH_REQUEST) + \
NS(self.user) + NS(self.instance.name) + NS('publickey') + '\xff' +\
NS(keyType) + NS(publicKey)
d = self.signData(publicKey, b)
if not d:
self.askForAuth('none', '')
# this will fail, we'll move on
return
d.addCallback(self._cbSignedData)
d.addErrback(self._ebAuth)
elif self.lastAuth == 'password':
prompt, language, rest = getNS(packet, 2)
self._oldPass = self._newPass = None
self.getPassword('Old Password: ').addCallbacks(self._setOldPass, self._ebAuth)
self.getPassword(prompt).addCallbacks(self._setNewPass, self._ebAuth)
elif self.lastAuth == 'keyboard-interactive':
name, instruction, lang, data = getNS(packet, 3)
numPrompts = struct.unpack('!L', data[:4])[0]
data = data[4:]
prompts = []
for i in range(numPrompts):
prompt, data = getNS(data)
echo = bool(ord(data[0]))
data = data[1:]
prompts.append((prompt, echo))
d = self.getGenericAnswers(name, instruction, prompts)
d.addCallback(self._cbGenericAnswers)
d.addErrback(self._ebAuth)
def _cbSignedData(self, signedData):
publicKey = self.lastPublicKey
keyType = getNS(publicKey)[0]
self.askForAuth('publickey', '\xff' + NS(keyType) + NS(publicKey) + \
NS(signedData))
def _setOldPass(self, op):
if self._newPass:
np = self._newPass
self._newPass = None
self.askForAuth('password', '\xff'+NS(op)+NS(np))
else:
self._oldPass = op
def _setNewPass(self, np):
if self._oldPass:
op = self._oldPass
self._oldPass = None
self.askForAuth('password', '\xff'+NS(op)+NS(np))
else:
self._newPass = np
def _cbGenericAnswers(self, responses):
data = struct.pack('!L', len(responses))
for r in responses:
data += NS(r.encode('UTF8'))
self.transport.sendPacket(MSG_USERAUTH_INFO_RESPONSE, data)
def auth_publickey(self):
publicKey = self.getPublicKey()
if publicKey:
self.lastPublicKey = publicKey
self.triedPublicKeys.append(publicKey)
keyType = getNS(publicKey)[0]
log.msg('using key of type %s' % keyType)
self.askForAuth('publickey', '\x00' + NS(keyType) + \
NS(publicKey))
return 1
else:
return 0
def auth_password(self):
d = self.getPassword()
if d:
d.addCallbacks(self._cbPassword, self._ebAuth)
return 1
else: # returned None, don't do password auth
return 0
def auth_keyboard_interactive(self):
log.msg('authing with keyboard-interactive')
self.askForAuth('keyboard-interactive', NS('') + NS(''))
return 1
def _cbPassword(self, password):
self.askForAuth('password', '\x00'+NS(password))
def signData(self, publicKey, signData):
"""
Sign the given data with the given public key blob.
By default, this will call getPrivateKey to get the private key,
the sign the data using keys.signData.
However, this is factored out so that it can use alternate methods,
such as a key agent.
"""
key = self.getPrivateKey()
if not key:
return
return key.addCallback(self._cbSignData, signData)
def _cbSignData(self, privateKey, signData):
return keys.signData(privateKey, signData)
def getPublicKey(self):
"""
Return a public key for the user. If no more public keys are
available, return None.
@rtype: C{str}/C{None}
"""
return None
#raise NotImplementedError
def getPrivateKey(self):
"""
Return a L{Deferred} that will be called back with the private key
corresponding to the last public key from getPublicKey().
If the private key is not available, errback on the Deferred.
@rtype: L{Deferred}
"""
return defer.fail(NotImplementedError())
def getPassword(self, prompt = None):
"""
Return a L{Deferred} that will be called back with a password.
prompt is a string to display for the password, or None for a generic
'user@hostname's password: '.
@type prompt: C{str}/C{None}
@rtype: L{Deferred}
"""
return defer.fail(NotImplementedError())
def getGenericAnswers(self, name, instruction, prompts):
"""
Returns a L{Deferred} with the responses to the promopts.
@param name: The name of the authentication currently in progress.
@param instruction: Describes what the authentication wants.
@param prompts: A list of (prompt, echo) pairs, where prompt is a
string to display and echo is a boolean indicating whether the
user's response should be echoed as they type it.
"""
return defer.fail(NotImplementedError())
MSG_USERAUTH_REQUEST = 50
MSG_USERAUTH_FAILURE = 51
MSG_USERAUTH_SUCCESS = 52
MSG_USERAUTH_BANNER = 53
MSG_USERAUTH_PASSWD_CHANGEREQ = 60
MSG_USERAUTH_INFO_REQUEST = 60
MSG_USERAUTH_INFO_RESPONSE = 61
MSG_USERAUTH_PK_OK = 60
messages = {}
import userauth
for v in dir(userauth):
if v[:4]=='MSG_':
messages[getattr(userauth,v)] = v # doesn't handle doubles
SSHUserAuthServer.protocolMessages = messages
SSHUserAuthClient.protocolMessages = messages | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/conch/ssh/userauth.py | userauth.py |
#
"""Save and load Small OBjects to and from files, using various formats.
API Stability: unstable
Maintainer: U{Moshe Zadka<mailto:[email protected]>}
"""
import os, md5, sys
try:
import cPickle as pickle
except ImportError:
import pickle
try:
import cStringIO as StringIO
except ImportError:
import StringIO
from twisted.python import log, runtime
from twisted.persisted import styles
from zope.interface import implements, Interface
# Note:
# These encrypt/decrypt functions only work for data formats
# which are immune to having spaces tucked at the end.
# All data formats which persist saves hold that condition.
def _encrypt(passphrase, data):
from Crypto.Cipher import AES as cipher
leftover = len(data) % cipher.block_size
if leftover:
data += ' '*(cipher.block_size - leftover)
return cipher.new(md5.new(passphrase).digest()[:16]).encrypt(data)
def _decrypt(passphrase, data):
from Crypto.Cipher import AES
return AES.new(md5.new(passphrase).digest()[:16]).decrypt(data)
class IPersistable(Interface):
"""An object which can be saved in several formats to a file"""
def setStyle(style):
"""Set desired format.
@type style: string (one of 'pickle', 'source' or 'xml')
"""
def save(tag=None, filename=None, passphrase=None):
"""Save object to file.
@type tag: string
@type filename: string
@type passphrase: string
"""
class Persistent:
implements(IPersistable)
style = "pickle"
def __init__(self, original, name):
self.original = original
self.name = name
def setStyle(self, style):
"""Set desired format.
@type style: string (one of 'pickle', 'source' or 'xml')
"""
self.style = style
def _getFilename(self, filename, ext, tag):
if filename:
finalname = filename
filename = finalname + "-2"
elif tag:
filename = "%s-%s-2.%s" % (self.name, tag, ext)
finalname = "%s-%s.%s" % (self.name, tag, ext)
else:
filename = "%s-2.%s" % (self.name, ext)
finalname = "%s.%s" % (self.name, ext)
return finalname, filename
def _saveTemp(self, filename, passphrase, dumpFunc):
f = open(filename, 'wb')
if passphrase is None:
dumpFunc(self.original, f)
else:
s = StringIO.StringIO()
dumpFunc(self.original, s)
f.write(_encrypt(passphrase, s.getvalue()))
f.close()
def _getStyle(self):
if self.style == "xml":
from twisted.persisted.marmalade import jellyToXML as dumpFunc
ext = "tax"
elif self.style == "source":
from twisted.persisted.aot import jellyToSource as dumpFunc
ext = "tas"
else:
def dumpFunc(obj, file):
pickle.dump(obj, file, 2)
ext = "tap"
return ext, dumpFunc
def save(self, tag=None, filename=None, passphrase=None):
"""Save object to file.
@type tag: string
@type filename: string
@type passphrase: string
"""
ext, dumpFunc = self._getStyle()
if passphrase:
ext = 'e' + ext
finalname, filename = self._getFilename(filename, ext, tag)
log.msg("Saving "+self.name+" application to "+finalname+"...")
self._saveTemp(filename, passphrase, dumpFunc)
if runtime.platformType == "win32" and os.path.isfile(finalname):
os.remove(finalname)
os.rename(filename, finalname)
log.msg("Saved.")
# "Persistant" has been present since 1.0.7, so retain it for compatibility
Persistant = Persistent
class _EverythingEphemeral(styles.Ephemeral):
initRun = 0
def __init__(self, mainMod):
"""
@param mainMod: The '__main__' module that this class will proxy.
"""
self.mainMod = mainMod
def __getattr__(self, key):
try:
return getattr(self.mainMod, key)
except AttributeError:
if self.initRun:
raise
else:
log.msg("Warning! Loading from __main__: %s" % key)
return styles.Ephemeral()
def load(filename, style, passphrase=None):
"""Load an object from a file.
Deserialize an object from a file. The file can be encrypted.
@param filename: string
@param style: string (one of 'source', 'xml' or 'pickle')
@param passphrase: string
"""
mode = 'r'
if style=='source':
from twisted.persisted.aot import unjellyFromSource as _load
elif style=='xml':
from twisted.persisted.marmalade import unjellyFromXML as _load
else:
_load, mode = pickle.load, 'rb'
if passphrase:
fp = StringIO.StringIO(_decrypt(passphrase,
open(filename, 'rb').read()))
else:
fp = open(filename, mode)
ee = _EverythingEphemeral(sys.modules['__main__'])
sys.modules['__main__'] = ee
ee.initRun = 1
try:
value = _load(fp)
finally:
# restore __main__ if an exception is raised.
sys.modules['__main__'] = ee.mainMod
styles.doUpgrade()
ee.initRun = 0
persistable = IPersistable(value, None)
if persistable is not None:
persistable.setStyle(style)
return value
def loadValueFromFile(filename, variable, passphrase=None):
"""Load the value of a variable in a Python file.
Run the contents of the file, after decrypting if C{passphrase} is
given, in a namespace and return the result of the variable
named C{variable}.
@param filename: string
@param variable: string
@param passphrase: string
"""
if passphrase:
mode = 'rb'
else:
mode = 'r'
fileObj = open(filename, mode)
d = {'__file__': filename}
if passphrase:
data = fileObj.read()
data = _decrypt(passphrase, data)
exec data in d, d
else:
exec fileObj in d, d
value = d[variable]
return value
def guessType(filename):
ext = os.path.splitext(filename)[1]
return {
'.tac': 'python',
'.etac': 'python',
'.py': 'python',
'.tap': 'pickle',
'.etap': 'pickle',
'.tas': 'source',
'.etas': 'source',
'.tax': 'xml',
'.etax': 'xml'
}[ext]
__all__ = ['loadValueFromFile', 'load', 'Persistent', 'Persistant',
'IPersistable', 'guessType'] | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/persisted/sob.py | sob.py |
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Utility classes for dealing with circular references.
"""
from twisted.python import log, reflect
try:
from new import instancemethod
except:
from org.python.core import PyMethod
instancemethod = PyMethod
class NotKnown:
def __init__(self):
self.dependants = []
self.resolved = 0
def addDependant(self, mutableObject, key):
assert not self.resolved
self.dependants.append( (mutableObject, key) )
resolvedObject = None
def resolveDependants(self, newObject):
self.resolved = 1
self.resolvedObject = newObject
for mut, key in self.dependants:
mut[key] = newObject
if isinstance(newObject, NotKnown):
newObject.addDependant(mut, key)
def __hash__(self):
assert 0, "I am not to be used as a dictionary key."
class _Tuple(NotKnown):
def __init__(self, l):
NotKnown.__init__(self)
self.l = l
self.locs = range(len(l))
for idx in xrange(len(l)):
if not isinstance(l[idx], NotKnown):
self.locs.remove(idx)
else:
l[idx].addDependant(self, idx)
if not self.locs:
self.resolveDependants(tuple(self.l))
def __setitem__(self, n, obj):
self.l[n] = obj
if not isinstance(obj, NotKnown):
self.locs.remove(n)
if not self.locs:
self.resolveDependants(tuple(self.l))
class _InstanceMethod(NotKnown):
def __init__(self, im_name, im_self, im_class):
NotKnown.__init__(self)
self.my_class = im_class
self.name = im_name
# im_self _must_ be a
im_self.addDependant(self, 0)
def __call__(self, *args, **kw):
import traceback
log.msg('instance method %s.%s' % (reflect.qual(self.my_class), self.name))
log.msg('being called with %r %r' % (args, kw))
traceback.print_stack(file=log.logfile)
assert 0
def __setitem__(self, n, obj):
assert n == 0, "only zero index allowed"
if not isinstance(obj, NotKnown):
self.resolveDependants(instancemethod(self.my_class.__dict__[self.name],
obj,
self.my_class))
class _DictKeyAndValue:
def __init__(self, dict):
self.dict = dict
def __setitem__(self, n, obj):
if n not in (1, 0):
raise AssertionError("DictKeyAndValue should only ever be called with 0 or 1")
if n: # value
self.value = obj
else:
self.key = obj
if hasattr(self, "key") and hasattr(self, "value"):
self.dict[self.key] = self.value
class _Dereference(NotKnown):
def __init__(self, id):
NotKnown.__init__(self)
self.id = id
from twisted.internet.defer import Deferred
class _Catcher:
def catch(self, value):
self.value = value
class _Defer(Deferred, NotKnown):
def __init__(self):
Deferred.__init__(self)
NotKnown.__init__(self)
self.pause()
wasset = 0
def __setitem__(self, n, obj):
if self.wasset:
raise 'waht!?', n, obj
else:
self.wasset = 1
self.callback(obj)
def addDependant(self, dep, key):
# by the time I'm adding a dependant, I'm *not* adding any more
# callbacks
NotKnown.addDependant(self, dep, key)
self.unpause()
resovd = self.result
self.resolveDependants(resovd) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/persisted/crefutil.py | crefutil.py |
# System Imports
import types
import copy_reg
import copy
try:
import cStringIO as StringIO
except ImportError:
import StringIO
# Twisted Imports
from twisted.python import log
try:
from new import instancemethod
except:
from org.python.core import PyMethod
instancemethod = PyMethod
oldModules = {}
## First, let's register support for some stuff that really ought to
## be registerable...
def pickleMethod(method):
'support function for copy_reg to pickle method refs'
return unpickleMethod, (method.im_func.__name__,
method.im_self,
method.im_class)
def unpickleMethod(im_name,
im_self,
im_class):
'support function for copy_reg to unpickle method refs'
try:
unbound = getattr(im_class,im_name)
if im_self is None:
return unbound
bound=instancemethod(unbound.im_func,
im_self,
im_class)
return bound
except AttributeError:
log.msg("Method",im_name,"not on class",im_class)
assert im_self is not None,"No recourse: no instance to guess from."
# Attempt a common fix before bailing -- if classes have
# changed around since we pickled this method, we may still be
# able to get it by looking on the instance's current class.
unbound = getattr(im_self.__class__,im_name)
log.msg("Attempting fixup with",unbound)
if im_self is None:
return unbound
bound=instancemethod(unbound.im_func,
im_self,
im_self.__class__)
return bound
copy_reg.pickle(types.MethodType,
pickleMethod,
unpickleMethod)
def pickleModule(module):
'support function for copy_reg to pickle module refs'
return unpickleModule, (module.__name__,)
def unpickleModule(name):
'support function for copy_reg to unpickle module refs'
if oldModules.has_key(name):
log.msg("Module has moved: %s" % name)
name = oldModules[name]
log.msg(name)
return __import__(name,{},{},'x')
copy_reg.pickle(types.ModuleType,
pickleModule,
unpickleModule)
def pickleStringO(stringo):
'support function for copy_reg to pickle StringIO.OutputTypes'
return unpickleStringO, (stringo.getvalue(), stringo.tell())
def unpickleStringO(val, sek):
x = StringIO.StringIO()
x.write(val)
x.seek(sek)
return x
if hasattr(StringIO, 'OutputType'):
copy_reg.pickle(StringIO.OutputType,
pickleStringO,
unpickleStringO)
def pickleStringI(stringi):
return unpickleStringI, (stringi.getvalue(), stringi.tell())
def unpickleStringI(val, sek):
x = StringIO.StringIO(val)
x.seek(sek)
return x
if hasattr(StringIO, 'InputType'):
copy_reg.pickle(StringIO.InputType,
pickleStringI,
unpickleStringI)
class Ephemeral:
"""
This type of object is never persisted; if possible, even references to it
are eliminated.
"""
def __getstate__(self):
log.msg( "WARNING: serializing ephemeral %s" % self )
import gc
for r in gc.get_referrers(self):
log.msg( " referred to by %s" % (r,))
return None
def __setstate__(self, state):
log.msg( "WARNING: unserializing ephemeral %s" % self.__class__ )
self.__class__ = Ephemeral
versionedsToUpgrade = {}
upgraded = {}
def doUpgrade():
global versionedsToUpgrade, upgraded
for versioned in versionedsToUpgrade.values():
requireUpgrade(versioned)
versionedsToUpgrade = {}
upgraded = {}
def requireUpgrade(obj):
"""Require that a Versioned instance be upgraded completely first.
"""
objID = id(obj)
if objID in versionedsToUpgrade and objID not in upgraded:
upgraded[objID] = 1
obj.versionUpgrade()
return obj
from twisted.python import reflect
def _aybabtu(c):
l = []
for b in reflect.allYourBase(c, Versioned):
if b not in l and b is not Versioned:
l.append(b)
return l
class Versioned:
"""
This type of object is persisted with versioning information.
I have a single class attribute, the int persistenceVersion. After I am
unserialized (and styles.doUpgrade() is called), self.upgradeToVersionX()
will be called for each version upgrade I must undergo.
For example, if I serialize an instance of a Foo(Versioned) at version 4
and then unserialize it when the code is at version 9, the calls::
self.upgradeToVersion5()
self.upgradeToVersion6()
self.upgradeToVersion7()
self.upgradeToVersion8()
self.upgradeToVersion9()
will be made. If any of these methods are undefined, a warning message
will be printed.
"""
persistenceVersion = 0
persistenceForgets = ()
def __setstate__(self, state):
versionedsToUpgrade[id(self)] = self
self.__dict__ = state
def __getstate__(self, dict=None):
"""Get state, adding a version number to it on its way out.
"""
dct = copy.copy(dict or self.__dict__)
bases = _aybabtu(self.__class__)
bases.reverse()
bases.append(self.__class__) # don't forget me!!
for base in bases:
if base.__dict__.has_key('persistenceForgets'):
for slot in base.persistenceForgets:
if dct.has_key(slot):
del dct[slot]
if base.__dict__.has_key('persistenceVersion'):
dct['%s.persistenceVersion' % reflect.qual(base)] = base.persistenceVersion
return dct
def versionUpgrade(self):
"""(internal) Do a version upgrade.
"""
bases = _aybabtu(self.__class__)
# put the bases in order so superclasses' persistenceVersion methods
# will be called first.
bases.reverse()
bases.append(self.__class__) # don't forget me!!
# first let's look for old-skool versioned's
if self.__dict__.has_key("persistenceVersion"):
# Hacky heuristic: if more than one class subclasses Versioned,
# we'll assume that the higher version number wins for the older
# class, so we'll consider the attribute the version of the older
# class. There are obviously possibly times when this will
# eventually be an incorrect assumption, but hopefully old-school
# persistenceVersion stuff won't make it that far into multiple
# classes inheriting from Versioned.
pver = self.__dict__['persistenceVersion']
del self.__dict__['persistenceVersion']
highestVersion = 0
highestBase = None
for base in bases:
if not base.__dict__.has_key('persistenceVersion'):
continue
if base.persistenceVersion > highestVersion:
highestBase = base
highestVersion = base.persistenceVersion
if highestBase:
self.__dict__['%s.persistenceVersion' % reflect.qual(highestBase)] = pver
for base in bases:
# ugly hack, but it's what the user expects, really
if (Versioned not in base.__bases__ and
not base.__dict__.has_key('persistenceVersion')):
continue
currentVers = base.persistenceVersion
pverName = '%s.persistenceVersion' % reflect.qual(base)
persistVers = (self.__dict__.get(pverName) or 0)
if persistVers:
del self.__dict__[pverName]
assert persistVers <= currentVers, "Sorry, can't go backwards in time."
while persistVers < currentVers:
persistVers = persistVers + 1
method = base.__dict__.get('upgradeToVersion%s' % persistVers, None)
if method:
log.msg( "Upgrading %s (of %s @ %s) to version %s" % (reflect.qual(base), reflect.qual(self.__class__), id(self), persistVers) )
method(self)
else:
log.msg( 'Warning: cannot upgrade %s to version %s' % (base, persistVers) ) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/persisted/styles.py | styles.py |
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
"""
AOT: Abstract Object Trees
The source-code-marshallin'est abstract-object-serializin'est persister
this side of Marmalade!
"""
import types, new, string, copy_reg, tokenize, re
from twisted.python import reflect, log
from twisted.persisted import crefutil
###########################
# Abstract Object Classes #
###########################
#"\0" in a getSource means "insert variable-width indention here".
#see `indentify'.
class Named:
def __init__(self, name):
self.name = name
class Class(Named):
def getSource(self):
return "Class(%r)" % self.name
class Function(Named):
def getSource(self):
return "Function(%r)" % self.name
class Module(Named):
def getSource(self):
return "Module(%r)" % self.name
class InstanceMethod:
def __init__(self, name, klass, inst):
if not (isinstance(inst, Ref) or isinstance(inst, Instance) or isinstance(inst, Deref)):
raise TypeError("%s isn't an Instance, Ref, or Deref!" % inst)
self.name = name
self.klass = klass
self.instance = inst
def getSource(self):
return "InstanceMethod(%r, %r, \n\0%s)" % (self.name, self.klass, prettify(self.instance))
class _NoStateObj:
pass
NoStateObj = _NoStateObj()
_SIMPLE_BUILTINS = [
types.StringType, types.UnicodeType, types.IntType, types.FloatType,
types.ComplexType, types.LongType, types.NoneType, types.SliceType,
types.EllipsisType]
try:
_SIMPLE_BUILTINS.append(types.BooleanType)
except AttributeError:
pass
class Instance:
def __init__(self, className, __stateObj__=NoStateObj, **state):
if not isinstance(className, types.StringType):
raise TypeError("%s isn't a string!" % className)
self.klass = className
if __stateObj__ is not NoStateObj:
self.state = __stateObj__
self.stateIsDict = 0
else:
self.state = state
self.stateIsDict = 1
def getSource(self):
#XXX make state be foo=bar instead of a dict.
if self.stateIsDict:
stateDict = self.state
elif isinstance(self.state, Ref) and isinstance(self.state.obj, types.DictType):
stateDict = self.state.obj
else:
stateDict = None
if stateDict is not None:
try:
return "Instance(%r, %s)" % (self.klass, dictToKW(stateDict))
except NonFormattableDict:
return "Instance(%r, %s)" % (self.klass, prettify(stateDict))
return "Instance(%r, %s)" % (self.klass, prettify(self.state))
class Ref:
def __init__(self, *args):
#blargh, lame.
if len(args) == 2:
self.refnum = args[0]
self.obj = args[1]
elif not args:
self.refnum = None
self.obj = None
def setRef(self, num):
if self.refnum:
raise ValueError("Error setting id %s, I already have %s" % (num, self.refnum))
self.refnum = num
def setObj(self, obj):
if self.obj:
raise ValueError("Error setting obj %s, I already have %s" % (obj, self.obj))
self.obj = obj
def getSource(self):
if self.obj is None:
raise RuntimeError("Don't try to display me before setting an object on me!")
if self.refnum:
return "Ref(%d, \n\0%s)" % (self.refnum, prettify(self.obj))
return prettify(self.obj)
class Deref:
def __init__(self, num):
self.refnum = num
def getSource(self):
return "Deref(%d)" % self.refnum
__repr__ = getSource
class Copyreg:
def __init__(self, loadfunc, state):
self.loadfunc = loadfunc
self.state = state
def getSource(self):
return "Copyreg(%r, %s)" % (self.loadfunc, prettify(self.state))
###############
# Marshalling #
###############
def getSource(ao):
"""Pass me an AO, I'll return a nicely-formatted source representation."""
return indentify("app = " + prettify(ao))
class NonFormattableDict(Exception):
"""A dictionary was not formattable.
"""
r = re.compile('[a-zA-Z_][a-zA-Z0-9_]*$')
def dictToKW(d):
out = []
items = d.items()
items.sort()
for k,v in items:
if not isinstance(k, types.StringType):
raise NonFormattableDict("%r ain't a string" % k)
if not r.match(k):
raise NonFormattableDict("%r ain't an identifier" % k)
out.append(
"\n\0%s=%s," % (k, prettify(v))
)
return string.join(out, '')
def prettify(obj):
if hasattr(obj, 'getSource'):
return obj.getSource()
else:
#basic type
t = type(obj)
if t in _SIMPLE_BUILTINS:
return repr(obj)
elif t is types.DictType:
out = ['{']
for k,v in obj.items():
out.append('\n\0%s: %s,' % (prettify(k), prettify(v)))
out.append(len(obj) and '\n\0}' or '}')
return string.join(out, '')
elif t is types.ListType:
out = ["["]
for x in obj:
out.append('\n\0%s,' % prettify(x))
out.append(len(obj) and '\n\0]' or ']')
return string.join(out, '')
elif t is types.TupleType:
out = ["("]
for x in obj:
out.append('\n\0%s,' % prettify(x))
out.append(len(obj) and '\n\0)' or ')')
return string.join(out, '')
else:
raise TypeError("Unsupported type %s when trying to prettify %s." % (t, obj))
def indentify(s):
out = []
stack = []
def eater(type, val, r, c, l, out=out, stack=stack):
#import sys
#sys.stdout.write(val)
if val in ['[', '(', '{']:
stack.append(val)
elif val in [']', ')', '}']:
stack.pop()
if val == '\0':
out.append(' '*len(stack))
else:
out.append(val)
l = ['', s]
tokenize.tokenize(l.pop, eater)
return string.join(out, '')
###########
# Unjelly #
###########
def unjellyFromAOT(aot):
"""
Pass me an Abstract Object Tree, and I'll unjelly it for you.
"""
return AOTUnjellier().unjelly(aot)
def unjellyFromSource(stringOrFile):
"""
Pass me a string of code or a filename that defines an 'app' variable (in
terms of Abstract Objects!), and I'll execute it and unjelly the resulting
AOT for you, returning a newly unpersisted Application object!
"""
ns = {"Instance": Instance,
"InstanceMethod": InstanceMethod,
"Class": Class,
"Function": Function,
"Module": Module,
"Ref": Ref,
"Deref": Deref,
"Copyreg": Copyreg,
}
if hasattr(stringOrFile, "read"):
exec stringOrFile.read() in ns
else:
exec stringOrFile in ns
if ns.has_key('app'):
return unjellyFromAOT(ns['app'])
else:
raise ValueError("%s needs to define an 'app', it didn't!" % stringOrFile)
class AOTUnjellier:
"""I handle the unjellying of an Abstract Object Tree.
See AOTUnjellier.unjellyAO
"""
def __init__(self):
self.references = {}
self.stack = []
self.afterUnjelly = []
##
# unjelly helpers (copied pretty much directly from marmalade XXX refactor)
##
def unjellyLater(self, node):
"""Unjelly a node, later.
"""
d = crefutil._Defer()
self.unjellyInto(d, 0, node)
return d
def unjellyInto(self, obj, loc, ao):
"""Utility method for unjellying one object into another.
This automates the handling of backreferences.
"""
o = self.unjellyAO(ao)
obj[loc] = o
if isinstance(o, crefutil.NotKnown):
o.addDependant(obj, loc)
return o
def callAfter(self, callable, result):
if isinstance(result, crefutil.NotKnown):
l = [None]
result.addDependant(l, 1)
else:
l = [result]
self.afterUnjelly.append((callable, l))
def unjellyAttribute(self, instance, attrName, ao):
#XXX this is unused????
"""Utility method for unjellying into instances of attributes.
Use this rather than unjellyAO unless you like surprising bugs!
Alternatively, you can use unjellyInto on your instance's __dict__.
"""
self.unjellyInto(instance.__dict__, attrName, ao)
def unjellyAO(self, ao):
"""Unjelly an Abstract Object and everything it contains.
I return the real object.
"""
self.stack.append(ao)
t = type(ao)
if t is types.InstanceType:
#Abstract Objects
c = ao.__class__
if c is Module:
return reflect.namedModule(ao.name)
elif c in [Class, Function] or issubclass(c, type):
return reflect.namedObject(ao.name)
elif c is InstanceMethod:
im_name = ao.name
im_class = reflect.namedObject(ao.klass)
im_self = self.unjellyAO(ao.instance)
if im_class.__dict__.has_key(im_name):
if im_self is None:
return getattr(im_class, im_name)
elif isinstance(im_self, crefutil.NotKnown):
return crefutil._InstanceMethod(im_name, im_self, im_class)
else:
return new.instancemethod(im_class.__dict__[im_name],
im_self,
im_class)
else:
raise "instance method changed"
elif c is Instance:
klass = reflect.namedObject(ao.klass)
state = self.unjellyAO(ao.state)
if hasattr(klass, "__setstate__"):
inst = new.instance(klass, {})
self.callAfter(inst.__setstate__, state)
else:
inst = new.instance(klass, state)
return inst
elif c is Ref:
o = self.unjellyAO(ao.obj) #THIS IS CHANGING THE REF OMG
refkey = ao.refnum
ref = self.references.get(refkey)
if ref is None:
self.references[refkey] = o
elif isinstance(ref, crefutil.NotKnown):
ref.resolveDependants(o)
self.references[refkey] = o
elif refkey is None:
# This happens when you're unjellying from an AOT not read from source
pass
else:
raise ValueError("Multiple references with the same ID: %s, %s, %s!" % (ref, refkey, ao))
return o
elif c is Deref:
num = ao.refnum
ref = self.references.get(num)
if ref is None:
der = crefutil._Dereference(num)
self.references[num] = der
return der
return ref
elif c is Copyreg:
loadfunc = reflect.namedObject(ao.loadfunc)
d = self.unjellyLater(ao.state).addCallback(
lambda result, _l: apply(_l, result), loadfunc)
return d
#Types
elif t in _SIMPLE_BUILTINS:
return ao
elif t is types.ListType:
l = []
for x in ao:
l.append(None)
self.unjellyInto(l, len(l)-1, x)
return l
elif t is types.TupleType:
l = []
tuple_ = tuple
for x in ao:
l.append(None)
if isinstance(self.unjellyInto(l, len(l)-1, x), crefutil.NotKnown):
tuple_ = crefutil._Tuple
return tuple_(l)
elif t is types.DictType:
d = {}
for k,v in ao.items():
kvd = crefutil._DictKeyAndValue(d)
self.unjellyInto(kvd, 0, k)
self.unjellyInto(kvd, 1, v)
return d
else:
raise TypeError("Unsupported AOT type: %s" % t)
del self.stack[-1]
def unjelly(self, ao):
try:
l = [None]
self.unjellyInto(l, 0, ao)
for callable, v in self.afterUnjelly:
callable(v[0])
return l[0]
except:
log.msg("Error jellying object! Stacktrace follows::")
log.msg(string.join(map(repr, self.stack), "\n"))
raise
#########
# Jelly #
#########
def jellyToAOT(obj):
"""Convert an object to an Abstract Object Tree."""
return AOTJellier().jelly(obj)
def jellyToSource(obj, file=None):
"""
Pass me an object and, optionally, a file object.
I'll convert the object to an AOT either return it (if no file was
specified) or write it to the file.
"""
aot = jellyToAOT(obj)
if file:
file.write(getSource(aot))
else:
return getSource(aot)
class AOTJellier:
def __init__(self):
# dict of {id(obj): (obj, node)}
self.prepared = {}
self._ref_id = 0
self.stack = []
def prepareForRef(self, aoref, object):
"""I prepare an object for later referencing, by storing its id()
and its _AORef in a cache."""
self.prepared[id(object)] = aoref
def jellyToAO(self, obj):
"""I turn an object into an AOT and return it."""
objType = type(obj)
self.stack.append(repr(obj))
#immutable: We don't care if these have multiple refs!
if objType in _SIMPLE_BUILTINS:
retval = obj
elif objType is types.MethodType:
# TODO: make methods 'prefer' not to jelly the object internally,
# so that the object will show up where it's referenced first NOT
# by a method.
retval = InstanceMethod(obj.im_func.__name__, reflect.qual(obj.im_class),
self.jellyToAO(obj.im_self))
elif objType is types.ModuleType:
retval = Module(obj.__name__)
elif objType is types.ClassType:
retval = Class(reflect.qual(obj))
elif issubclass(objType, type):
retval = Class(reflect.qual(obj))
elif objType is types.FunctionType:
retval = Function(reflect.fullFuncName(obj))
else: #mutable! gotta watch for refs.
#Marmalade had the nicety of being able to just stick a 'reference' attribute
#on any Node object that was referenced, but in AOT, the referenced object
#is *inside* of a Ref call (Ref(num, obj) instead of
#<objtype ... reference="1">). The problem is, especially for built-in types,
#I can't just assign some attribute to them to give them a refnum. So, I have
#to "wrap" a Ref(..) around them later -- that's why I put *everything* that's
#mutable inside one. The Ref() class will only print the "Ref(..)" around an
#object if it has a Reference explicitly attached.
if self.prepared.has_key(id(obj)):
oldRef = self.prepared[id(obj)]
if oldRef.refnum:
# it's been referenced already
key = oldRef.refnum
else:
# it hasn't been referenced yet
self._ref_id = self._ref_id + 1
key = self._ref_id
oldRef.setRef(key)
return Deref(key)
retval = Ref()
self.prepareForRef(retval, obj)
if objType is types.ListType:
retval.setObj(map(self.jellyToAO, obj)) #hah!
elif objType is types.TupleType:
retval.setObj(tuple(map(self.jellyToAO, obj)))
elif objType is types.DictionaryType:
d = {}
for k,v in obj.items():
d[self.jellyToAO(k)] = self.jellyToAO(v)
retval.setObj(d)
elif objType is types.InstanceType:
if hasattr(obj, "__getstate__"):
state = self.jellyToAO(obj.__getstate__())
else:
state = self.jellyToAO(obj.__dict__)
retval.setObj(Instance(reflect.qual(obj.__class__), state))
elif copy_reg.dispatch_table.has_key(objType):
unpickleFunc, state = copy_reg.dispatch_table[objType](obj)
retval.setObj(Copyreg( reflect.fullFuncName(unpickleFunc),
self.jellyToAO(state)))
else:
raise "Unsupported type: %s" % objType.__name__
del self.stack[-1]
return retval
def jelly(self, obj):
try:
ao = self.jellyToAO(obj)
return ao
except:
log.msg("Error jellying object! Stacktrace follows::")
log.msg(string.join(self.stack, '\n'))
raise | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/persisted/aot.py | aot.py |
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
"""Marmalade: jelly, with just a hint of bitterness.
I can serialize a Python object to an XML DOM tree (twisted.web.microdom), and
therefore to XML data, similarly to twisted.spread.jelly. Because both Python
lists and DOM trees are tree data-structures, many of the idioms used here are
identical.
"""
import warnings
warnings.warn("twisted.persisted.marmalade is deprecated", DeprecationWarning, stacklevel=2)
import new
from twisted.python.reflect import namedModule, namedClass, namedObject, fullFuncName, qual
from twisted.persisted.crefutil import NotKnown, _Tuple, _InstanceMethod, _DictKeyAndValue, _Dereference, _Defer
try:
from new import instancemethod
except:
from org.python.core import PyMethod
instancemethod = PyMethod
import types
import copy_reg
#for some reason, __builtins__ == __builtin__.__dict__ in the context where this is used.
#Can someone tell me why?
import __builtin__
def instance(klass, d):
if isinstance(klass, types.ClassType):
return new.instance(klass, d)
elif isinstance(klass, type):
o = object.__new__(klass)
o.__dict__ = d
return o
else:
raise TypeError, "%s is not a class" % klass
def getValueElement(node):
"""Get the one child element of a given element.
If there is more than one child element, raises ValueError. Otherwise,
returns the value element.
"""
valueNode = None
for subnode in node.childNodes:
if isinstance(subnode, Element):
if valueNode is None:
valueNode = subnode
else:
raise ValueError("Only one value node allowed per instance!")
return valueNode
class DOMJellyable:
jellyDOMVersion = 1
def jellyToDOM(self, jellier, element):
element.setAttribute("marmalade:version", str(self.jellyDOMVersion))
method = getattr(self, "jellyToDOM_%s" % self.jellyDOMVersion, None)
if method:
method(jellier, element)
else:
element.appendChild(jellier.jellyToNode(self.__dict__))
def unjellyFromDOM(self, unjellier, element):
pDOMVersion = element.getAttribute("marmalade:version") or "0"
method = getattr(self, "unjellyFromDOM_%s" % pDOMVersion, None)
if method:
method(unjellier, element)
else:
# XXX: DOMJellyable.unjellyNode does not exist
# XXX: 'node' is undefined - did you mean 'self', 'element', or 'Node'?
state = self.unjellyNode(getValueElement(node))
if hasattr(self.__class__, "__setstate__"):
self.__setstate__(state)
else:
self.__dict__ = state
class DOMUnjellier:
def __init__(self):
self.references = {}
self._savedLater = []
def unjellyLater(self, node):
"""Unjelly a node, later.
"""
d = _Defer()
self.unjellyInto(d, 0, node)
self._savedLater.append(d)
return d
def unjellyInto(self, obj, loc, node):
"""Utility method for unjellying one object into another.
This automates the handling of backreferences.
"""
o = self.unjellyNode(node)
obj[loc] = o
if isinstance(o, NotKnown):
o.addDependant(obj, loc)
return o
def unjellyAttribute(self, instance, attrName, valueNode):
"""Utility method for unjellying into instances of attributes.
Use this rather than unjellyNode unless you like surprising bugs!
Alternatively, you can use unjellyInto on your instance's __dict__.
"""
self.unjellyInto(instance.__dict__, attrName, valueNode)
def unjellyNode(self, node):
if node.tagName.lower() == "none":
retval = None
elif node.tagName == "string":
# XXX FIXME this is obviously insecure
# if you doubt:
# >>> unjellyFromXML('''<string value="h"+str(__import__("sys"))+"i" />''')
# "h<module 'sys' (built-in)>i"
retval = str(eval('"%s"' % node.getAttribute("value")))
elif node.tagName == "int":
retval = int(node.getAttribute("value"))
elif node.tagName == "float":
retval = float(node.getAttribute("value"))
elif node.tagName == "longint":
retval = long(node.getAttribute("value"))
elif node.tagName == "bool":
retval = int(node.getAttribute("value"))
if retval:
retval = True
else:
retval = False
elif node.tagName == "module":
retval = namedModule(str(node.getAttribute("name")))
elif node.tagName == "class":
retval = namedClass(str(node.getAttribute("name")))
elif node.tagName == "unicode":
retval = unicode(str(node.getAttribute("value")).replace("\\n", "\n").replace("\\t", "\t"), "raw_unicode_escape")
elif node.tagName == "function":
retval = namedObject(str(node.getAttribute("name")))
elif node.tagName == "method":
im_name = node.getAttribute("name")
im_class = namedClass(node.getAttribute("class"))
im_self = self.unjellyNode(getValueElement(node))
if im_class.__dict__.has_key(im_name):
if im_self is None:
retval = getattr(im_class, im_name)
elif isinstance(im_self, NotKnown):
retval = _InstanceMethod(im_name, im_self, im_class)
else:
retval = instancemethod(im_class.__dict__[im_name],
im_self,
im_class)
else:
raise "instance method changed"
elif node.tagName == "tuple":
l = []
tupFunc = tuple
for subnode in node.childNodes:
if isinstance(subnode, Element):
l.append(None)
if isinstance(self.unjellyInto(l, len(l)-1, subnode), NotKnown):
tupFunc = _Tuple
retval = tupFunc(l)
elif node.tagName == "list":
l = []
finished = 1
for subnode in node.childNodes:
if isinstance(subnode, Element):
l.append(None)
self.unjellyInto(l, len(l)-1, subnode)
retval = l
elif node.tagName == "dictionary":
d = {}
keyMode = 1
for subnode in node.childNodes:
if isinstance(subnode, Element):
if keyMode:
kvd = _DictKeyAndValue(d)
if not subnode.getAttribute("role") == "key":
raise "Unjellying Error: key role not set"
self.unjellyInto(kvd, 0, subnode)
else:
self.unjellyInto(kvd, 1, subnode)
keyMode = not keyMode
retval = d
elif node.tagName == "instance":
className = node.getAttribute("class")
clasz = namedClass(className)
if issubclass(clasz, DOMJellyable):
retval = instance(clasz, {})
retval.unjellyFromDOM(self, node)
else:
state = self.unjellyNode(getValueElement(node))
if hasattr(clasz, "__setstate__"):
inst = instance(clasz, {})
inst.__setstate__(state)
else:
inst = instance(clasz, state)
retval = inst
elif node.tagName == "reference":
refkey = node.getAttribute("key")
retval = self.references.get(refkey)
if retval is None:
der = _Dereference(refkey)
self.references[refkey] = der
retval = der
elif node.tagName == "copyreg":
nodefunc = namedObject(node.getAttribute("loadfunc"))
loaddef = self.unjellyLater(getValueElement(node)).addCallback(
lambda result, _l: apply(_l, result), nodefunc)
retval = loaddef
else:
raise "Unsupported Node Type: %s" % str(node.tagName)
if node.hasAttribute("reference"):
refkey = node.getAttribute("reference")
ref = self.references.get(refkey)
if ref is None:
self.references[refkey] = retval
elif isinstance(ref, NotKnown):
ref.resolveDependants(retval)
self.references[refkey] = retval
else:
assert 0, "Multiple references with the same ID!"
return retval
def unjelly(self, doc):
l = [None]
self.unjellyInto(l, 0, doc.childNodes[0])
for svd in self._savedLater:
svd.unpause()
return l[0]
class DOMJellier:
def __init__(self):
# dict of {id(obj): (obj, node)}
self.prepared = {}
self.document = Document()
self._ref_id = 0
def prepareElement(self, element, object):
self.prepared[id(object)] = (object, element)
def jellyToNode(self, obj):
"""Create a node representing the given object and return it.
"""
objType = type(obj)
#immutable (We don't care if these have multiple refs)
if objType is types.NoneType:
node = self.document.createElement("None")
elif objType is types.StringType:
node = self.document.createElement("string")
r = repr(obj)
if r[0] == '"':
r = r.replace("'", "\\'")
else:
r = r.replace('"', '\\"')
node.setAttribute("value", r[1:-1])
# node.appendChild(CDATASection(obj))
elif objType is types.IntType:
node = self.document.createElement("int")
node.setAttribute("value", str(obj))
elif objType is types.LongType:
node = self.document.createElement("longint")
s = str(obj)
if s[-1] == 'L':
s = s[:-1]
node.setAttribute("value", s)
elif objType is types.FloatType:
node = self.document.createElement("float")
node.setAttribute("value", repr(obj))
elif objType is types.MethodType:
node = self.document.createElement("method")
node.setAttribute("name", obj.im_func.__name__)
node.setAttribute("class", qual(obj.im_class))
# TODO: make methods 'prefer' not to jelly the object internally,
# so that the object will show up where it's referenced first NOT
# by a method.
node.appendChild(self.jellyToNode(obj.im_self))
elif hasattr(types, 'BooleanType') and objType is types.BooleanType:
node = self.document.createElement("bool")
node.setAttribute("value", str(int(obj)))
elif objType is types.ModuleType:
node = self.document.createElement("module")
node.setAttribute("name", obj.__name__)
elif objType==types.ClassType or issubclass(objType, type):
node = self.document.createElement("class")
node.setAttribute("name", qual(obj))
elif objType is types.UnicodeType:
node = self.document.createElement("unicode")
obj = obj.encode('raw_unicode_escape')
s = obj.replace("\n", "\\n").replace("\t", "\\t")
node.setAttribute("value", s)
elif objType in (types.FunctionType, types.BuiltinFunctionType):
# TODO: beat pickle at its own game, and do BuiltinFunctionType
# separately, looking for __self__ attribute and unpickling methods
# of C objects when possible.
node = self.document.createElement("function")
node.setAttribute("name", fullFuncName(obj))
else:
#mutable!
if self.prepared.has_key(id(obj)):
oldNode = self.prepared[id(obj)][1]
if oldNode.hasAttribute("reference"):
# it's been referenced already
key = oldNode.getAttribute("reference")
else:
# it hasn't been referenced yet
self._ref_id = self._ref_id + 1
key = str(self._ref_id)
oldNode.setAttribute("reference", key)
node = self.document.createElement("reference")
node.setAttribute("key", key)
return node
node = self.document.createElement("UNNAMED")
self.prepareElement(node, obj)
if objType is types.ListType or __builtin__.__dict__.has_key('object') and isinstance(obj, NodeList):
node.tagName = "list"
for subobj in obj:
node.appendChild(self.jellyToNode(subobj))
elif objType is types.TupleType:
node.tagName = "tuple"
for subobj in obj:
node.appendChild(self.jellyToNode(subobj))
elif objType is types.DictionaryType:
node.tagName = "dictionary"
for k, v in obj.items():
n = self.jellyToNode(k)
n.setAttribute("role", "key")
n2 = self.jellyToNode(v)
node.appendChild(n)
node.appendChild(n2)
elif copy_reg.dispatch_table.has_key(objType):
unpickleFunc, state = copy_reg.dispatch_table[objType](obj)
node = self.document.createElement("copyreg")
# node.setAttribute("type", objType.__name__)
node.setAttribute("loadfunc", fullFuncName(unpickleFunc))
node.appendChild(self.jellyToNode(state))
elif objType is types.InstanceType or hasattr(objType, "__module__"):
className = qual(obj.__class__)
node.tagName = "instance"
node.setAttribute("class", className)
if isinstance(obj, DOMJellyable):
obj.jellyToDOM(self, node)
else:
if hasattr(obj, "__getstate__"):
state = obj.__getstate__()
else:
state = obj.__dict__
n = self.jellyToNode(state)
node.appendChild(n)
else:
raise "Unsupported type: %s" % objType.__name__
return node
def jelly(self, obj):
"""Create a document representing the current object, and return it.
"""
node = self.jellyToNode(obj)
self.document.appendChild(node)
return self.document
def jellyToDOM(object):
"""Convert an Object into an twisted.web.microdom.Document.
"""
dj = DOMJellier()
document = dj.jelly(object)
return document
def unjellyFromDOM(document):
"""Convert an twisted.web.microdom.Document into a Python object.
"""
du = DOMUnjellier()
return du.unjelly(document)
def jellyToXML(object, file=None):
"""jellyToXML(object, [file]) -> None | string
Converts a Python object to an XML stream. If you pass a file, the XML
will be written to that file; otherwise, a string of the XML will be
returned.
"""
document = jellyToDOM(object)
if file:
document.writexml(file, "", " ", "\n")
else:
return document.toprettyxml(" ", "\n")
def unjellyFromXML(stringOrFile):
"""I convert a string or the contents of an XML file into a Python object.
"""
if hasattr(stringOrFile, "read"):
document = parse(stringOrFile)
else:
document = parseString(stringOrFile)
return unjellyFromDOM(document)
from twisted.web.microdom import Element, Document, parse, parseString, NodeList | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/persisted/marmalade.py | marmalade.py |
import os
import types
import base64
import glob
try:
import cPickle as pickle
except ImportError:
import pickle
try:
_open
except NameError:
_open = open
class DirDBM:
"""A directory with a DBM interface.
This class presents a hash-like interface to a directory of small,
flat files. It can only use strings as keys or values.
"""
def __init__(self, name):
"""
@type name: str
@param name: Base path to use for the directory storage.
"""
self.dname = os.path.abspath(name)
if not os.path.isdir(self.dname):
os.mkdir(self.dname)
else:
# Run recovery, in case we crashed. we delete all files ending
# with ".new". Then we find all files who end with ".rpl". If a
# corresponding file exists without ".rpl", we assume the write
# failed and delete the ".rpl" file. If only a ".rpl" exist we
# assume the program crashed right after deleting the old entry
# but before renaming the replacement entry.
#
# NOTE: '.' is NOT in the base64 alphabet!
for f in glob.glob(os.path.join(self.dname, "*.new")):
os.remove(f)
replacements = glob.glob(os.path.join(self.dname, "*.rpl"))
for f in replacements:
old = f[:-4]
if os.path.exists(old):
os.remove(f)
else:
os.rename(f, old)
def _encode(self, k):
"""Encode a key so it can be used as a filename.
"""
# NOTE: '_' is NOT in the base64 alphabet!
return base64.encodestring(k).replace('\n', '_').replace("/", "-")
def _decode(self, k):
"""Decode a filename to get the key.
"""
return base64.decodestring(k.replace('_', '\n').replace("-", "/"))
def _readFile(self, path):
"""Read in the contents of a file.
Override in subclasses to e.g. provide transparently encrypted dirdbm.
"""
f = _open(path, "rb")
s = f.read()
f.close()
return s
def _writeFile(self, path, data):
"""Write data to a file.
Override in subclasses to e.g. provide transparently encrypted dirdbm.
"""
f = _open(path, "wb")
f.write(data)
f.flush()
f.close()
def __len__(self):
"""
@return: The number of key/value pairs in this Shelf
"""
return len(os.listdir(self.dname))
def __setitem__(self, k, v):
"""
C{dirdbm[k] = v}
Create or modify a textfile in this directory
@type k: str
@param k: key to set
@type v: str
@param v: value to associate with C{k}
"""
assert type(k) == types.StringType, AssertionError("DirDBM key must be a string")
assert type(v) == types.StringType, AssertionError("DirDBM value must be a string")
k = self._encode(k)
# we create a new file with extension .new, write the data to it, and
# if the write succeeds delete the old file and rename the new one.
old = os.path.join(self.dname, k)
if os.path.exists(old):
new = old + ".rpl" # replacement entry
else:
new = old + ".new" # new entry
try:
self._writeFile(new, v)
except:
os.remove(new)
raise
else:
if os.path.exists(old): os.remove(old)
os.rename(new, old)
def __getitem__(self, k):
"""
C{dirdbm[k]}
Get the contents of a file in this directory as a string.
@type k: str
@param k: key to lookup
@return: The value associated with C{k}
@raise KeyError: Raised when there is no such key
"""
assert type(k) == types.StringType, AssertionError("DirDBM key must be a string")
path = os.path.join(self.dname, self._encode(k))
try:
return self._readFile(path)
except:
raise KeyError, k
def __delitem__(self, k):
"""
C{del dirdbm[foo]}
Delete a file in this directory.
@type k: str
@param k: key to delete
@raise KeyError: Raised when there is no such key
"""
assert type(k) == types.StringType, AssertionError("DirDBM key must be a string")
k = self._encode(k)
try: os.remove(os.path.join(self.dname, k))
except (OSError, IOError): raise KeyError(self._decode(k))
def keys(self):
"""
@return: a C{list} of filenames (keys).
"""
return map(self._decode, os.listdir(self.dname))
def values(self):
"""
@return: a C{list} of file-contents (values).
"""
vals = []
keys = self.keys()
for key in keys:
vals.append(self[key])
return vals
def items(self):
"""
@return: a C{list} of 2-tuples containing key/value pairs.
"""
items = []
keys = self.keys()
for key in keys:
items.append((key, self[key]))
return items
def has_key(self, key):
"""
@type key: str
@param key: The key to test
@return: A true value if this dirdbm has the specified key, a faluse
value otherwise.
"""
assert type(key) == types.StringType, AssertionError("DirDBM key must be a string")
key = self._encode(key)
return os.path.isfile(os.path.join(self.dname, key))
def setdefault(self, key, value):
"""
@type key: str
@param key: The key to lookup
@param value: The value to associate with key if key is not already
associated with a value.
"""
if not self.has_key(key):
self[key] = value
return value
return self[key]
def get(self, key, default = None):
"""
@type key: str
@param key: The key to lookup
@param default: The value to return if the given key does not exist
@return: The value associated with C{key} or C{default} if not
C{self.has_key(key)}
"""
if self.has_key(key):
return self[key]
else:
return default
def __contains__(self, key):
"""
C{key in dirdbm}
@type key: str
@param key: The key to test
@return: A true value if C{self.has_key(key)}, a false value otherwise.
"""
assert type(key) == types.StringType, AssertionError("DirDBM key must be a string")
key = self._encode(key)
return os.path.isfile(os.path.join(self.dname, key))
def update(self, dict):
"""
Add all the key/value pairs in C{dict} to this dirdbm. Any conflicting
keys will be overwritten with the values from C{dict}.
@type dict: mapping
@param dict: A mapping of key/value pairs to add to this dirdbm.
"""
for key, val in dict.items():
self[key]=val
def copyTo(self, path):
"""
Copy the contents of this dirdbm to the dirdbm at C{path}.
@type path: C{str}
@param path: The path of the dirdbm to copy to. If a dirdbm
exists at the destination path, it is cleared first.
@rtype: C{DirDBM}
@return: The dirdbm this dirdbm was copied to.
"""
path = os.path.abspath(path)
assert path != self.dname
d = self.__class__(path)
d.clear()
for k in self.keys():
d[k] = self[k]
return d
def clear(self):
"""
Delete all key/value pairs in this dirdbm.
"""
for k in self.keys():
del self[k]
def close(self):
"""
Close this dbm: no-op, for dbm-style interface compliance.
"""
def getModificationTime(self, key):
"""
Returns modification time of an entry.
@return: Last modification date (seconds since epoch) of entry C{key}
@raise KeyError: Raised when there is no such key
"""
assert type(key) == types.StringType, AssertionError("DirDBM key must be a string")
path = os.path.join(self.dname, self._encode(key))
if os.path.isfile(path):
return os.path.getmtime(path)
else:
raise KeyError, key
class Shelf(DirDBM):
"""A directory with a DBM shelf interface.
This class presents a hash-like interface to a directory of small,
flat files. Keys must be strings, but values can be any given object.
"""
def __setitem__(self, k, v):
"""
C{shelf[foo] = bar}
Create or modify a textfile in this directory.
@type k: str
@param k: The key to set
@param v: The value to associate with C{key}
"""
v = pickle.dumps(v)
DirDBM.__setitem__(self, k, v)
def __getitem__(self, k):
"""
C{dirdbm[foo]}
Get and unpickle the contents of a file in this directory.
@type k: str
@param k: The key to lookup
@return: The value associated with the given key
@raise KeyError: Raised if the given key does not exist
"""
return pickle.loads(DirDBM.__getitem__(self, k))
def open(file, flag = None, mode = None):
"""
This is for 'anydbm' compatibility.
@param file: The parameter to pass to the DirDBM constructor.
@param flag: ignored
@param mode: ignored
"""
return DirDBM(file)
__all__ = ["open", "DirDBM", "Shelf"] | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/persisted/dirdbm.py | dirdbm.py |
#
"""Basic classes and interfaces for journal."""
from __future__ import nested_scopes
# system imports
import os, time
try:
import cPickle as pickle
except ImportError:
import pickle
# twisted imports
from zope.interface import implements, Interface
class Journal:
"""All commands to the system get routed through here.
Subclasses should implement the actual snapshotting capability.
"""
def __init__(self, log, journaledService):
self.log = log
self.journaledService = journaledService
self.latestIndex = self.log.getCurrentIndex()
def updateFromLog(self):
"""Run all commands from log that haven't been run yet.
This method should be run on startup to ensure the snapshot
is up-to-date.
"""
snapshotIndex = self.getLastSnapshot()
if snapshotIndex < self.latestIndex:
for cmdtime, command in self.log.getCommandsSince(snapshotIndex + 1):
command.execute(self.journaledService, cmdtime)
def executeCommand(self, command):
"""Log and execute a command."""
runTime = time.time()
d = self.log.logCommand(command, runTime)
d.addCallback(self._reallyExecute, command, runTime)
return d
def _reallyExecute(self, index, command, runTime):
"""Callback called when logging command is done."""
result = command.execute(self.journaledService, runTime)
self.latestIndex = index
return result
def getLastSnapshot(self):
"""Return command index of the last snapshot taken."""
raise NotImplementedError
def sync(self, *args, **kwargs):
"""Save journal to disk, returns Deferred of finish status.
Subclasses may choose whatever signature is appropriate, or may
not implement this at all.
"""
raise NotImplementedError
class MemoryJournal(Journal):
"""Prevayler-like journal that dumps from memory to disk."""
def __init__(self, log, journaledService, path, loadedCallback):
self.path = path
if os.path.exists(path):
try:
self.lastSync, obj = pickle.load(open(path, "rb"))
except (IOError, OSError, pickle.UnpicklingError):
self.lastSync, obj = 0, None
loadedCallback(obj)
else:
self.lastSync = 0
loadedCallback(None)
Journal.__init__(self, log, journaledService)
def getLastSnapshot(self):
return self.lastSync
def sync(self, obj):
# make this more reliable at some point
f = open(self.path, "wb")
pickle.dump((self.latestIndex, obj), f, 1)
f.close()
self.lastSync = self.latestIndex
class ICommand(Interface):
"""A serializable command which interacts with a journaled service."""
def execute(journaledService, runTime):
"""Run the command and return result."""
class ICommandLog(Interface):
"""Interface for command log."""
def logCommand(command, runTime):
"""Add a command and its run time to the log.
@return: Deferred of command index.
"""
def getCurrentIndex():
"""Return index of last command that was logged."""
def getCommandsSince(index):
"""Return commands who's index >= the given one.
@return: list of (time, command) tuples, sorted with ascending times.
"""
class LoadingService:
"""Base class for journalled service used with Wrappables."""
def loadObject(self, objType, objId):
"""Return object of specified type and id."""
raise NotImplementedError
class Wrappable:
"""Base class for objects used with LoadingService."""
objectType = None # override in base class
def getUid(self):
"""Return uid for loading with LoadingService.loadObject"""
raise NotImplementedError
class WrapperCommand:
implements(ICommand)
def __init__(self, methodName, obj, args=(), kwargs={}):
self.obj = obj
self.objId = obj.getUid()
self.objType = obj.objectType
self.methodName = methodName
self.args = args
self.kwargs = kwargs
def execute(self, svc, commandTime):
if not hasattr(self, "obj"):
obj = svc.loadObject(self.objType, self.objId)
else:
obj = self.obj
return getattr(obj, self.methodName)(*self.args, **self.kwargs)
def __getstate__(self):
d = self.__dict__.copy()
del d["obj"]
return d
def command(methodName, cmdClass=WrapperCommand):
"""Wrap a method so it gets turned into command automatically.
For use with Wrappables.
Usage::
| class Foo(Wrappable):
| objectType = "foo"
| def getUid(self):
| return self.id
| def _bar(self, x):
| return x + 1
|
| bar = command('_bar')
The resulting callable will have signature identical to wrapped
function, except that it expects journal as first argument, and
returns a Deferred.
"""
def wrapper(obj, journal, *args, **kwargs):
return journal.executeCommand(cmdClass(methodName, obj, args, kwargs))
return wrapper
class ServiceWrapperCommand:
implements(ICommand)
def __init__(self, methodName, args=(), kwargs={}):
self.methodName = methodName
self.args = args
self.kwargs = kwargs
def execute(self, svc, commandTime):
return getattr(svc, self.methodName)(*self.args, **self.kwargs)
def __repr__(self):
return "<ServiceWrapperCommand: %s, %s, %s>" % (self.methodName, self.args, self.kwargs)
def __cmp__(self, other):
if hasattr(other, "__dict__"):
return cmp(self.__dict__, other.__dict__)
else:
return 0
def serviceCommand(methodName, cmdClass=ServiceWrapperCommand):
"""Wrap methods into commands for a journalled service.
The resulting callable will have signature identical to wrapped
function, except that it expects journal as first argument, and
returns a Deferred.
"""
def wrapper(obj, journal, *args, **kwargs):
return journal.executeCommand(cmdClass(methodName, args, kwargs))
return wrapper | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/persisted/journal/base.py | base.py |
#
"""Journal using twisted.enterprise.row RDBMS support.
You're going to need the following table in your database::
| CREATE TABLE journalinfo
| (
| commandIndex int
| );
| INSERT INTO journalinfo VALUES (0);
"""
from __future__ import nested_scopes
# twisted imports
from twisted.internet import defer
# sibling imports
import base
# constants for command list
INSERT, DELETE, UPDATE = range(3)
class RowJournal(base.Journal):
"""Journal that stores data 'snapshot' in using twisted.enterprise.row.
Use this as the reflector instead of the original reflector.
It may block on creation, if it has to run recovery.
"""
def __init__(self, log, journaledService, reflector):
self.reflector = reflector
self.commands = []
self.syncing = 0
base.Journal.__init__(self, log, journaledService)
def updateRow(self, obj):
"""Mark on object for updating when sync()ing."""
self.commands.append((UPDATE, obj))
def insertRow(self, obj):
"""Mark on object for inserting when sync()ing."""
self.commands.append((INSERT, obj))
def deleteRow(self, obj):
"""Mark on object for deleting when sync()ing."""
self.commands.append((DELETE, obj))
def loadObjectsFrom(self, tableName, parentRow=None, data=None, whereClause=None, forceChildren=0):
"""Flush all objects to the database and then load objects."""
d = self.sync()
d.addCallback(lambda result: self.reflector.loadObjectsFrom(
tableName, parentRow=parentRow, data=data, whereClause=whereClause,
forceChildren=forceChildren))
return d
def sync(self):
"""Commit changes to database."""
if self.syncing:
raise ValueError, "sync already in progress"
comandMap = {INSERT : self.reflector.insertRowSQL,
UPDATE : self.reflector.updateRowSQL,
DELETE : self.reflector.deleteRowSQL}
sqlCommands = []
for kind, obj in self.commands:
sqlCommands.append(comandMap[kind](obj))
self.commands = []
if sqlCommands:
self.syncing = 1
d = self.reflector.dbpool.runInteraction(self._sync, self.latestIndex, sqlCommands)
d.addCallback(self._syncDone)
return d
else:
return defer.succeed(1)
def _sync(self, txn, index, commands):
"""Do the actual database synchronization."""
for c in commands:
txn.execute(c)
txn.update("UPDATE journalinfo SET commandIndex = %d" % index)
def _syncDone(self, result):
self.syncing = 0
return result
def getLastSnapshot(self):
"""Return command index of last snapshot."""
conn = self.reflector.dbpool.connect()
cursor = conn.cursor()
cursor.execute("SELECT commandIndex FROM journalinfo")
return cursor.fetchall()[0][0] | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/persisted/journal/rowjournal.py | rowjournal.py |
from time import time, ctime
from zope.interface import implements
from twisted.words import iwords, ewords
from twisted.python.components import registerAdapter
from twisted.cred import portal, credentials, error as ecred
from twisted.spread import pb
from twisted.words.protocols import irc
from twisted.internet import defer, protocol
from twisted.python import log, failure, reflect
from twisted import copyright
class Group(object):
implements(iwords.IGroup)
def __init__(self, name):
self.name = name
self.users = {}
self.meta = {
"topic": "",
"topic_author": "",
}
def _ebUserCall(self, err, p):
return failure.Failure(Exception(p, err))
def _cbUserCall(self, results):
for (success, result) in results:
if not success:
user, err = result.value # XXX
self.remove(user, err.getErrorMessage())
def add(self, user):
assert iwords.IChatClient.providedBy(user), "%r is not a chat client" % (user,)
if user.name not in self.users:
additions = []
self.users[user.name] = user
for p in self.users.itervalues():
if p is not user:
d = defer.maybeDeferred(p.userJoined, self, user)
d.addErrback(self._ebUserCall, p=p)
additions.append(d)
defer.DeferredList(additions).addCallback(self._cbUserCall)
return defer.succeed(None)
def remove(self, user, reason=None):
assert reason is None or isinstance(reason, unicode)
try:
del self.users[user.name]
except KeyError:
pass
else:
removals = []
for p in self.users.itervalues():
if p is not user:
d = defer.maybeDeferred(p.userLeft, self, user, reason)
d.addErrback(self._ebUserCall, p=p)
removals.append(d)
defer.DeferredList(removals).addCallback(self._cbUserCall)
return defer.succeed(None)
def size(self):
return defer.succeed(len(self.users))
def receive(self, sender, recipient, message):
assert recipient is self
receives = []
for p in self.users.itervalues():
if p is not sender:
d = defer.maybeDeferred(p.receive, sender, self, message)
d.addErrback(self._ebUserCall, p=p)
receives.append(d)
defer.DeferredList(receives).addCallback(self._cbUserCall)
return defer.succeed(None)
def setMetadata(self, meta):
self.meta = meta
sets = []
for p in self.users.itervalues():
d = defer.maybeDeferred(p.groupMetaUpdate, self, meta)
d.addErrback(self._ebUserCall, p=p)
sets.append(d)
defer.DeferredList(sets).addCallback(self._cbUserCall)
return defer.succeed(None)
def iterusers(self):
# XXX Deferred?
return iter(self.users.values())
class User(object):
implements(iwords.IUser)
realm = None
mind = None
def __init__(self, name):
self.name = name
self.groups = []
self.lastMessage = time()
def loggedIn(self, realm, mind):
self.realm = realm
self.mind = mind
self.signOn = time()
def join(self, group):
def cbJoin(result):
self.groups.append(group)
return result
return group.add(self.mind).addCallback(cbJoin)
def leave(self, group, reason=None):
def cbLeave(result):
self.groups.remove(group)
return result
return group.remove(self.mind, reason).addCallback(cbLeave)
def send(self, recipient, message):
self.lastMessage = time()
return recipient.receive(self.mind, recipient, message)
def itergroups(self):
return iter(self.groups)
def logout(self):
for g in self.groups[:]:
self.leave(g)
NICKSERV = 'NickServ!NickServ@services'
class IRCUser(irc.IRC):
implements(iwords.IChatClient)
# A list of IGroups in which I am participating
groups = None
# A no-argument callable I should invoke when I go away
logout = None
# An IUser we use to interact with the chat service
avatar = None
# To whence I belong
realm = None
# How to handle unicode (TODO: Make this customizable on a per-user basis)
encoding = 'utf-8'
# Twisted callbacks
def connectionMade(self):
self.irc_PRIVMSG = self.irc_NICKSERV_PRIVMSG
def connectionLost(self, reason):
if self.logout is not None:
self.logout()
self.avatar = None
# Make sendMessage a bit more useful to us
def sendMessage(self, command, *parameter_list, **kw):
if not kw.has_key('prefix'):
kw['prefix'] = self.hostname
if not kw.has_key('to'):
kw['to'] = self.name.encode(self.encoding)
arglist = [self, command, kw['to']] + list(parameter_list)
irc.IRC.sendMessage(*arglist, **kw)
# IChatClient implementation
def userJoined(self, group, user):
self.join(
"%s!%s@%s" % (user.name, user.name, self.hostname),
'#' + group.name)
def userLeft(self, group, user, reason=None):
assert reason is None or isinstance(reason, unicode)
self.part(
"%s!%s@%s" % (user.name, user.name, self.hostname),
'#' + group.name,
(reason or u"leaving").encode(self.encoding, 'replace'))
def receive(self, sender, recipient, message):
#>> :[email protected] PRIVMSG glyph_ :hello
# omg???????????
if iwords.IGroup.providedBy(recipient):
recipientName = '#' + recipient.name
else:
recipientName = recipient.name
text = message.get('text', '<an unrepresentable message>')
for L in text.splitlines():
self.privmsg(
'%s!%s@%s' % (sender.name, sender.name, self.hostname),
recipientName,
L)
def groupMetaUpdate(self, group, meta):
if 'topic' in meta:
topic = meta['topic']
author = meta.get('topic_author', '')
self.topic(
self.name,
'#' + group.name,
topic,
'%s!%s@%s' % (author, author, self.hostname)
)
# irc.IRC callbacks - starting with login related stuff.
nickname = None
password = None
def irc_PASS(self, prefix, params):
"""Password message -- Register a password.
Parameters: <password>
[REQUIRED]
Note that IRC requires the client send this *before* NICK
and USER.
"""
self.password = params[-1]
def irc_NICK(self, prefix, params):
"""Nick message -- Set your nickname.
Parameters: <nickname>
[REQUIRED]
"""
try:
nickname = params[0].decode(self.encoding)
except UnicodeDecodeError:
self.privmsg(
NICKSERV,
nickname,
'Your nickname is cannot be decoded. Please use ASCII or UTF-8.')
self.transport.loseConnection()
return
if self.password is None:
self.nickname = nickname
self.privmsg(
NICKSERV,
nickname,
'Password?')
else:
password = self.password
self.password = None
self.logInAs(nickname, password)
def irc_USER(self, prefix, params):
"""User message -- Set your realname.
Parameters: <user> <mode> <unused> <realname>
"""
# Note: who gives a crap about this? The IUser has the real
# information we care about. Save it anyway, I guess, just
# for fun.
self.realname = params[-1]
def irc_NICKSERV_PRIVMSG(self, prefix, params):
"""Send a (private) message.
Parameters: <msgtarget> <text to be sent>
"""
target = params[0]
password = params[-1]
if self.nickname is None:
# XXX Send an error response here
self.transport.loseConnection()
elif target.lower() != "nickserv":
self.privmsg(
NICKSERV,
self.nickname,
"Denied. Please send me (NickServ) your password.")
else:
nickname = self.nickname
self.nickname = None
self.logInAs(nickname, password)
def logInAs(self, nickname, password):
d = self.factory.portal.login(
credentials.UsernamePassword(nickname, password),
self,
iwords.IUser)
d.addCallbacks(self._cbLogin, self._ebLogin, errbackArgs=(nickname,))
_welcomeMessages = [
(irc.RPL_WELCOME,
":connected to Twisted IRC"),
(irc.RPL_YOURHOST,
":Your host is %(serviceName)s, running version %(serviceVersion)s"),
(irc.RPL_CREATED,
":This server was created on %(creationDate)s"),
# "Bummer. This server returned a worthless 004 numeric.
# I'll have to guess at all the values"
# -- epic
(irc.RPL_MYINFO,
# w and n are the currently supported channel and user modes
# -- specify this better
"%(serviceName)s %(serviceVersion)s w n"),
]
def _cbLogin(self, (iface, avatar, logout)):
assert iface is iwords.IUser, "Realm is buggy, got %r" % (iface,)
# Let them send messages to the world
del self.irc_PRIVMSG
self.avatar = avatar
self.logout = logout
self.realm = avatar.realm
self.hostname = self.realm.name
info = {
"serviceName": self.hostname,
"serviceVersion": copyright.version,
"creationDate": ctime(), # XXX
}
for code, text in self._welcomeMessages:
self.sendMessage(code, text % info)
def _ebLogin(self, err, nickname):
if err.check(ewords.AlreadyLoggedIn):
self.privmsg(
NICKSERV,
nickname,
"Already logged in. No pod people allowed!")
elif err.check(ecred.UnauthorizedLogin):
self.privmsg(
NICKSERV,
nickname,
"Login failed. Goodbye.")
else:
log.msg("Unhandled error during login:")
log.err(err)
self.privmsg(
NICKSERV,
nickname,
"Server error during login. Sorry.")
self.transport.loseConnection()
# Great, now that's out of the way, here's some of the interesting
# bits
def irc_PING(self, prefix, params):
"""Ping message
Parameters: <server1> [ <server2> ]
"""
if self.realm is not None:
self.sendMessage('PONG', self.hostname)
def irc_QUIT(self, prefix, params):
"""Quit
Parameters: [ <Quit Message> ]
"""
self.transport.loseConnection()
def _channelMode(self, group, modes=None, *args):
if modes:
self.sendMessage(
irc.ERR_UNKNOWNMODE,
":Unknown MODE flag.")
else:
self.channelMode(self.name, '#' + group.name, '+')
def _userMode(self, user, modes=None):
if modes:
self.sendMessage(
irc.ERR_UNKNOWNMODE,
":Unknown MODE flag.")
elif user is self.avatar:
self.sendMessage(
irc.RPL_UMODEIS,
"+")
else:
self.sendMessage(
irc.ERR_USERSDONTMATCH,
":You can't look at someone else's modes.")
def irc_MODE(self, prefix, params):
"""User mode message
Parameters: <nickname>
*( ( "+" / "-" ) *( "i" / "w" / "o" / "O" / "r" ) )
"""
try:
channelOrUser = params[0].decode(self.encoding)
except UnicodeDecodeError:
self.sendMessage(
irc.ERR_NOSUCHNICK, params[0],
":No such nickname (could not decode your unicode!)")
return
if channelOrUser.startswith('#'):
def ebGroup(err):
err.trap(ewords.NoSuchGroup)
self.sendMessage(
irc.ERR_NOSUCHCHANNEL, params[0],
":That channel doesn't exist.")
d = self.realm.lookupGroup(channelOrUser[1:])
d.addCallbacks(
self._channelMode,
ebGroup,
callbackArgs=tuple(params[1:]))
else:
def ebUser(err):
self.sendMessage(
irc.ERR_NOSUCHNICK,
":No such nickname.")
d = self.realm.lookupUser(channelOrUser)
d.addCallbacks(
self._userMode,
ebUser,
callbackArgs=tuple(params[1:]))
def irc_USERHOST(self, prefix, params):
"""Userhost message
Parameters: <nickname> *( SPACE <nickname> )
[Optional]
"""
pass
def irc_PRIVMSG(self, prefix, params):
"""Send a (private) message.
Parameters: <msgtarget> <text to be sent>
"""
try:
targetName = params[0].decode(self.encoding)
except UnicodeDecodeError:
self.sendMessage(
irc.ERR_NOSUCHNICK, targetName,
":No such nick/channel (could not decode your unicode!)")
return
messageText = params[-1]
if targetName.startswith('#'):
target = self.realm.lookupGroup(targetName[1:])
else:
target = self.realm.lookupUser(targetName).addCallback(lambda user: user.mind)
def cbTarget(targ):
if targ is not None:
return self.avatar.send(targ, {"text": messageText})
def ebTarget(err):
self.sendMessage(
irc.ERR_NOSUCHNICK, targetName,
":No such nick/channel.")
target.addCallbacks(cbTarget, ebTarget)
def irc_JOIN(self, prefix, params):
"""Join message
Parameters: ( <channel> *( "," <channel> ) [ <key> *( "," <key> ) ] )
"""
try:
groupName = params[0].decode(self.encoding)
except UnicodeDecodeError:
self.sendMessage(
irc.IRC_NOSUCHCHANNEL, params[0],
":No such channel (could not decode your unicode!)")
return
if groupName.startswith('#'):
groupName = groupName[1:]
def cbGroup(group):
def cbJoin(ign):
self.userJoined(group, self)
self.names(
self.name,
'#' + group.name,
[user.name for user in group.iterusers()])
self._sendTopic(group)
return self.avatar.join(group).addCallback(cbJoin)
def ebGroup(err):
self.sendMessage(
irc.ERR_NOSUCHCHANNEL, '#' + groupName,
":No such channel.")
self.realm.getGroup(groupName).addCallbacks(cbGroup, ebGroup)
def irc_PART(self, prefix, params):
"""Part message
Parameters: <channel> *( "," <channel> ) [ <Part Message> ]
"""
try:
groupName = params[0].decode(self.encoding)
except UnicodeDecodeError:
self.sendMessage(
irc.ERR_NOTONCHANNEL, params[0],
":Could not decode your unicode!")
return
if groupName.startswith('#'):
groupName = groupName[1:]
if len(params) > 1:
reason = params[1].decode('utf-8')
else:
reason = None
def cbGroup(group):
def cbLeave(result):
self.userLeft(group, self, reason)
return self.avatar.leave(group, reason).addCallback(cbLeave)
def ebGroup(err):
err.trap(ewords.NoSuchGroup)
self.sendMessage(
irc.ERR_NOTONCHANNEL,
'#' + groupName,
":" + err.getErrorMessage())
self.realm.lookupGroup(groupName).addCallbacks(cbGroup, ebGroup)
def irc_NAMES(self, prefix, params):
"""Names message
Parameters: [ <channel> *( "," <channel> ) [ <target> ] ]
"""
#<< NAMES #python
#>> :benford.openprojects.net 353 glyph = #python :Orban ... @glyph ... Zymurgy skreech
#>> :benford.openprojects.net 366 glyph #python :End of /NAMES list.
try:
channel = params[-1].decode(self.encoding)
except UnicodeDecodeError:
self.sendMessage(
irc.ERR_NOSUCHCHANNEL, params[-1],
":No such channel (could not decode your unicode!)")
return
if channel.startswith('#'):
channel = channel[1:]
def cbGroup(group):
self.names(
self.name,
'#' + group.name,
[user.name for user in group.iterusers()])
def ebGroup(err):
err.trap(ewords.NoSuchGroup)
# No group? Fine, no names!
self.names(
self.name,
'#' + channel,
[])
self.realm.lookupGroup(channel).addCallbacks(cbGroup, ebGroup)
def irc_TOPIC(self, prefix, params):
"""Topic message
Parameters: <channel> [ <topic> ]
"""
try:
channel = params[0].decode(self.encoding)
except UnicodeDecodeError:
self.sendMessage(
irc.ERR_NOSUCHCHANNEL,
":That channel doesn't exist (could not decode your unicode!)")
return
if channel.startswith('#'):
channel = channel[1:]
if len(params) > 1:
self._setTopic(channel, params[1])
else:
self._getTopic(channel)
def _sendTopic(self, group):
topic = group.meta.get("topic")
author = group.meta.get("topic_author") or "<noone>"
date = group.meta.get("topic_date", 0)
self.topic(self.name, '#' + group.name, topic)
self.topicAuthor(self.name, '#' + group.name, author, date)
def _getTopic(self, channel):
#<< TOPIC #python
#>> :benford.openprojects.net 332 glyph #python :<churchr> I really did. I sprained all my toes.
#>> :benford.openprojects.net 333 glyph #python itamar|nyc 994713482
def ebGroup(err):
err.trap(ewords.NoSuchGroup)
self.sendMessage(
irc.ERR_NOSUCHCHANNEL, '=', channel,
":That channel doesn't exist.")
self.realm.lookupGroup(channel).addCallbacks(self._sendTopic, ebGroup)
def _setTopic(self, channel, topic):
#<< TOPIC #divunal :foo
#>> :[email protected] TOPIC #divunal :foo
def cbGroup(group):
newMeta = group.meta.copy()
newMeta['topic'] = topic
newMeta['topic_author'] = self.name
newMeta['topic_date'] = int(time())
def ebSet(err):
self.sendMessage(
irc.ERR_CHANOPRIVSNEEDED,
"#" + group.name,
":You need to be a channel operator to do that.")
return group.setMetadata(newMeta).addErrback(ebSet)
def ebGroup(err):
err.trap(ewords.NoSuchGroup)
self.sendMessage(
irc.ERR_NOSUCHCHANNEL, '=', channel,
":That channel doesn't exist.")
self.realm.lookupGroup(channel).addCallbacks(cbGroup, ebGroup)
def list(self, channels):
"""Send a group of LIST response lines
@type channel: C{list} of C{(str, int, str)}
@param channel: Information about the channels being sent:
their name, the number of participants, and their topic.
"""
for (name, size, topic) in channels:
self.sendMessage(irc.RPL_LIST, name, str(size), ":" + topic)
self.sendMessage(irc.RPL_LISTEND, ":End of /LIST")
def irc_LIST(self, prefix, params):
"""List query
Return information about the indicated channels, or about all
channels if none are specified.
Parameters: [ <channel> *( "," <channel> ) [ <target> ] ]
"""
#<< list #python
#>> :orwell.freenode.net 321 exarkun Channel :Users Name
#>> :orwell.freenode.net 322 exarkun #python 358 :The Python programming language
#>> :orwell.freenode.net 323 exarkun :End of /LIST
if params:
# Return information about indicated channels
try:
channels = params[0].decode(self.encoding).split(',')
except UnicodeDecodeError:
self.sendMessage(
irc.ERR_NOSUCHCHANNEL, params[0],
":No such channel (could not decode your unicode!)")
return
groups = []
for ch in channels:
if ch.startswith('#'):
ch = ch[1:]
groups.append(self.realm.lookupGroup(ch))
groups = defer.DeferredList(groups, consumeErrors=True)
groups.addCallback(lambda gs: [r for (s, r) in gs if s])
else:
# Return information about all channels
groups = self.realm.itergroups()
def cbGroups(groups):
def gotSize(size, group):
return group.name, size, group.meta.get('topic')
d = defer.DeferredList([
group.size().addCallback(gotSize, group) for group in groups])
d.addCallback(lambda results: self.list([r for (s, r) in results if s]))
return d
groups.addCallback(cbGroups)
def _channelWho(self, group):
self.who(self.name, '#' + group.name,
[(m.name, self.hostname, self.realm.name, m.name, "H", 0, m.name) for m in group.iterusers()])
def _userWho(self, user):
self.sendMessage(irc.RPL_ENDOFWHO,
":User /WHO not implemented")
def irc_WHO(self, prefix, params):
"""Who query
Parameters: [ <mask> [ "o" ] ]
"""
#<< who #python
#>> :x.opn 352 glyph #python aquarius pc-62-31-193-114-du.blueyonder.co.uk y.opn Aquarius H :3 Aquarius
# ...
#>> :x.opn 352 glyph #python foobar europa.tranquility.net z.opn skreech H :0 skreech
#>> :x.opn 315 glyph #python :End of /WHO list.
### also
#<< who glyph
#>> :x.opn 352 glyph #python glyph adsl-64-123-27-108.dsl.austtx.swbell.net x.opn glyph H :0 glyph
#>> :x.opn 315 glyph glyph :End of /WHO list.
if not params:
self.sendMessage(irc.RPL_ENDOFWHO, ":/WHO not supported.")
return
try:
channelOrUser = params[0].decode(self.encoding)
except UnicodeDecodeError:
self.sendMessage(
irc.RPL_ENDOFWHO, params[0],
":End of /WHO list (could not decode your unicode!)")
return
if channelOrUser.startswith('#'):
def ebGroup(err):
err.trap(ewords.NoSuchGroup)
self.sendMessage(
irc.RPL_ENDOFWHO, channelOrUser,
":End of /WHO list.")
d = self.realm.lookupGroup(channelOrUser[1:])
d.addCallbacks(self._channelWho, ebGroup)
else:
def ebUser(err):
err.trap(ewords.NoSuchUser)
self.sendMessage(
irc.RPL_ENDOFWHO, channelOrUser,
":End of /WHO list.")
d = self.realm.lookupUser(channelOrUser)
d.addCallbacks(self._userWho, ebUser)
def irc_WHOIS(self, prefix, params):
"""Whois query
Parameters: [ <target> ] <mask> *( "," <mask> )
"""
def cbUser(user):
self.whois(
self.name,
user.name, user.name, self.realm.name,
user.name, self.realm.name, 'Hi mom!', False,
int(time() - user.lastMessage), user.signOn,
['#' + group.name for group in user.itergroups()])
def ebUser(err):
err.trap(ewords.NoSuchUser)
self.sendMessage(
irc.ERR_NOSUCHNICK,
params[0],
":No such nick/channel")
try:
user = params[0].decode(self.encoding)
except UnicodeDecodeError:
self.sendMessage(
irc.ERR_NOSUCHNICK,
params[0],
":No such nick/channel")
return
self.realm.lookupUser(user).addCallbacks(cbUser, ebUser)
# Unsupported commands, here for legacy compatibility
def irc_OPER(self, prefix, params):
"""Oper message
Parameters: <name> <password>
"""
self.sendMessage(irc.ERR_NOOPERHOST, ":O-lines not applicable")
class IRCFactory(protocol.ServerFactory):
protocol = IRCUser
def __init__(self, realm, portal):
self.realm = realm
self.portal = portal
class PBMind(pb.Referenceable):
def __init__(self):
pass
def jellyFor(self, jellier):
return reflect.qual(PBMind), jellier.invoker.registerReference(self)
def remote_userJoined(self, user, group):
pass
def remote_userLeft(self, user, group, reason):
pass
def remote_receive(self, sender, recipient, message):
pass
def remote_groupMetaUpdate(self, group, meta):
pass
class PBMindReference(pb.RemoteReference):
implements(iwords.IChatClient)
def receive(self, sender, recipient, message):
if iwords.IGroup.providedBy(recipient):
rec = PBGroup(self.realm, self.avatar, recipient)
else:
rec = PBUser(self.realm, self.avatar, recipient)
return self.callRemote(
'receive',
PBUser(self.realm, self.avatar, sender),
rec,
message)
def groupMetaUpdate(self, group, meta):
return self.callRemote(
'groupMetaUpdate',
PBGroup(self.realm, self.avatar, group),
meta)
def userJoined(self, group, user):
return self.callRemote(
'userJoined',
PBGroup(self.realm, self.avatar, group),
PBUser(self.realm, self.avatar, user))
def userLeft(self, group, user, reason=None):
assert reason is None or isinstance(reason, unicode)
return self.callRemote(
'userLeft',
PBGroup(self.realm, self.avatar, group),
PBUser(self.realm, self.avatar, user),
reason)
pb.setUnjellyableForClass(PBMind, PBMindReference)
class PBGroup(pb.Referenceable):
def __init__(self, realm, avatar, group):
self.realm = realm
self.avatar = avatar
self.group = group
def processUniqueID(self):
return hash((self.realm.name, self.avatar.name, self.group.name))
def jellyFor(self, jellier):
return reflect.qual(self.__class__), self.group.name.encode('utf-8'), jellier.invoker.registerReference(self)
def remote_leave(self, reason=None):
return self.avatar.leave(self.group, reason)
def remote_send(self, message):
return self.avatar.send(self.group, message)
class PBGroupReference(pb.RemoteReference):
implements(iwords.IGroup)
def unjellyFor(self, unjellier, unjellyList):
clsName, name, ref = unjellyList
self.name = name.decode('utf-8')
return pb.RemoteReference.unjellyFor(self, unjellier, [clsName, ref])
def leave(self, reason=None):
return self.callRemote("leave", reason)
def send(self, message):
return self.callRemote("send", message)
pb.setUnjellyableForClass(PBGroup, PBGroupReference)
class PBUser(pb.Referenceable):
def __init__(self, realm, avatar, user):
self.realm = realm
self.avatar = avatar
self.user = user
def processUniqueID(self):
return hash((self.realm.name, self.avatar.name, self.user.name))
class ChatAvatar(pb.Referenceable):
implements(iwords.IChatClient)
def __init__(self, avatar):
self.avatar = avatar
def jellyFor(self, jellier):
return reflect.qual(self.__class__), jellier.invoker.registerReference(self)
def remote_join(self, groupName):
assert isinstance(groupName, unicode)
def cbGroup(group):
def cbJoin(ignored):
return PBGroup(self.avatar.realm, self.avatar, group)
d = self.avatar.join(group)
d.addCallback(cbJoin)
return d
d = self.avatar.realm.getGroup(groupName)
d.addCallback(cbGroup)
return d
registerAdapter(ChatAvatar, iwords.IUser, pb.IPerspective)
class AvatarReference(pb.RemoteReference):
def join(self, groupName):
return self.callRemote('join', groupName)
def quit(self):
d = defer.Deferred()
self.broker.notifyOnDisconnect(lambda: d.callback(None))
self.broker.transport.loseConnection()
return d
pb.setUnjellyableForClass(ChatAvatar, AvatarReference)
class WordsRealm(object):
implements(portal.IRealm, iwords.IChatService)
_encoding = 'utf-8'
def __init__(self, name):
self.name = name
def userFactory(self, name):
return User(name)
def groupFactory(self, name):
return Group(name)
def logoutFactory(self, avatar, facet):
def logout():
# XXX Deferred support here
getattr(facet, 'logout', lambda: None)()
avatar.realm = avatar.mind = None
return logout
def requestAvatar(self, avatarId, mind, *interfaces):
if isinstance(avatarId, str):
avatarId = avatarId.decode(self._encoding)
def gotAvatar(avatar):
if avatar.realm is not None:
raise ewords.AlreadyLoggedIn()
for iface in interfaces:
facet = iface(avatar, None)
if facet is not None:
avatar.loggedIn(self, mind)
mind.name = avatarId
mind.realm = self
mind.avatar = avatar
return iface, facet, self.logoutFactory(avatar, facet)
raise NotImplementedError(self, interfaces)
return self.getUser(avatarId).addCallback(gotAvatar)
# IChatService, mostly.
createGroupOnRequest = False
createUserOnRequest = True
def lookupUser(self, name):
raise NotImplementedError
def lookupGroup(self, group):
raise NotImplementedError
def addUser(self, user):
"""Add the given user to this service.
This is an internal method intented to be overridden by
L{WordsRealm} subclasses, not called by external code.
@type user: L{IUser}
@rtype: L{twisted.internet.defer.Deferred}
@return: A Deferred which fires with C{None} when the user is
added, or which fails with
L{twisted.words.ewords.DuplicateUser} if a user with the
same name exists already.
"""
raise NotImplementedError
def addGroup(self, group):
"""Add the given group to this service.
@type group: L{IGroup}
@rtype: L{twisted.internet.defer.Deferred}
@return: A Deferred which fires with C{None} when the group is
added, or which fails with
L{twisted.words.ewords.DuplicateGroup} if a group with the
same name exists already.
"""
raise NotImplementedError
def getGroup(self, name):
assert isinstance(name, unicode)
if self.createGroupOnRequest:
def ebGroup(err):
err.trap(ewords.DuplicateGroup)
return self.lookupGroup(name)
return self.createGroup(name).addErrback(ebGroup)
return self.lookupGroup(name)
def getUser(self, name):
assert isinstance(name, unicode)
if self.createUserOnRequest:
def ebUser(err):
err.trap(ewords.DuplicateUser)
return self.lookupUser(name)
return self.createUser(name).addErrback(ebUser)
return self.lookupUser(name)
def createUser(self, name):
assert isinstance(name, unicode)
def cbLookup(user):
return failure.Failure(ewords.DuplicateUser(name))
def ebLookup(err):
err.trap(ewords.NoSuchUser)
return self.userFactory(name)
name = name.lower()
d = self.lookupUser(name)
d.addCallbacks(cbLookup, ebLookup)
d.addCallback(self.addUser)
return d
def createGroup(self, name):
assert isinstance(name, unicode)
def cbLookup(group):
return failure.Failure(ewords.DuplicateGroup(name))
def ebLookup(err):
err.trap(ewords.NoSuchGroup)
return self.groupFactory(name)
name = name.lower()
d = self.lookupGroup(name)
d.addCallbacks(cbLookup, ebLookup)
d.addCallback(self.addGroup)
return d
class InMemoryWordsRealm(WordsRealm):
def __init__(self, *a, **kw):
super(InMemoryWordsRealm, self).__init__(*a, **kw)
self.users = {}
self.groups = {}
def itergroups(self):
return defer.succeed(self.groups.itervalues())
def addUser(self, user):
if user.name in self.users:
return defer.fail(failure.Failure(ewords.DuplicateUser()))
self.users[user.name] = user
return defer.succeed(user)
def addGroup(self, group):
if group.name in self.groups:
return defer.fail(failure.Failure(ewords.DuplicateGroup()))
self.groups[group.name] = group
return defer.succeed(group)
def lookupUser(self, name):
assert isinstance(name, unicode)
name = name.lower()
try:
user = self.users[name]
except KeyError:
return defer.fail(failure.Failure(ewords.NoSuchUser(name)))
else:
return defer.succeed(user)
def lookupGroup(self, name):
assert isinstance(name, unicode)
name = name.lower()
try:
group = self.groups[name]
except KeyError:
return defer.fail(failure.Failure(ewords.NoSuchGroup(name)))
else:
return defer.succeed(group)
__all__ = [
'Group', 'User',
'WordsRealm', 'InMemoryWordsRealm',
] | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/service.py | service.py |
from zope.interface import Interface, Attribute, implements
class IProtocolPlugin(Interface):
"""Interface for plugins providing an interface to a Words service
"""
name = Attribute("A single word describing what kind of interface this is (eg, irc or web)")
def getFactory(realm, portal):
"""Retrieve a C{twisted.internet.interfaces.IServerFactory} provider
@param realm: An object providing C{twisted.cred.portal.IRealm} and
C{IChatService}, with which service information should be looked up.
@param portal: An object providing C{twisted.cred.portal.IPortal},
through which logins should be performed.
"""
class IGroup(Interface):
name = Attribute("A short string, unique among groups.")
def add(user):
"""Include the given user in this group.
@type user: L{IUser}
"""
def remove(user, reason=None):
"""Remove the given user from this group.
@type user: L{IUser}
@type reason: C{unicode}
"""
def size():
"""Return the number of participants in this group.
@rtype: L{twisted.internet.defer.Deferred}
@return: A Deferred which fires with an C{int} representing the the
number of participants in this group.
"""
def receive(sender, recipient, message):
"""
Broadcast the given message from the given sender to other
users in group.
The message is not re-transmitted to the sender.
@param sender: L{IUser}
@type recipient: L{IGroup}
@param recipient: This is probably a wart. Maybe it will be removed
in the future. For now, it should be the group object the message
is being delivered to.
@param message: C{dict}
@rtype: L{twisted.internet.defer.Deferred}
@return: A Deferred which fires with None when delivery has been
attempted for all users.
"""
def setMetadata(meta):
"""Change the metadata associated with this group.
@type meta: C{dict}
"""
def iterusers():
"""Return an iterator of all users in this group.
"""
class IChatClient(Interface):
"""Interface through which IChatService interacts with clients.
"""
name = Attribute("A short string, unique among users. This will be set by the L{IChatService} at login time.")
def receive(sender, recipient, message):
"""
Callback notifying this user of the given message sent by the
given user.
This will be invoked whenever another user sends a message to a
group this user is participating in, or whenever another user sends
a message directly to this user. In the former case, C{recipient}
will be the group to which the message was sent; in the latter, it
will be the same object as the user who is receiving the message.
@type sender: L{IUser}
@type recipient: L{IUser} or L{IGroup}
@type message: C{dict}
@rtype: L{twisted.internet.defer.Deferred}
@return: A Deferred which fires when the message has been delivered,
or which fails in some way. If the Deferred fails and the message
was directed at a group, this user will be removed from that group.
"""
def groupMetaUpdate(group, meta):
"""
Callback notifying this user that the metadata for the given
group has changed.
@type group: L{IGroup}
@type meta: C{dict}
@rtype: L{twisted.internet.defer.Deferred}
"""
def userJoined(group, user):
"""
Callback notifying this user that the given user has joined
the given group.
@type group: L{IGroup}
@type user: L{IUser}
@rtype: L{twisted.internet.defer.Deferred}
"""
def userLeft(group, user, reason=None):
"""
Callback notifying this user that the given user has left the
given group for the given reason.
@type group: L{IGroup}
@type user: L{IUser}
@type reason: C{unicode}
@rtype: L{twisted.internet.defer.Deferred}
"""
class IUser(Interface):
"""Interface through which clients interact with IChatService.
"""
realm = Attribute("A reference to the Realm to which this user belongs. Set if and only if the user is logged in.")
mind = Attribute("A reference to the mind which logged in to this user. Set if and only if the user is logged in.")
name = Attribute("A short string, unique among users.")
lastMessage = Attribute("A POSIX timestamp indicating the time of the last message received from this user.")
signOn = Attribute("A POSIX timestamp indicating this user's most recent sign on time.")
def loggedIn(realm, mind):
"""Invoked by the associated L{IChatService} when login occurs.
@param realm: The L{IChatService} through which login is occurring.
@param mind: The mind object used for cred login.
"""
def send(recipient, message):
"""Send the given message to the given user or group.
@type recipient: Either L{IUser} or L{IGroup}
@type message: C{dict}
"""
def join(group):
"""Attempt to join the given group.
@type group: L{IGroup}
@rtype: L{twisted.internet.defer.Deferred}
"""
def leave(group):
"""Discontinue participation in the given group.
@type group: L{IGroup}
@rtype: L{twisted.internet.defer.Deferred}
"""
def itergroups():
"""
Return an iterator of all groups of which this user is a
member.
"""
class IChatService(Interface):
name = Attribute("A short string identifying this chat service (eg, a hostname)")
createGroupOnRequest = Attribute(
"A boolean indicating whether L{getGroup} should implicitly "
"create groups which are requested but which do not yet exist.")
createUserOnRequest = Attribute(
"A boolean indicating whether L{getUser} should implicitly "
"create users which are requested but which do not yet exist.")
def itergroups():
"""Return all groups available on this service.
@rtype: C{twisted.internet.defer.Deferred}
@return: A Deferred which fires with a list of C{IGroup} providers.
"""
def getGroup(name):
"""Retrieve the group by the given name.
@type name: C{str}
@rtype: L{twisted.internet.defer.Deferred}
@return: A Deferred which fires with the group with the given
name if one exists (or if one is created due to the setting of
L{createGroupOnRequest}, or which fails with
L{twisted.words.ewords.NoSuchGroup} if no such group exists.
"""
def createGroup(name):
"""Create a new group with the given name.
@type name: C{str}
@rtype: L{twisted.internet.defer.Deferred}
@return: A Deferred which fires with the created group, or
with fails with L{twisted.words.ewords.DuplicateGroup} if a
group by that name exists already.
"""
def lookupGroup(name):
"""Retrieve a group by name.
Unlike C{getGroup}, this will never implicitly create a group.
@type name: C{str}
@rtype: L{twisted.internet.defer.Deferred}
@return: A Deferred which fires with the group by the given
name, or which fails with L{twisted.words.ewords.NoSuchGroup}.
"""
def getUser(name):
"""Retrieve the user by the given name.
@type name: C{str}
@rtype: L{twisted.internet.defer.Deferred}
@return: A Deferred which fires with the user with the given
name if one exists (or if one is created due to the setting of
L{createUserOnRequest}, or which fails with
L{twisted.words.ewords.NoSuchUser} if no such user exists.
"""
def createUser(name):
"""Create a new user with the given name.
@type name: C{str}
@rtype: L{twisted.internet.defer.Deferred}
@return: A Deferred which fires with the created user, or
with fails with L{twisted.words.ewords.DuplicateUser} if a
user by that name exists already.
"""
__all__ = [
'IChatInterface', 'IGroup', 'IChatClient', 'IUser', 'IChatService',
] | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/iwords.py | iwords.py |
import sys, socket
from twisted.application import strports
from twisted.application.service import MultiService
from twisted.python import usage
from twisted import plugin
from twisted.words import iwords, service
from twisted.cred import checkers, portal
class Options(usage.Options):
optParameters = [
('passwd', None, None,
'Name of a passwd-style password file. (REQUIRED)'),
('hostname', None, socket.gethostname(),
'Name of this server; purely an informative')]
interfacePlugins = {}
plg = None
for plg in plugin.getPlugins(iwords.IProtocolPlugin):
assert plg.name not in interfacePlugins
interfacePlugins[plg.name] = plg
optParameters.append((
plg.name + '-port',
None, None,
'strports description of the port to bind for the ' + plg.name + ' server'))
del plg
def __init__(self, *a, **kw):
usage.Options.__init__(self, *a, **kw)
self['groups'] = []
self['checkers'] = None
def opt_group(self, name):
"""Specify a group which should exist
"""
self['groups'].append(name.decode(sys.stdin.encoding))
def makeService(config):
if config['passwd']:
credCheckers = [checkers.FilePasswordDB(config['passwd'], cache=True)]
elif config['checkers']:
credCheckers = config['checkers']
else:
credCheckers = []
wordsRealm = service.InMemoryWordsRealm(config['hostname'])
wordsPortal = portal.Portal(wordsRealm, credCheckers)
msvc = MultiService()
# XXX Attribute lookup on config is kind of bad - hrm.
for plgName in config.interfacePlugins:
port = config.get(plgName + '-port')
if port is not None:
factory = config.interfacePlugins[plgName].getFactory(wordsRealm, wordsPortal)
svc = strports.service(port, factory)
svc.setServiceParent(msvc)
# This is bogus. createGroup is async. makeService must be
# allowed to return a Deferred or some crap.
for g in config['groups']:
wordsRealm.createGroup(g)
return msvc | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/tap.py | tap.py |
import os, re
from twisted.python import reflect
from twisted.python import util
from twisted.manhole.ui.pywidgets import isCursorOnFirstLine, isCursorOnLastLine
import string
import gtk
from libglade import GladeXML
GLADE_FILE = util.sibpath(__file__, "instancemessenger.glade")
SETTINGS_FILE = os.path.expanduser("~/.InstanceMessenger")
OFFLINE = 0
ONLINE = 1
AWAY = 2
True = gtk.TRUE
False = gtk.FALSE
class InputOutputWindow:
def __init__(self, rootName, inputName, outputName):
self.xml = openGlade(GLADE_FILE, root=rootName)
wid = self.xml.get_widget
self.entry = wid(inputName)
#self.entry.set_word_wrap(gtk.TRUE)
self.output = wid(outputName)
#self.output.set_word_wrap(gtk.TRUE)
self.widget = wid(rootName)
self.history = []
self.histpos = 0
self.linemode = True
self.currentlyVisible = 0
self.win = None
autoConnectMethods(self)
def show(self):
if not self.currentlyVisible:
self.win = w = gtk.GtkWindow(gtk.WINDOW_TOPLEVEL)
self.connectid = w.connect("destroy", self.hidden)
w.add(self.widget)
w.set_title(self.getTitle())
w.show_all()
self.entry.grab_focus()
self.currentlyVisible = 1
def hidden(self, w):
self.win = None
w.remove(self.widget)
self.currentlyVisible = 0
def hide(self):
if self.currentlyVisible:
self.win.remove(self.widget)
self.currentlyVisible = 0
self.win.disconnect(self.connectid)
self.win.destroy()
def handle_key_press_event(self, entry, event):
stopSignal = False
# ASSUMPTION: Assume Meta == mod4
isMeta = event.state & gtk.GDK.MOD4_MASK
##
# Return handling
##
if event.keyval == gtk.GDK.Return:
isShift = event.state & gtk.GDK.SHIFT_MASK
if isShift:
self.linemode = True
entry.insert_defaults('\n')
else:
stopSignal = True
text = entry.get_chars(0,-1)
if not text:
return
self.entry.delete_text(0, -1)
self.linemode = False
self.sendText(text)
self.history.append(text)
self.histpos = len(self.history)
##
# History handling
##
elif ((event.keyval == gtk.GDK.Up and isCursorOnFirstLine(entry))
or (isMeta and event.string == 'p')):
print "history up"
self.historyUp()
stopSignal = True
elif ((event.keyval == gtk.GDK.Down and isCursorOnLastLine(entry))
or (isMeta and event.string == 'n')):
print "history down"
self.historyDown()
stopSignal = True
##
# Tab Completion
##
elif event.keyval == gtk.GDK.Tab:
oldpos = entry.get_point()
word, pos = self.getCurrentWord(entry)
result = self.tabComplete(word)
#If there are multiple potential matches, then we spit
#them out and don't insert a tab, so the user can type
#a couple more characters and try completing again.
if len(result) > 1:
for nick in result:
self.output.insert_defaults(nick + " ")
self.output.insert_defaults('\n')
stopSignal = True
elif result: #only happens when len(result) == 1
entry.freeze()
entry.delete_text(*pos)
entry.set_position(pos[0])
entry.insert_defaults(result[0])
entry.set_position(oldpos+len(result[0])-len(word))
entry.thaw()
stopSignal = True
if stopSignal:
entry.emit_stop_by_name("key_press_event")
return True
def tabComplete(self, word):
"""Override me to implement tab completion for your window,
I should return a list of potential matches."""
return []
def getCurrentWord(self, entry):
i = entry.get_point()
text = entry.get_chars(0,-1)
word = re.split(r'\s', text)[-1]
start = string.rfind(text, word)
end = start+len(word)
return (word, (start, end))
def historyUp(self):
if self.histpos > 0:
self.entry.delete_text(0, -1)
self.histpos = self.histpos - 1
self.entry.insert_defaults(self.history[self.histpos])
self.entry.set_position(0)
def historyDown(self):
if self.histpos < len(self.history) - 1:
self.histpos = self.histpos + 1
self.entry.delete_text(0, -1)
self.entry.insert_defaults(self.history[self.histpos])
elif self.histpos == len(self.history) - 1:
self.histpos = self.histpos + 1
self.entry.delete_text(0, -1)
def createMethodDict(o, d=None):
if d is None:
d = {}
for base in reflect.allYourBase(o.__class__) + [o.__class__]:
for n in dir(base):
m = getattr(o, n)
#print 'd[%s] = %s' % (n, m)
d[n] = m
#print d
return d
def autoConnectMethods(*objs):
o = {}
for obj in objs:
createMethodDict(obj, o)
# print 'connecting', o
objs[0].xml.signal_autoconnect(o)
def openGlade(*args, **kwargs):
# print "opening glade file"
r = GladeXML(*args, **kwargs)
if r._o:
return r
else:
raise IOError("Couldn't open Glade XML: %s; %s" % (args, kwargs)) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/im/gtkcommon.py | gtkcommon.py |
#
from twisted.words.im.baseaccount import AccountManager
from twisted.words.im.pbsupport import PBAccount
from twisted.words.im.tocsupport import TOCAccount
from twisted.words.im.ircsupport import IRCAccount
import twisted.words.im.jychat
from java.awt import GridLayout, FlowLayout, BorderLayout, Container
import sys
from java.awt.event import ActionListener
from javax.swing import JTextField, JPasswordField, JComboBox, JPanel, JLabel,\
JCheckBox, JFrame, JButton, BoxLayout, JTable, JScrollPane, \
ListSelectionModel
from javax.swing.border import TitledBorder
from javax.swing.table import DefaultTableModel
doublebuffered = 0
stype = "twisted.words"
class NewAccountGUI:
def __init__(self, amgui):
self.amgui = amgui
self.am = amgui.acctmanager
self.buildgwinfo()
self.autologin = JCheckBox("Automatically Log In")
self.acctname = JTextField()
self.gwoptions = JPanel(doublebuffered)
self.gwoptions.border = TitledBorder("Gateway Options")
self.buildgwoptions("Twisted")
self.mainframe = JFrame("New Account Window")
self.buildpane()
def buildgwinfo(self):
self.gateways = {"Twisted" : {"ident" : JTextField(),
"passwd" : JPasswordField(),
"host" : JTextField("twistedmatrix.com"),
"port" : JTextField("8787"),
"service" : JTextField("twisted.words"),
"persp" : JTextField()},
"AIM" : {"ident" : JTextField(),
"passwd" : JPasswordField(),
"host" : JTextField("toc.oscar.aol.com"),
"port" : JTextField("9898")},
"IRC" : {"ident" : JTextField(),
"passwd" : JPasswordField(),
"host" : JTextField(),
"port" : JTextField("6667"),
"channels" : JTextField()}
}
self.displayorder = { "Twisted" : [["Identity Name", "ident"],
["Password", "passwd"],
["Host", "host"],
["Port", "port"],
["Service Name", "service"],
["Perspective Name", "persp"]],
"AIM" : [["Screen Name", "ident"],
["Password", "passwd"],
["Host", "host"],
["Port", "port"]],
"IRC" : [["Nickname", "ident"],
["Password", "passwd"],
["Host", "host"],
["Port", "port"],
["Channels", "channels"]]
}
def buildgwoptions(self, gw):
self.gwoptions.removeAll()
self.gwoptions.layout = GridLayout(len(self.gateways[gw]), 2)
for mapping in self.displayorder[gw]:
self.gwoptions.add(JLabel(mapping[0]))
self.gwoptions.add(self.gateways[gw][mapping[1]])
def buildpane(self):
gw = JPanel(GridLayout(1, 2), doublebuffered)
gw.add(JLabel("Gateway"))
self.gwlist = JComboBox(self.gateways.keys())#, actionPerformed=self.changegw)
self.gwlist.setSelectedItem("Twisted")
gw.add(self.gwlist)
stdoptions = JPanel(GridLayout(2, 2), doublebuffered)
stdoptions.border = TitledBorder("Standard Options")
stdoptions.add(JLabel())
stdoptions.add(self.autologin)
stdoptions.add(JLabel("Account Name"))
stdoptions.add(self.acctname)
buttons = JPanel(FlowLayout(), doublebuffered)
buttons.add(JButton("OK", actionPerformed=self.addaccount))
buttons.add(JButton("Cancel", actionPerformed=self.cancel))
mainpane = self.mainframe.getContentPane()
mainpane.layout = BoxLayout(mainpane, BoxLayout.Y_AXIS)
mainpane.add(gw)
mainpane.add(self.gwoptions)
mainpane.add(stdoptions)
mainpane.add(buttons)
def show(self):
self.mainframe.setLocation(100, 100)
self.mainframe.pack()
self.mainframe.show()
#actionlisteners
def changegw(self, ae):
self.buildgwoptions(self.gwlist.getSelectedItem())
self.mainframe.pack()
self.mainframe.show()
def addaccount(self, ae):
gwselection = self.gwlist.getSelectedItem()
gw = self.gateways[gwselection]
name = gw["ident"].text
passwd = gw["passwd"].text
host = gw["host"].text
port = int(gw["port"].text)
autologin = self.autologin.isSelected()
acctname = self.acctname.text
if gwselection == "Twisted":
sname = gw["service"].text
perspective = gw["persp"].text
self.am.addAccount(PBAccount(acctname, autologin, name, passwd,
host, port,
[[stype, sname, perspective]]))
elif gwselection == "AIM":
self.am.addAccount(TOCAccount(acctname, autologin, name, passwd,
host, port))
elif gwselection == "IRC":
channels = gw["channels"].text
self.am.addAccount(IRCAccount(acctname, autologin, name, passwd,
host, port, channels))
self.amgui.update()
print "Added new account"
self.mainframe.dispose()
def cancel(self, ae):
print "Cancelling new account creation"
self.mainframe.dispose()
class UneditableTableModel(DefaultTableModel):
def isCellEditable(self, x, y):
return 0
class AccountManagementGUI:
def __init__(self):
self.acctmanager = AccountManager()
self.mainframe = JFrame("Account Manager")
self.chatui = None
self.headers = ["Account Name", "Status", "Autologin", "Gateway"]
self.data = UneditableTableModel([], self.headers)
self.table = JTable(self.data)
self.table.columnSelectionAllowed = 0 #cannot select columns
self.table.selectionMode = ListSelectionModel.SINGLE_SELECTION
self.connectbutton = JButton("Connect", actionPerformed=self.connect)
self.dconnbutton = JButton("Disconnect", actionPerformed=self.disconnect)
self.deletebutton = JButton("Delete", actionPerformed=self.deleteAccount)
self.buildpane()
self.mainframe.pack()
self.mainframe.show()
def buildpane(self):
buttons = JPanel(FlowLayout(), doublebuffered)
buttons.add(self.connectbutton)
buttons.add(self.dconnbutton)
buttons.add(JButton("New", actionPerformed=self.addNewAccount))
buttons.add(self.deletebutton)
buttons.add(JButton("Quit", actionPerformed=self.quit))
mainpane = self.mainframe.getContentPane()
mainpane.layout = BoxLayout(mainpane, BoxLayout.Y_AXIS)
mainpane.add(JScrollPane(self.table))
mainpane.add(buttons)
self.update()
def update(self):
self.data.setDataVector(self.acctmanager.getSnapShot(), self.headers)
if self.acctmanager.isEmpty():
self.deletebutton.setEnabled(0)
self.connectbutton.setEnabled(0)
self.dconnbutton.setEnabled(0)
else:
self.deletebutton.setEnabled(1)
if not 1 in self.acctmanager.getConnectionInfo(): #all disconnected
self.dconnbutton.setEnabled(0)
self.connectbutton.setEnabled(1)
elif not 0 in self.acctmanager.getConnectionInfo(): #all connected
self.dconnbutton.setEnabled(1)
self.connectbutton.setEnabled(0)
else:
self.dconnbutton.setEnabled(1)
self.connectbutton.setEnabled(1)
#callable button actions
def connect(self, ae):
print "Trying to connect"
row = self.table.getSelectedRow()
if row < 0:
print "Trying to connect to an account but no account selected"
else:
acctname = self.data.getValueAt(row, 0)
if not self.chatui:
self.chatui = twisted.words.im.jychat.JyChatUI()
self.acctmanager.connect(acctname, self.chatui)
self.update()
def disconnect(self, ae):
print "Trying to disconnect"
row = self.table.getSelectedRow()
if row < 0:
print "Trying to logoff an account but no account was selected."
else:
acctname = self.data.getValueAt(row, 0)
self.acctmanager.disconnect(acctname)
self.update()
def addNewAccount(self, ae):
print "Starting new account creation"
NewAccountGUI(self).show()
def deleteAccount(self, ae):
print "Deleting account"
row = self.table.getSelectedRow()
if row < 0:
print "Trying to delete an account but no account selected"
else:
acctname = self.data.getValueAt(row, 0)
self.acctmanager.delAccount(acctname)
self.update()
def quit(self, ae):
self.acctmanager.quit()
sys.exit()
if __name__ == "__main__":
n = AccountManagementGUI() | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/im/jyaccount.py | jyaccount.py |
#
"""Instance Messenger base classes for protocol support.
You will find these useful if you're adding a new protocol to IM.
"""
# Abstract representation of chat "model" classes
from twisted.words.im.locals import ONLINE, OFFLINE, OfflineError
from twisted.words.im import interfaces
from twisted.internet.protocol import Protocol
from twisted.python.reflect import prefixedMethods
from twisted.persisted import styles
from twisted.internet import error
class AbstractGroup:
def __init__(self, name, account):
self.name = name
self.account = account
def getGroupCommands(self):
"""finds group commands
these commands are methods on me that start with imgroup_; they are
called with no arguments
"""
return prefixedMethods(self, "imgroup_")
def getTargetCommands(self, target):
"""finds group commands
these commands are methods on me that start with imgroup_; they are
called with a user present within this room as an argument
you may want to override this in your group in order to filter for
appropriate commands on the given user
"""
return prefixedMethods(self, "imtarget_")
def join(self):
if not self.account.client:
raise OfflineError
self.account.client.joinGroup(self.name)
def leave(self):
if not self.account.client:
raise OfflineError
self.account.client.leaveGroup(self.name)
def __repr__(self):
return '<%s %r>' % (self.__class__, self.name)
def __str__(self):
return '%s@%s' % (self.name, self.account.accountName)
class AbstractPerson:
def __init__(self, name, baseAccount):
self.name = name
self.account = baseAccount
self.status = OFFLINE
def getPersonCommands(self):
"""finds person commands
these commands are methods on me that start with imperson_; they are
called with no arguments
"""
return prefixedMethods(self, "imperson_")
def getIdleTime(self):
"""
Returns a string.
"""
return '--'
def __repr__(self):
return '<%s %r/%s>' % (self.__class__, self.name, self.status)
def __str__(self):
return '%s@%s' % (self.name, self.account.accountName)
class AbstractClientMixin:
"""Designed to be mixed in to a Protocol implementing class.
Inherit from me first.
@ivar _logonDeferred: Fired when I am done logging in.
"""
def __init__(self, account, chatui, logonDeferred):
for base in self.__class__.__bases__:
if issubclass(base, Protocol):
self.__class__._protoBase = base
break
else:
pass
self.account = account
self.chat = chatui
self._logonDeferred = logonDeferred
def connectionMade(self):
self._protoBase.connectionMade(self)
def connectionLost(self, reason):
self.account._clientLost(self, reason)
self.unregisterAsAccountClient()
return self._protoBase.connectionLost(self, reason)
def unregisterAsAccountClient(self):
"""Tell the chat UI that I have `signed off'.
"""
self.chat.unregisterAccountClient(self)
class AbstractAccount(styles.Versioned):
"""Base class for Accounts.
I am the start of an implementation of L{IAccount<interfaces.IAccount>}, I
implement L{isOnline} and most of L{logOn}, though you'll need to implement
L{_startLogOn} in a subclass.
@cvar _groupFactory: A Callable that will return a L{IGroup} appropriate
for this account type.
@cvar _personFactory: A Callable that will return a L{IPerson} appropriate
for this account type.
@type _isConnecting: boolean
@ivar _isConnecting: Whether I am in the process of establishing a
connection to the server.
@type _isOnline: boolean
@ivar _isOnline: Whether I am currently on-line with the server.
@ivar accountName:
@ivar autoLogin:
@ivar username:
@ivar password:
@ivar host:
@ivar port:
"""
_isOnline = 0
_isConnecting = 0
client = None
_groupFactory = AbstractGroup
_personFactory = AbstractPerson
persistanceVersion = 2
def __init__(self, accountName, autoLogin, username, password, host, port):
self.accountName = accountName
self.autoLogin = autoLogin
self.username = username
self.password = password
self.host = host
self.port = port
self._groups = {}
self._persons = {}
def upgrateToVersion2(self):
# Added in CVS revision 1.16.
for k in ('_groups', '_persons'):
if not hasattr(self, k):
setattr(self, k, {})
def __getstate__(self):
state = styles.Versioned.__getstate__(self)
for k in ('client', '_isOnline', '_isConnecting'):
try:
del state[k]
except KeyError:
pass
return state
def isOnline(self):
return self._isOnline
def logOn(self, chatui):
"""Log on to this account.
Takes care to not start a connection if a connection is
already in progress. You will need to implement
L{_startLogOn} for this to work, and it would be a good idea
to override L{_loginFailed} too.
@returntype: Deferred L{interfaces.IClient}
"""
if (not self._isConnecting) and (not self._isOnline):
self._isConnecting = 1
d = self._startLogOn(chatui)
d.addCallback(self._cb_logOn)
# if chatui is not None:
# (I don't particularly like having to pass chatUI to this function,
# but we haven't factored it out yet.)
d.addCallback(chatui.registerAccountClient)
d.addErrback(self._loginFailed)
return d
else:
raise error.ConnectError("Connection in progress")
def getGroup(self, name):
"""Group factory.
@param name: Name of the group on this account.
@type name: string
"""
group = self._groups.get(name)
if group is None:
group = self._groupFactory(name, self)
self._groups[name] = group
return group
def getPerson(self, name):
"""Person factory.
@param name: Name of the person on this account.
@type name: string
"""
person = self._persons.get(name)
if person is None:
person = self._personFactory(name, self)
self._persons[name] = person
return person
def _startLogOn(self, chatui):
"""Start the sign on process.
Factored out of L{logOn}.
@returntype: Deferred L{interfaces.IClient}
"""
raise NotImplementedError()
def _cb_logOn(self, client):
self._isConnecting = 0
self._isOnline = 1
self.client = client
return client
def _loginFailed(self, reason):
"""Errorback for L{logOn}.
@type reason: Failure
@returns: I{reason}, for further processing in the callback chain.
@returntype: Failure
"""
self._isConnecting = 0
self._isOnline = 0 # just in case
return reason
def _clientLost(self, client, reason):
self.client = None
self._isConnecting = 0
self._isOnline = 0
return reason
def __repr__(self):
return "<%s: %s (%s@%s:%s)>" % (self.__class__,
self.accountName,
self.username,
self.host,
self.port) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/im/basesupport.py | basesupport.py |
from zope.interface import Interface
from twisted.words.im import locals
# (Random musings, may not reflect on current state of code:)
#
# Accounts have Protocol components (clients)
# Persons have Conversation components
# Groups have GroupConversation components
# Persons and Groups are associated with specific Accounts
# At run-time, Clients/Accounts are slaved to a User Interface
# (Note: User may be a bot, so don't assume all UIs are built on gui toolkits)
class IAccount(Interface):
"""I represent a user's account with a chat service.
@cvar gatewayType: Identifies the protocol used by this account.
@type gatewayType: string
@ivar client: The Client currently connecting to this account, if any.
@type client: L{IClient}
"""
def __init__(accountName, autoLogin, username, password, host, port):
"""
@type accountName: string
@param accountName: A name to refer to the account by locally.
@type autoLogin: boolean
@type username: string
@type password: string
@type host: string
@type port: integer
"""
def isOnline():
"""Am I online?
@returntype: boolean
"""
def logOn(chatui):
"""Go on-line.
@type chatui: Implementor of C{IChatUI}
@returntype: Deferred L{Client}
"""
def logOff():
"""Sign off.
"""
def getGroup(groupName):
"""
@returntype: L{Group<IGroup>}
"""
def getPerson(personName):
"""
@returntype: L{Person<IPerson>}
"""
class IClient(Interface):
"""
@ivar account: The Account I am a Client for.
@type account: L{IAccount}
"""
def __init__(account, chatui, logonDeferred):
"""
@type account: L{IAccount}
@type chatui: L{IChatUI}
@param logonDeferred: Will be called back once I am logged on.
@type logonDeferred: L{Deferred<twisted.internet.defer.Deferred>}
"""
def joinGroup(groupName):
"""
@param groupName: The name of the group to join.
@type groupName: string
"""
def leaveGroup(groupName):
"""
@param groupName: The name of the group to leave.
@type groupName: string
"""
def getGroupConversation(name,hide=0):
pass
def getPerson(name):
pass
class IPerson(Interface):
def __init__(name, account):
"""Initialize me.
@param name: My name, as the server knows me.
@type name: string
@param account: The account I am accessed through.
@type account: I{Account}
"""
def isOnline():
"""Am I online right now?
@returntype: boolean
"""
def getStatus():
"""What is my on-line status?
@returns: L{locals.StatusEnum}
"""
def getIdleTime():
"""
@returntype: string (XXX: How about a scalar?)
"""
def sendMessage(text, metadata=None):
"""Send a message to this person.
@type text: string
@type metadata: dict
"""
class IGroup(Interface):
"""A group which you may have a conversation with.
Groups generally have a loosely-defined set of members, who may
leave and join at any time.
@ivar name: My name, as the server knows me.
@type name: string
@ivar account: The account I am accessed through.
@type account: I{Account<IAccount>}
"""
def __init__(name, account):
"""Initialize me.
@param name: My name, as the server knows me.
@type name: string
@param account: The account I am accessed through.
@type account: I{Account<IAccount>}
"""
def setTopic(text):
"""Set this Groups topic on the server.
@type text: string
"""
def sendGroupMessage(text, metadata=None):
"""Send a message to this group.
@type text: string
@type metadata: dict
@param metadata: Valid keys for this dictionary include:
- C{'style'}: associated with one of:
- C{'emote'}: indicates this is an action
"""
def join():
pass
def leave():
"""Depart this group"""
class IConversation(Interface):
"""A conversation with a specific person."""
def __init__(person, chatui):
"""
@type person: L{IPerson}
"""
def show():
"""doesn't seem like it belongs in this interface."""
def hide():
"""nor this neither."""
def sendText(text, metadata):
pass
def showMessage(text, metadata):
pass
def changedNick(person, newnick):
"""
@param person: XXX Shouldn't this always be Conversation.person?
"""
class IGroupConversation(Interface):
def show():
"""doesn't seem like it belongs in this interface."""
def hide():
"""nor this neither."""
def sendText(text, metadata):
pass
def showGroupMessage(sender, text, metadata):
pass
def setGroupMembers(members):
"""Sets the list of members in the group and displays it to the user
"""
def setTopic(topic, author):
"""Displays the topic (from the server) for the group conversation window
@type topic: string
@type author: string (XXX: Not Person?)
"""
def memberJoined(member):
"""Adds the given member to the list of members in the group conversation
and displays this to the user
@type member: string (XXX: Not Person?)
"""
def memberChangedNick(oldnick, newnick):
"""Changes the oldnick in the list of members to newnick and displays this
change to the user
@type oldnick: string (XXX: Not Person?)
@type newnick: string
"""
def memberLeft(member):
"""Deletes the given member from the list of members in the group
conversation and displays the change to the user
@type member: string (XXX: Not Person?)
"""
class IChatUI(Interface):
def registerAccountClient(client):
"""Notifies user that an account has been signed on to.
@type client: L{Client<IClient>}
"""
def unregisterAccountClient(client):
"""Notifies user that an account has been signed off or disconnected
@type client: L{Client<IClient>}
"""
def getContactsList():
"""
@returntype: L{ContactsList}
"""
# WARNING: You'll want to be polymorphed into something with
# intrinsic stoning resistance before continuing.
def getConversation(person, Class, stayHidden=0):
"""For the given person object, returns the conversation window
or creates and returns a new conversation window if one does not exist.
@type person: L{Person<IPerson>}
@type Class: L{Conversation<IConversation>} class
@type stayHidden: boolean
@returntype: L{Conversation<IConversation>}
"""
def getGroupConversation(group,Class,stayHidden=0):
"""For the given group object, returns the group conversation window or
creates and returns a new group conversation window if it doesn't exist.
@type group: L{Group<interfaces.IGroup>}
@type Class: L{Conversation<interfaces.IConversation>} class
@type stayHidden: boolean
@returntype: L{GroupConversation<interfaces.IGroupConversation>}
"""
def getPerson(name, client):
"""Get a Person for a client.
Duplicates L{IAccount.getPerson}.
@type name: string
@type client: L{Client<IClient>}
@returntype: L{Person<IPerson>}
"""
def getGroup(name, client):
"""Get a Group for a client.
Duplicates L{IAccount.getGroup}.
@type name: string
@type client: L{Client<IClient>}
@returntype: L{Group<IGroup>}
"""
def contactChangedNick(oldnick, newnick):
"""For the given person, changes the person's name to newnick, and
tells the contact list and any conversation windows with that person
to change as well.
@type oldnick: string
@type newnick: string
""" | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/im/interfaces.py | interfaces.py |
try:
import cPickle as pickle
except ImportError:
import pickle
import gtk
from twisted.words.im.gtkcommon import GLADE_FILE, SETTINGS_FILE, autoConnectMethods,\
openGlade
from twisted.words.im import gtkchat
### This generic stuff uses the word "account" in a very different way -- chat
### accounts are potential sources of messages, InstanceMessenger accounts are
### individual network connections.
class AccountManager:
def __init__(self):
self.xml = openGlade(GLADE_FILE, root="MainIMWindow")
self.chatui = gtkchat.GtkChatClientUI(self.xml)
self.chatui._accountmanager = self # TODO: clean this up... it's used in gtkchat
print self.xml._o
autoConnectMethods(self, self.chatui.theContactsList)
self.widget = self.xml.get_widget("AccountManWidget")
self.widget.show_all()
try:
f = open(SETTINGS_FILE)
self.accounts = pickle.load(f)
print 'loaded!'
self.refreshAccounts()
except IOError:
self.accounts = []
print 'initialized!'
def on_ConsoleButton_clicked(self, b):
#### For debugging purposes...
from twisted.manhole.ui.pywidgets import LocalInteraction
l = LocalInteraction()
l.localNS['chat'] = self.chatui
l.show_all()
def created(self, acct):
self.accounts.append(acct)
self.refreshAccounts()
def refreshAccounts(self):
w = self.xml.get_widget("accountsList")
w.clear()
for acct in self.accounts:
l = [acct.accountName, acct.isOnline() and 'yes' or 'no',
acct.autoLogin and 'yes' or 'no', acct.gatewayType]
w.append(l)
def lockNewAccount(self, b):
self.xml.get_widget("NewAccountButton").set_sensitive(not b)
def on_NewAccountButton_clicked(self, b):
NewAccount(self)
def on_MainIMWindow_destroy(self, w):
print 'Saving...'
pickle.dump(self.accounts, open(SETTINGS_FILE,'wb'))
print 'Saved.'
gtk.mainquit()
def on_DeleteAccountButton_clicked(self, b):
lw = self.xml.get_widget("accountsList")
if lw.selection:
del self.accounts[lw.selection[0]]
self.refreshAccounts()
def on_LogOnButton_clicked(self, b):
lw = self.xml.get_widget("accountsList")
if lw.selection:
self.accounts[lw.selection[0]].logOn(self.chatui)
class DummyAccountForm:
def __init__(self, manager):
self.widget = gtk.GtkButton("HELLO")
def create(self, sname, autoLogin):
return None
class NewAccount:
def __init__(self, manager):
self.manager = manager
self.manager.lockNewAccount(1)
self.xml = openGlade(GLADE_FILE, root="NewAccountWindow")
autoConnectMethods(self)
self.widget = self.xml.get_widget("NewAccountWindow")
self.frame = self.xml.get_widget("GatewayFrame")
# Making up for a deficiency in glade.
widgetMenu = self.xml.get_widget("GatewayOptionMenu")
m = gtk.GtkMenu()
activ = 0
self.currentGateway = None
for name, klas in registeredTypes:
i = gtk.GtkMenuItem(name)
m.append(i)
k = klas(self.manager)
i.connect("activate", self.gatewaySelected, k)
if not activ:
activ = 1
self.gatewaySelected(None, k)
widgetMenu.set_menu(m)
self.widget.show_all()
def gatewaySelected(self, ig, k):
if self.currentGateway:
self.frame.remove(self.currentGateway.widget)
self.currentGateway = k
self.frame.add(k.widget)
k.widget.show_all()
def createAccount(self, b):
autoLogin = self.xml.get_widget("AutoLogin").get_active()
accountName = self.xml.get_widget("accountName").get_text()
x = self.currentGateway.create(accountName, autoLogin)
if x:
self.manager.created(x)
self.destroyMe()
def destroyMe(self, b=None):
self.widget.destroy()
def on_NewAccountWindow_destroy(self, w):
self.manager.lockNewAccount(0)
from twisted.words.im.pbsupport import PBAccount
from twisted.words.im.tocsupport import TOCAccount
from twisted.words.im.ircsupport import IRCAccount
class PBAccountForm:
def __init__(self, manager):
self.manager = manager
self.xml = openGlade(GLADE_FILE, root="PBAccountWidget")
autoConnectMethods(self)
self.widget = self.xml.get_widget("PBAccountWidget")
self.on_serviceType_changed()
self.selectedRow = None
def addPerspective(self, b):
stype = self.xml.get_widget("serviceType").get_text()
sname = self.xml.get_widget("serviceName").get_text()
pname = self.xml.get_widget("perspectiveName").get_text()
self.xml.get_widget("serviceList").append([stype, sname, pname])
def removePerspective(self, b):
if self.selectedRow is not None:
self.xml.get_widget("serviceList").remove(self.selectedRow)
def on_serviceType_changed(self, w=None):
self.xml.get_widget("serviceName").set_text(self.xml.get_widget("serviceType").get_text())
self.xml.get_widget("perspectiveName").set_text(self.xml.get_widget("identity").get_text())
on_identity_changed = on_serviceType_changed
def on_serviceList_select_row(self, slist, row, column, event):
self.selectedRow = row
def create(self, accName, autoLogin):
host = self.xml.get_widget("hostname").get_text()
port = self.xml.get_widget("portno").get_text()
user = self.xml.get_widget("identity").get_text()
pasw = self.xml.get_widget("password").get_text()
serviceList = self.xml.get_widget("serviceList")
services = []
for r in xrange(0, serviceList.rows):
row = []
for c in xrange(0, serviceList.columns):
row.append(serviceList.get_text(r, c))
services.append(row)
if not services:
services.append([
self.xml.get_widget("serviceType").get_text(),
self.xml.get_widget("serviceName").get_text(),
self.xml.get_widget("perspectiveName").get_text()])
return PBAccount(accName, autoLogin, user, pasw, host, int(port),
services)
class TOCAccountForm:
def __init__(self, maanger):
self.xml = openGlade(GLADE_FILE, root="TOCAccountWidget")
self.widget = self.xml.get_widget("TOCAccountWidget")
def create(self, accountName, autoLogin):
return TOCAccount(
accountName, autoLogin,
self.xml.get_widget("TOCName").get_text(),
self.xml.get_widget("TOCPass").get_text(),
self.xml.get_widget("TOCHost").get_text(),
int(self.xml.get_widget("TOCPort").get_text()) )
class IRCAccountForm:
def __init__(self, maanger):
self.xml = openGlade(GLADE_FILE, root="IRCAccountWidget")
self.widget = self.xml.get_widget("IRCAccountWidget")
def create(self, accountName, autoLogin):
return IRCAccount(
accountName, autoLogin,
self.xml.get_widget("ircNick").get_text(),
self.xml.get_widget("ircPassword").get_text(),
self.xml.get_widget("ircServer").get_text(),
int(self.xml.get_widget("ircPort").get_text()),
self.xml.get_widget("ircChannels").get_text(),
)
registeredTypes = [ ("Twisted", PBAccountForm),
("AOL Instant Messenger", TOCAccountForm),
["IRC", IRCAccountForm],
("Dummy", DummyAccountForm) ] | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/im/gtkaccount.py | gtkaccount.py |
#
"""Base classes for Instance Messenger clients."""
from twisted.words.im.locals import OFFLINE, ONLINE, AWAY
class ContactsList:
"""A GUI object that displays a contacts list"""
def __init__(self, chatui):
"""
@param chatui: ???
@type chatui: L{ChatUI}
"""
self.chatui = chatui
self.contacts = {}
self.onlineContacts = {}
self.clients = []
def setContactStatus(self, person):
"""Inform the user that a person's status has changed.
@type person: L{Person<interfaces.IPerson>}
"""
if not self.contacts.has_key(person.name):
self.contacts[person.name] = person
if not self.onlineContacts.has_key(person.name) and \
(person.status == ONLINE or person.status == AWAY):
self.onlineContacts[person.name] = person
if self.onlineContacts.has_key(person.name) and \
person.status == OFFLINE:
del self.onlineContacts[person.name]
def registerAccountClient(self, client):
"""Notify the user that an account client has been signed on to.
@type client: L{Client<interfaces.IClient>}
"""
if not client in self.clients:
self.clients.append(client)
def unregisterAccountClient(self, client):
"""Notify the user that an account client has been signed off
or disconnected from.
@type client: L{Client<interfaces.IClient>}
"""
if client in self.clients:
self.clients.remove(client)
def contactChangedNick(self, person, newnick):
oldname = person.name
if self.contacts.has_key(oldname):
del self.contacts[oldname]
person.name = newnick
self.contacts[newnick] = person
if self.onlineContacts.has_key(oldname):
del self.onlineContacts[oldname]
self.onlineContacts[newnick] = person
class Conversation:
"""A GUI window of a conversation with a specific person"""
def __init__(self, person, chatui):
"""
@type person: L{Person<interfaces.IPerson>}
@type chatui: L{ChatUI}
"""
self.chatui = chatui
self.person = person
def show(self):
"""Displays the ConversationWindow"""
raise NotImplementedError("Subclasses must implement this method")
def hide(self):
"""Hides the ConversationWindow"""
raise NotImplementedError("Subclasses must implement this method")
def sendText(self, text):
"""Sends text to the person with whom the user is conversing.
@returntype: L{Deferred<twisted.internet.defer.Deferred>}
"""
self.person.sendMessage(text, None)
def showMessage(self, text, metadata=None):
"""Display a message sent from the person with whom she is conversing
@type text: string
@type metadata: dict
"""
raise NotImplementedError("Subclasses must implement this method")
def contactChangedNick(self, person, newnick):
"""Change a person's name.
@type person: L{Person<interfaces.IPerson>}
@type newnick: string
"""
self.person.name = newnick
class GroupConversation:
"""A conversation with a group of people."""
def __init__(self, group, chatui):
"""
@type group: L{Group<interfaces.IGroup>}
@param chatui: ???
@type chatui: L{ChatUI}
"""
self.chatui = chatui
self.group = group
self.members = []
def show(self):
"""Displays the GroupConversationWindow."""
raise NotImplementedError("Subclasses must implement this method")
def hide(self):
"""Hides the GroupConversationWindow."""
raise NotImplementedError("Subclasses must implement this method")
def sendText(self, text):
"""Sends text to the group.
@type text: string
@returntype: L{Deferred<twisted.internet.defer.Deferred>}
"""
self.group.sendGroupMessage(text, None)
def showGroupMessage(self, sender, text, metadata=None):
"""Displays to the user a message sent to this group from the given sender
@type sender: string (XXX: Not Person?)
@type text: string
@type metadata: dict
"""
raise NotImplementedError("Subclasses must implement this method")
def setGroupMembers(self, members):
"""Sets the list of members in the group and displays it to the user
"""
self.members = members
def setTopic(self, topic, author):
"""Displays the topic (from the server) for the group conversation window
@type topic: string
@type author: string (XXX: Not Person?)
"""
raise NotImplementedError("Subclasses must implement this method")
def memberJoined(self, member):
"""Adds the given member to the list of members in the group conversation
and displays this to the user
@type member: string (XXX: Not Person?)
"""
if not member in self.members:
self.members.append(member)
def memberChangedNick(self, oldnick, newnick):
"""Changes the oldnick in the list of members to newnick and displays this
change to the user
@type oldnick: string
@type newnick: string
"""
if oldnick in self.members:
self.members.remove(oldnick)
self.members.append(newnick)
#self.chatui.contactChangedNick(oldnick, newnick)
def memberLeft(self, member):
"""Deletes the given member from the list of members in the group
conversation and displays the change to the user
@type member: string
"""
if member in self.members:
self.members.remove(member)
class ChatUI:
"""A GUI chat client"""
def __init__(self):
self.conversations = {} # cache of all direct windows
self.groupConversations = {} # cache of all group windows
self.persons = {} # keys are (name, client)
self.groups = {} # cache of all groups
self.onlineClients = [] # list of message sources currently online
self.contactsList = ContactsList(self)
def registerAccountClient(self, client):
"""Notifies user that an account has been signed on to.
@type client: L{Client<interfaces.IClient>}
@returns: client, so that I may be used in a callback chain
"""
print "signing onto", client.accountName
self.onlineClients.append(client)
self.contactsList.registerAccountClient(client)
return client
def unregisterAccountClient(self, client):
"""Notifies user that an account has been signed off or disconnected
@type client: L{Client<interfaces.IClient>}
"""
print "signing off from", client.accountName
self.onlineClients.remove(client)
self.contactsList.unregisterAccountClient(client)
def getContactsList(self):
"""
@returntype: L{ContactsList}
"""
return self.contactsList
def getConversation(self, person, Class=Conversation, stayHidden=0):
"""For the given person object, returns the conversation window
or creates and returns a new conversation window if one does not exist.
@type person: L{Person<interfaces.IPerson>}
@type Class: L{Conversation<interfaces.IConversation>} class
@type stayHidden: boolean
@returntype: L{Conversation<interfaces.IConversation>}
"""
conv = self.conversations.get(person)
if not conv:
conv = Class(person, self)
self.conversations[person] = conv
if stayHidden:
conv.hide()
else:
conv.show()
return conv
def getGroupConversation(self,group,Class=GroupConversation,stayHidden=0):
"""For the given group object, returns the group conversation window or
creates and returns a new group conversation window if it doesn't exist
@type group: L{Group<interfaces.IGroup>}
@type Class: L{Conversation<interfaces.IConversation>} class
@type stayHidden: boolean
@returntype: L{GroupConversation<interfaces.IGroupConversation>}
"""
conv = self.groupConversations.get(group)
if not conv:
conv = Class(group, self)
self.groupConversations[group] = conv
if stayHidden:
conv.hide()
else:
conv.show()
return conv
def getPerson(self, name, client):
"""For the given name and account client, returns the instance of the
AbstractPerson subclass, or creates and returns a new AbstractPerson
subclass of the type Class
@type name: string
@type client: L{Client<interfaces.IClient>}
@returntype: L{Person<interfaces.IPerson>}
"""
account = client.account
p = self.persons.get((name, account))
if not p:
p = account.getPerson(name)
self.persons[name, account] = p
return p
def getGroup(self, name, client):
"""For the given name and account client, returns the instance of the
AbstractGroup subclass, or creates and returns a new AbstractGroup
subclass of the type Class
@type name: string
@type client: L{Client<interfaces.IClient>}
@returntype: L{Group<interfaces.IGroup>}
"""
# I accept 'client' instead of 'account' in my signature for
# backwards compatibility. (Groups changed to be Account-oriented
# in CVS revision 1.8.)
account = client.account
g = self.groups.get((name, account))
if not g:
g = account.getGroup(name)
self.groups[name, account] = g
return g
def contactChangedNick(self, oldnick, newnick):
"""For the given person, changes the person's name to newnick, and
tells the contact list and any conversation windows with that person
to change as well.
@type oldnick: string
@type newnick: string
"""
if self.persons.has_key((person.name, person.account)):
conv = self.conversations.get(person)
if conv:
conv.contactChangedNick(person, newnick)
self.contactsList.contactChangedNick(person, newnick)
del self.persons[person.name, person.account]
person.name = newnick
self.persons[person.name, person.account] = person | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/im/basechat.py | basechat.py |
# System Imports
import string, re
from zope.interface import implements
# Twisted Imports
from twisted.words.protocols import toc
from twisted.words.im.locals import ONLINE, OFFLINE, AWAY
from twisted.internet import defer, reactor, protocol
from twisted.internet.defer import succeed
# Sibling Imports
from twisted.words.im import basesupport, interfaces, locals
def dehtml(text):
text=string.replace(text,"<br>","\n")
text=string.replace(text,"<BR>","\n")
text=string.replace(text,"<Br>","\n") # XXX make this a regexp
text=string.replace(text,"<bR>","\n")
text=re.sub('<.*?>','',text)
text=string.replace(text,'>','>')
text=string.replace(text,'<','<')
text=string.replace(text,'&','&')
text=string.replace(text,' ',' ')
text=string.replace(text,'"','"')
return text
def html(text):
text=string.replace(text,'"','"')
text=string.replace(text,'&','&')
text=string.replace(text,'<','<')
text=string.replace(text,'>','>')
text=string.replace(text,"\n","<br>")
return '<font color="#000000" back="#ffffff" size=3>%s</font>'%text
class TOCPerson(basesupport.AbstractPerson):
def isOnline(self):
return self.status != OFFLINE
def getStatus(self):
return self.status
def getIdleTime(self):
return str(self.idletime)
def setStatusAndIdle(self, status, idletime):
if self.account.client is None:
raise locals.OfflineError
self.status = status
self.idletime = idletime
self.account.client.chat.getContactsList().setContactStatus(self)
def sendMessage(self, text, meta=None):
if self.account.client is None:
raise locals.OfflineError
if meta:
if meta.get("style", None) == "emote":
text="* "+text+"* "
self.account.client.say(self.name,html(text))
return succeed(text)
class TOCGroup(basesupport.AbstractGroup):
implements(interfaces.IGroup)
def __init__(self, name, tocAccount):
basesupport.AbstractGroup.__init__(self, name, tocAccount)
self.roomID = self.client.roomID[self.name]
def sendGroupMessage(self, text, meta=None):
if self.account.client is None:
raise locals.OfflineError
if meta:
if meta.get("style", None) == "emote":
text="* "+text+"* "
self.account.client.chat_say(self.roomID,html(text))
return succeed(text)
def leave(self):
if self.account.client is None:
raise locals.OfflineError
self.account.client.chat_leave(self.roomID)
class TOCProto(basesupport.AbstractClientMixin, toc.TOCClient):
def __init__(self, account, chatui, logonDeferred):
toc.TOCClient.__init__(self, account.username, account.password)
basesupport.AbstractClientMixin.__init__(self, account, chatui,
logonDeferred)
self.roomID = {}
self.roomIDreverse = {}
def _debug(self, m):
pass #print '<toc debug>', repr(m)
def getGroupConversation(self, name, hide=0):
return self.chat.getGroupConversation(
self.chat.getGroup(name, self), hide)
def addContact(self, name):
self.add_buddy([name])
if not self._buddylist.has_key('TwistedIM'):
self._buddylist['TwistedIM'] = []
if name in self._buddylist['TwistedIM']:
# whoops, don't add again
return
self._buddylist['TwistedIM'].append(name)
self.set_config(self._config_mode, self._buddylist, self._permit, self._deny)
def getPerson(self,name):
return self.chat.getPerson(name, self)
def onLine(self):
self.account._isOnline = 1
#print '$$!&*$&!(@$*& TOC ONLINE *!#@&$(!*%&'
def gotConfig(self, mode, buddylist, permit, deny):
#print 'got toc config', repr(mode), repr(buddylist), repr(permit), repr(deny)
self._config_mode = mode
self._buddylist = buddylist
self._permit = permit
self._deny = deny
if permit:
self._debug('adding permit')
self.add_permit(permit)
if deny:
self._debug('adding deny')
self.add_deny(deny)
clist=[]
for k in buddylist.keys():
self.add_buddy(buddylist[k])
for name in buddylist[k]:
self.getPerson(name).setStatusAndIdle(OFFLINE, '--')
self.signon()
name = None
def tocNICK(self,data):
if not self.name:
print 'Waiting for second NICK', data
self.name=data[0]
self.accountName = '%s (TOC)' % self.name
self.chat.getContactsList()
else:
print 'reregistering...?', data
self.name=data[0]
# self.accountName = "%s (TOC)"%data[0]
if self._logonDeferred is not None:
self._logonDeferred.callback(self)
self._logonDeferred = None
### Error Messages
def hearError(self, code, args):
print '*** TOC ERROR ***', repr(code), repr(args)
def hearWarning(self, newamount, username):
print '*** TOC WARNING ***', repr(newamount), repr(username)
### Buddy Messages
def hearMessage(self,username,message,autoreply):
if autoreply:
message='<AUTO-REPLY>: '+message
self.chat.getConversation(self.getPerson(username)
).showMessage(dehtml(message))
def updateBuddy(self,username,online,evilness,signontime,idletime,userclass,away):
if away:
status=AWAY
elif online:
status=ONLINE
else:
status=OFFLINE
self.getPerson(username).setStatusAndIdle(status, idletime)
### Group Chat
def chatJoined(self, roomid, roomname, users):
self.roomID[roomname]=roomid
self.roomIDreverse[roomid]=roomname
self.getGroupConversation(roomname).setGroupMembers(users)
def chatUpdate(self,roomid,member,inroom):
group=self.roomIDreverse[roomid]
if inroom:
self.getGroupConversation(group).memberJoined(member)
else:
self.getGroupConversation(group).memberLeft(member)
def chatHearMessage(self, roomid, username, message):
if toc.normalize(username) == toc.normalize(self.name):
return # ignore the message
group=self.roomIDreverse[roomid]
self.getGroupConversation(group).showGroupMessage(username, dehtml(message))
def chatHearWhisper(self, roomid, username, message):
print '*** user whispered *** ', roomid, username, message
def chatInvited(self, roomid, roomname, username, message):
print '*** user invited us to chat *** ',roomid, roomname, username, message
def chatLeft(self, roomid):
group=self.roomIDreverse[roomid]
self.getGroupConversation(group,1)
del self.roomID[group]
del self.roomIDreverse[roomid]
def rvousProposal(self,type,cookie,user,vip,port,**kw):
print '*** rendezvous. ***', type, cookie, user, vip, port, kw
def receiveBytes(self, user, file, chunk, sofar, total):
print '*** File transfer! ***', user, file, chunk, sofar, total
def joinGroup(self,name):
self.chat_join(4,toc.normalize(name))
class TOCAccount(basesupport.AbstractAccount):
implements(interfaces.IAccount)
gatewayType = "AIM (TOC)"
_groupFactory = TOCGroup
_personFactory = TOCPerson
def _startLogOn(self, chatui):
logonDeferred = defer.Deferred()
cc = protocol.ClientCreator(reactor, TOCProto, self, chatui,
logonDeferred)
d = cc.connectTCP(self.host, self.port)
d.addErrback(logonDeferred.errback)
return logonDeferred | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/im/tocsupport.py | tocsupport.py |
from __future__ import nested_scopes
from twisted.internet import defer
from twisted.internet import error
from twisted.python import log
from twisted.python.failure import Failure
from twisted.spread import pb
from twisted.words.im.locals import ONLINE, OFFLINE, AWAY
from twisted.words.im import basesupport, interfaces
from zope.interface import implements
class TwistedWordsPerson(basesupport.AbstractPerson):
"""I a facade for a person you can talk to through a twisted.words service.
"""
def __init__(self, name, wordsAccount):
basesupport.AbstractPerson.__init__(self, name, wordsAccount)
self.status = OFFLINE
def isOnline(self):
return ((self.status == ONLINE) or
(self.status == AWAY))
def getStatus(self):
return self.status
def sendMessage(self, text, metadata):
"""Return a deferred...
"""
if metadata:
d=self.account.client.perspective.directMessage(self.name,
text, metadata)
d.addErrback(self.metadataFailed, "* "+text)
return d
else:
return self.account.client.perspective.callRemote('directMessage',self.name, text)
def metadataFailed(self, result, text):
print "result:",result,"text:",text
return self.account.client.perspective.directMessage(self.name, text)
def setStatus(self, status):
self.status = status
self.chat.getContactsList().setContactStatus(self)
class TwistedWordsGroup(basesupport.AbstractGroup):
implements(interfaces.IGroup)
def __init__(self, name, wordsClient):
basesupport.AbstractGroup.__init__(self, name, wordsClient)
self.joined = 0
def sendGroupMessage(self, text, metadata=None):
"""Return a deferred.
"""
#for backwards compatibility with older twisted.words servers.
if metadata:
d=self.account.client.perspective.callRemote(
'groupMessage', self.name, text, metadata)
d.addErrback(self.metadataFailed, "* "+text)
return d
else:
return self.account.client.perspective.callRemote('groupMessage',
self.name, text)
def setTopic(self, text):
self.account.client.perspective.callRemote(
'setGroupMetadata',
{'topic': text, 'topic_author': self.client.name},
self.name)
def metadataFailed(self, result, text):
print "result:",result,"text:",text
return self.account.client.perspective.callRemote('groupMessage',
self.name, text)
def joining(self):
self.joined = 1
def leaving(self):
self.joined = 0
def leave(self):
return self.account.client.perspective.callRemote('leaveGroup',
self.name)
class TwistedWordsClient(pb.Referenceable, basesupport.AbstractClientMixin):
"""In some cases, this acts as an Account, since it a source of text
messages (multiple Words instances may be on a single PB connection)
"""
def __init__(self, acct, serviceName, perspectiveName, chatui,
_logonDeferred=None):
self.accountName = "%s (%s:%s)" % (acct.accountName, serviceName, perspectiveName)
self.name = perspectiveName
print "HELLO I AM A PB SERVICE", serviceName, perspectiveName
self.chat = chatui
self.account = acct
self._logonDeferred = _logonDeferred
def getPerson(self, name):
return self.chat.getPerson(name, self)
def getGroup(self, name):
return self.chat.getGroup(name, self)
def getGroupConversation(self, name):
return self.chat.getGroupConversation(self.getGroup(name))
def addContact(self, name):
self.perspective.callRemote('addContact', name)
def remote_receiveGroupMembers(self, names, group):
print 'received group members:', names, group
self.getGroupConversation(group).setGroupMembers(names)
def remote_receiveGroupMessage(self, sender, group, message, metadata=None):
print 'received a group message', sender, group, message, metadata
self.getGroupConversation(group).showGroupMessage(sender, message, metadata)
def remote_memberJoined(self, member, group):
print 'member joined', member, group
self.getGroupConversation(group).memberJoined(member)
def remote_memberLeft(self, member, group):
print 'member left'
self.getGroupConversation(group).memberLeft(member)
def remote_notifyStatusChanged(self, name, status):
self.chat.getPerson(name, self).setStatus(status)
def remote_receiveDirectMessage(self, name, message, metadata=None):
self.chat.getConversation(self.chat.getPerson(name, self)).showMessage(message, metadata)
def remote_receiveContactList(self, clist):
for name, status in clist:
self.chat.getPerson(name, self).setStatus(status)
def remote_setGroupMetadata(self, dict_, groupName):
if dict_.has_key("topic"):
self.getGroupConversation(groupName).setTopic(dict_["topic"], dict_.get("topic_author", None))
def joinGroup(self, name):
self.getGroup(name).joining()
return self.perspective.callRemote('joinGroup', name).addCallback(self._cbGroupJoined, name)
def leaveGroup(self, name):
self.getGroup(name).leaving()
return self.perspective.callRemote('leaveGroup', name).addCallback(self._cbGroupLeft, name)
def _cbGroupJoined(self, result, name):
groupConv = self.chat.getGroupConversation(self.getGroup(name))
groupConv.showGroupMessage("sys", "you joined")
self.perspective.callRemote('getGroupMembers', name)
def _cbGroupLeft(self, result, name):
print 'left',name
groupConv = self.chat.getGroupConversation(self.getGroup(name), 1)
groupConv.showGroupMessage("sys", "you left")
def connected(self, perspective):
print 'Connected Words Client!', perspective
if self._logonDeferred is not None:
self._logonDeferred.callback(self)
self.perspective = perspective
self.chat.getContactsList()
pbFrontEnds = {
"twisted.words": TwistedWordsClient,
"twisted.reality": None
}
class PBAccount(basesupport.AbstractAccount):
implements(interfaces.IAccount)
gatewayType = "PB"
_groupFactory = TwistedWordsGroup
_personFactory = TwistedWordsPerson
def __init__(self, accountName, autoLogin, username, password, host, port,
services=None):
"""
@param username: The name of your PB Identity.
@type username: string
"""
basesupport.AbstractAccount.__init__(self, accountName, autoLogin,
username, password, host, port)
self.services = []
if not services:
services = [('twisted.words', 'twisted.words', username)]
for serviceType, serviceName, perspectiveName in services:
self.services.append([pbFrontEnds[serviceType], serviceName,
perspectiveName])
def logOn(self, chatui):
"""
@returns: this breaks with L{interfaces.IAccount}
@returntype: DeferredList of L{interfaces.IClient}s
"""
# Overriding basesupport's implementation on account of the
# fact that _startLogOn tends to return a deferredList rather
# than a simple Deferred, and we need to do registerAccountClient.
if (not self._isConnecting) and (not self._isOnline):
self._isConnecting = 1
d = self._startLogOn(chatui)
d.addErrback(self._loginFailed)
def registerMany(results):
for success, result in results:
if success:
chatui.registerAccountClient(result)
self._cb_logOn(result)
else:
log.err(result)
d.addCallback(registerMany)
return d
else:
raise error.ConnectionError("Connection in progress")
def _startLogOn(self, chatui):
print 'Connecting...',
d = pb.getObjectAt(self.host, self.port)
d.addCallbacks(self._cbConnected, self._ebConnected,
callbackArgs=(chatui,))
return d
def _cbConnected(self, root, chatui):
print 'Connected!'
print 'Identifying...',
d = pb.authIdentity(root, self.username, self.password)
d.addCallbacks(self._cbIdent, self._ebConnected,
callbackArgs=(chatui,))
return d
def _cbIdent(self, ident, chatui):
if not ident:
print 'falsely identified.'
return self._ebConnected(Failure(Exception("username or password incorrect")))
print 'Identified!'
dl = []
for handlerClass, sname, pname in self.services:
d = defer.Deferred()
dl.append(d)
handler = handlerClass(self, sname, pname, chatui, d)
ident.callRemote('attach', sname, pname, handler).addCallback(handler.connected)
return defer.DeferredList(dl)
def _ebConnected(self, error):
print 'Not connected.'
return error | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/im/pbsupport.py | pbsupport.py |
import string
from twisted.words.protocols import irc
from twisted.words.im.locals import ONLINE
from twisted.internet import defer, reactor, protocol
from twisted.internet.defer import succeed
from twisted.words.im import basesupport, interfaces, locals
from zope.interface import implements
class IRCPerson(basesupport.AbstractPerson):
def imperson_whois(self):
if self.account.client is None:
raise locals.OfflineError
self.account.client.sendLine("WHOIS %s" % self.name)
### interface impl
def isOnline(self):
return ONLINE
def getStatus(self):
return ONLINE
def setStatus(self,status):
self.status=status
self.chat.getContactsList().setContactStatus(self)
def sendMessage(self, text, meta=None):
if self.account.client is None:
raise locals.OfflineError
for line in string.split(text, '\n'):
if meta and meta.get("style", None) == "emote":
self.account.client.ctcpMakeQuery(self.name,[('ACTION', line)])
else:
self.account.client.msg(self.name, line)
return succeed(text)
class IRCGroup(basesupport.AbstractGroup):
implements(interfaces.IGroup)
def imgroup_testAction(self):
print 'action test!'
def imtarget_kick(self, target):
if self.account.client is None:
raise locals.OfflineError
reason = "for great justice!"
self.account.client.sendLine("KICK #%s %s :%s" % (
self.name, target.name, reason))
### Interface Implementation
def setTopic(self, topic):
if self.account.client is None:
raise locals.OfflineError
self.account.client.topic(self.name, topic)
def sendGroupMessage(self, text, meta={}):
if self.account.client is None:
raise locals.OfflineError
if meta and meta.get("style", None) == "emote":
self.account.client.me(self.name,text)
return succeed(text)
#standard shmandard, clients don't support plain escaped newlines!
for line in string.split(text, '\n'):
self.account.client.say(self.name, line)
return succeed(text)
def leave(self):
if self.account.client is None:
raise locals.OfflineError
self.account.client.leave(self.name)
self.account.client.getGroupConversation(self.name,1)
class IRCProto(basesupport.AbstractClientMixin, irc.IRCClient):
def __init__(self, account, chatui, logonDeferred=None):
basesupport.AbstractClientMixin.__init__(self, account, chatui,
logonDeferred)
self._namreplies={}
self._ingroups={}
self._groups={}
self._topics={}
def getGroupConversation(self, name, hide=0):
name=string.lower(name)
return self.chat.getGroupConversation(self.chat.getGroup(name, self),
stayHidden=hide)
def getPerson(self,name):
return self.chat.getPerson(name, self)
def connectionMade(self):
# XXX: Why do I duplicate code in IRCClient.register?
try:
print 'connection made on irc service!?', self
if self.account.password:
self.sendLine("PASS :%s" % self.account.password)
self.setNick(self.account.username)
self.sendLine("USER %s foo bar :Twisted-IM user" % (self.nickname,))
for channel in self.account.channels:
self.joinGroup(channel)
self.account._isOnline=1
print 'uh, registering irc acct'
if self._logonDeferred is not None:
self._logonDeferred.callback(self)
self.chat.getContactsList()
except:
import traceback
traceback.print_exc()
def setNick(self,nick):
self.name=nick
self.accountName="%s (IRC)"%nick
irc.IRCClient.setNick(self,nick)
def kickedFrom(self, channel, kicker, message):
"""Called when I am kicked from a channel.
"""
print 'ono i was kicked', channel, kicker, message
return self.chat.getGroupConversation(
self.chat.getGroup(channel[1:], self), 1)
def userKicked(self, kickee, channel, kicker, message):
print 'whew somebody else', kickee, channel, kicker, message
def noticed(self, username, channel, message):
self.privmsg(username, channel, message, {"dontAutoRespond": 1})
def privmsg(self, username, channel, message, metadata=None):
if metadata is None:
metadata = {}
username=string.split(username,'!',1)[0]
if username==self.name: return
if channel[0]=='#':
group=channel[1:]
self.getGroupConversation(group).showGroupMessage(username, message, metadata)
return
self.chat.getConversation(self.getPerson(username)).showMessage(message, metadata)
def action(self,username,channel,emote):
username=string.split(username,'!',1)[0]
if username==self.name: return
meta={'style':'emote'}
if channel[0]=='#':
group=channel[1:]
self.getGroupConversation(group).showGroupMessage(username, emote, meta)
return
self.chat.getConversation(self.getPerson(username)).showMessage(emote,meta)
def irc_RPL_NAMREPLY(self,prefix,params):
"""
RPL_NAMREPLY
>> NAMES #bnl
<< :Arlington.VA.US.Undernet.Org 353 z3p = #bnl :pSwede Dan-- SkOyg AG
"""
group=string.lower(params[2][1:])
users=string.split(params[3])
for ui in range(len(users)):
while users[ui][0] in ["@","+"]: # channel modes
users[ui]=users[ui][1:]
if not self._namreplies.has_key(group):
self._namreplies[group]=[]
self._namreplies[group].extend(users)
for nickname in users:
try:
self._ingroups[nickname].append(group)
except:
self._ingroups[nickname]=[group]
def irc_RPL_ENDOFNAMES(self,prefix,params):
group=params[1][1:]
self.getGroupConversation(group).setGroupMembers(self._namreplies[string.lower(group)])
del self._namreplies[string.lower(group)]
def irc_RPL_TOPIC(self,prefix,params):
self._topics[params[1][1:]]=params[2]
def irc_333(self,prefix,params):
group=params[1][1:]
self.getGroupConversation(group).setTopic(self._topics[group],params[2])
del self._topics[group]
def irc_TOPIC(self,prefix,params):
nickname = string.split(prefix,"!")[0]
group = params[0][1:]
topic = params[1]
self.getGroupConversation(group).setTopic(topic,nickname)
def irc_JOIN(self,prefix,params):
nickname=string.split(prefix,"!")[0]
group=string.lower(params[0][1:])
if nickname!=self.nickname:
try:
self._ingroups[nickname].append(group)
except:
self._ingroups[nickname]=[group]
self.getGroupConversation(group).memberJoined(nickname)
def irc_PART(self,prefix,params):
nickname=string.split(prefix,"!")[0]
group=string.lower(params[0][1:])
if nickname!=self.nickname:
if group in self._ingroups[nickname]:
self._ingroups[nickname].remove(group)
self.getGroupConversation(group).memberLeft(nickname)
else:
print "%s left %s, but wasn't in the room."%(nickname,group)
def irc_QUIT(self,prefix,params):
nickname=string.split(prefix,"!")[0]
if self._ingroups.has_key(nickname):
for group in self._ingroups[nickname]:
self.getGroupConversation(group).memberLeft(nickname)
self._ingroups[nickname]=[]
else:
print '*** WARNING: ingroups had no such key %s' % nickname
def irc_NICK(self, prefix, params):
fromNick = string.split(prefix, "!")[0]
toNick = params[0]
if not self._ingroups.has_key(fromNick):
print "%s changed nick to %s. But she's not in any groups!?" % (fromNick, toNick)
return
for group in self._ingroups[fromNick]:
self.getGroupConversation(group).memberChangedNick(fromNick, toNick)
self._ingroups[toNick] = self._ingroups[fromNick]
del self._ingroups[fromNick]
def irc_unknown(self, prefix, command, params):
print "unknown message from IRCserver. prefix: %s, command: %s, params: %s" % (prefix, command, params)
# GTKIM calls
def joinGroup(self,name):
self.join(name)
self.getGroupConversation(name)
class IRCAccount(basesupport.AbstractAccount):
implements(interfaces.IAccount)
gatewayType = "IRC"
_groupFactory = IRCGroup
_personFactory = IRCPerson
def __init__(self, accountName, autoLogin, username, password, host, port,
channels=''):
basesupport.AbstractAccount.__init__(self, accountName, autoLogin,
username, password, host, port)
self.channels = map(string.strip,string.split(channels,','))
if self.channels == ['']:
self.channels = []
def _startLogOn(self, chatui):
logonDeferred = defer.Deferred()
cc = protocol.ClientCreator(reactor, IRCProto, self, chatui,
logonDeferred)
d = cc.connectTCP(self.host, self.port)
d.addErrback(logonDeferred.errback)
return logonDeferred | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/im/ircsupport.py | ircsupport.py |
import string
import time
import gtk
from twisted.words.im.gtkcommon import GLADE_FILE, autoConnectMethods, InputOutputWindow, openGlade
class ContactsList:
def __init__(self, chatui, xml):
self.xml = xml# openGlade(GLADE_FILE, root="ContactsWidget")
# self.widget = self.xml.get_widget("ContactsWidget")
self.people = []
self.onlinePeople = []
self.countOnline = 0
autoConnectMethods(self)
self.selectedPerson = None
self.xml.get_widget("OnlineCount").set_text("Online: 0")
self.chat = chatui
# Construct Menu for Account Selection
self.optionMenu = self.xml.get_widget("AccountsListPopup")
self.accountMenuItems = []
self.currentAccount = None
def registerAccountClient(self, account):
print 'registering account client', self, account
self.accountMenuItems.append(account)
self._updateAccountMenu()
self.chat._accountmanager.refreshAccounts()
def _updateAccountMenu(self):
# This seems to be necessary -- I don't understand gtk's handling of
# GtkOptionMenus
print 'updating account menu', self.accountMenuItems
self.accountMenu = gtk.GtkMenu()
for account in self.accountMenuItems:
i = gtk.GtkMenuItem(account.accountName)
i.connect('activate', self.on_AccountsListPopup_activate, account)
self.accountMenu.append(i)
if self.accountMenuItems:
print "setting default account to", self.accountMenuItems[0]
self.currentAccount = self.accountMenuItems[0]
self.accountMenu.show_all()
self.optionMenu.set_menu(self.accountMenu)
def on_AccountsListPopup_activate(self, w, account):
print 'setting current account', account
self.currentAccount = account
def on_AddContactButton_clicked(self, b):
self.currentAccount.addContact(
self.xml.get_widget("ContactNameEntry").get_text())
def unregisterAccountClient(self,account):
print 'unregistering account client', self, account
self.accountMenuItems.remove(account)
self._updateAccountMenu()
def setContactStatus(self, person):
if person not in self.people:
self.people.append(person)
self.refreshContactsLists()
def on_OnlineContactsTree_select_row(self, w, row, column, event):
self.selectedPerson = self.onlinePeople[row]
entry = self.xml.get_widget("ContactNameEntry")
entry.set_text(self.selectedPerson.name)
self.currentAccount = self.selectedPerson.account.client
idx = self.accountMenuItems.index(self.currentAccount)
self.accountMenu.set_active(idx)
self.optionMenu.remove_menu()
self.optionMenu.set_menu(self.accountMenu)
def on_PlainSendIM_clicked(self, b):
self.chat.getConversation(
self.currentAccount.getPerson(
self.xml.get_widget("ContactNameEntry").get_text()))
## if self.selectedPerson:
## c = self.chat.getConversation(self.selectedPerson)
def on_PlainJoinChat_clicked(self, b):
## GroupJoinWindow(self.chat)
name = self.xml.get_widget("ContactNameEntry").get_text()
self.currentAccount.joinGroup(name)
def refreshContactsLists(self):
# HIDEOUSLY inefficient
online = self.xml.get_widget("OnlineContactsTree")
offline = self.xml.get_widget("OfflineContactsList")
online.freeze()
offline.freeze()
online.clear()
offline.clear()
self.countOnline = 0
self.onlinePeople = []
self.people.sort(lambda x, y: cmp(x.name, y.name))
for person in self.people:
if person.isOnline():
self.onlinePeople.append(person)
online.append([person.name, str(person.getStatus()),
person.getIdleTime(),
person.account.accountName])
self.countOnline = self.countOnline + 1
offline.append([person.name, person.account.accountName,
'Aliasing Not Implemented', 'Groups Not Implemented'])
self.xml.get_widget("OnlineCount").set_text("Online: %d" % self.countOnline)
online.thaw()
offline.thaw()
def colorhash(name):
h = hash(name)
l = [0x5555ff,
0x55aa55,
0x55aaff,
0xff5555,
0xff55ff,
0xffaa55]
index = l[h % len(l)]
return '%06.x' % (abs(hash(name)) & index)
def _msgDisplay(output, name, text, color, isEmote):
text = string.replace(text, '\n', '\n\t')
ins = output.insert
ins(None, color, None, "[ %s ] " % time.strftime("%H:%M:%S"))
if isEmote:
ins(None, color, None, "* %s " % name)
ins(None, None, None, "%s\n" % text)
else:
ins(None, color, None, "<%s> " % name)
ins(None, None, None, "%s\n" % text)
class Conversation(InputOutputWindow):
"""GUI representation of a conversation.
"""
def __init__(self, person):
InputOutputWindow.__init__(self,
"ConversationWidget",
"ConversationMessageEntry",
"ConversationOutput")
self.person = person
alloc_color = self.output.get_colormap().alloc
self.personColor = alloc_color("#%s" % colorhash(person.name))
self.myColor = alloc_color("#0000ff")
print "allocated my color %s and person color %s" % (
self.myColor, self.personColor)
def getTitle(self):
return "Conversation - %s (%s)" % (self.person.name,
self.person.account.accountName)
# Chat Interface Implementation
def sendText(self, text):
metadata = None
if text[:4] == "/me ":
text = text[4:]
metadata = {"style": "emote"}
self.person.sendMessage(text, metadata).addCallback(self._cbTextSent, text, metadata)
def showMessage(self, text, metadata=None):
_msgDisplay(self.output, self.person.name, text, self.personColor,
(metadata and metadata.get("style", None) == "emote"))
# Internal
def _cbTextSent(self, result, text, metadata=None):
_msgDisplay(self.output, self.person.account.client.name,
text, self.myColor,
(metadata and metadata.get("style", None) == "emote"))
class GroupConversation(InputOutputWindow):
def __init__(self, group):
InputOutputWindow.__init__(self,
"GroupChatBox",
"GroupInput",
"GroupOutput")
self.group = group
self.members = []
self.membersHidden = 0
self._colorcache = {}
alloc_color = self.output.get_colormap().alloc
self.myColor = alloc_color("#0000ff")
# TODO: we shouldn't be getting group conversations randomly without
# names, but irc autojoin appears broken.
self.xml.get_widget("NickLabel").set_text(
getattr(self.group.account.client,"name","(no name)"))
participantList = self.xml.get_widget("ParticipantList")
groupBox = self.xml.get_widget("GroupActionsBox")
for method in group.getGroupCommands():
b = gtk.GtkButton(method.__name__)
b.connect("clicked", self._doGroupAction, method)
groupBox.add(b)
self.setTopic("No Topic Yet", "No Topic Author Yet")
# GTK Event Handlers
def on_HideButton_clicked(self, b):
self.membersHidden = not self.membersHidden
self.xml.get_widget("GroupHPaned").set_position(self.membersHidden and -1 or 20000)
def on_LeaveButton_clicked(self, b):
self.win.destroy()
self.group.leave()
def on_AddContactButton_clicked(self, b):
lw = self.xml.get_widget("ParticipantList")
if lw.selection:
self.group.client.addContact(self.members[lw.selection[0]])
def on_TopicEntry_focus_out_event(self, w, e):
self.xml.get_widget("TopicEntry").set_text(self._topic)
def on_TopicEntry_activate(self, e):
print "ACTIVATING TOPIC!!"
self.group.setTopic(e.get_text())
# self.xml.get_widget("TopicEntry").set_editable(0)
self.xml.get_widget("GroupInput").grab_focus()
def on_ParticipantList_unselect_row(self, w, row, column, event):
print 'row unselected'
personBox = self.xml.get_widget("PersonActionsBox")
for child in personBox.children():
personBox.remove(child)
def on_ParticipantList_select_row(self, w, row, column, event):
self.selectedPerson = self.group.account.client.getPerson(self.members[row])
print 'selected', self.selectedPerson
personBox = self.xml.get_widget("PersonActionsBox")
personFrame = self.xml.get_widget("PersonFrame")
# clear out old buttons
for child in personBox.children():
personBox.remove(child)
personFrame.set_label("Person: %s" % self.selectedPerson.name)
for method in self.selectedPerson.getPersonCommands():
b = gtk.GtkButton(method.__name__)
b.connect("clicked", self._doPersonAction, method)
personBox.add(b)
b.show()
for method in self.group.getTargetCommands(self.selectedPerson):
b = gtk.GtkButton(method.__name__)
b.connect("clicked", self._doTargetAction, method,
self.selectedPerson)
personBox.add(b)
b.show()
def _doGroupAction(self, evt, method):
method()
def _doPersonAction(self, evt, method):
method()
def _doTargetAction(self, evt, method, person):
method(person)
def hidden(self, w):
InputOutputWindow.hidden(self, w)
self.group.leave()
def getTitle(self):
return "Group Conversation - " + self.group.name
# Chat Interface Implementation
def sendText(self, text):
metadata = None
if text[:4] == "/me ":
text = text[4:]
metadata = {"style": "emote"}
self.group.sendGroupMessage(text, metadata).addCallback(self._cbTextSent, text, metadata=metadata)
def showGroupMessage(self, sender, text, metadata=None):
_msgDisplay(self.output, sender, text, self._cacheColorHash(sender),
(metadata and metadata.get("style", None) == "emote"))
def setGroupMembers(self, members):
self.members = members
self.refreshMemberList()
def setTopic(self, topic, author):
self._topic = topic
self._topicAuthor = author
self.xml.get_widget("TopicEntry").set_text(topic)
self.xml.get_widget("AuthorLabel").set_text(author)
def memberJoined(self, member):
self.members.append(member)
self.output.insert_defaults("> %s joined <\n" % member)
self.refreshMemberList()
def memberChangedNick(self, member, newnick):
self.members.remove(member)
self.members.append(newnick)
self.output.insert_defaults("> %s becomes %s <\n" % (member, newnick))
self.refreshMemberList()
def memberLeft(self, member):
self.members.remove(member)
self.output.insert_defaults("> %s left <\n" % member)
self.refreshMemberList()
# Tab Completion
def tabComplete(self, word):
"""InputOutputWindow calls me when tab is pressed."""
if not word:
return []
potentialMatches = []
for nick in self.members:
if string.lower(nick[:len(word)]) == string.lower(word):
potentialMatches.append(nick + ": ") #colon is a nick-specific thing
return potentialMatches
# Internal
def _cbTextSent(self, result, text, metadata=None):
_msgDisplay(self.output, self.group.account.client.name,
text, self.myColor,
(metadata and metadata.get("style", None) == "emote"))
def refreshMemberList(self):
pl = self.xml.get_widget("ParticipantList")
pl.freeze()
pl.clear()
self.members.sort(lambda x,y: cmp(string.lower(x), string.lower(y)))
for member in self.members:
pl.append([member])
pl.thaw()
def _cacheColorHash(self, name):
if self._colorcache.has_key(name):
return self._colorcache[name]
else:
alloc_color = self.output.get_colormap().alloc
c = alloc_color('#%s' % colorhash(name))
self._colorcache[name] = c
return c
class GtkChatClientUI:
def __init__(self,xml):
self.conversations = {} # cache of all direct windows
self.groupConversations = {} # cache of all group windows
self.personCache = {} # keys are (name, account)
self.groupCache = {} # cache of all groups
self.theContactsList = ContactsList(self,xml)
self.onlineAccounts = [] # list of message sources currently online
def registerAccountClient(self,account):
print 'registering account client'
self.onlineAccounts.append(account)
self.getContactsList().registerAccountClient(account)
def unregisterAccountClient(self,account):
print 'unregistering account client'
self.onlineAccounts.remove(account)
self.getContactsList().unregisterAccountClient(account)
def contactsListClose(self, w, evt):
return gtk.TRUE
def getContactsList(self):
return self.theContactsList
def getConversation(self, person):
conv = self.conversations.get(person)
if not conv:
conv = Conversation(person)
self.conversations[person] = conv
conv.show()
return conv
def getGroupConversation(self, group, stayHidden=0):
conv = self.groupConversations.get(group)
if not conv:
conv = GroupConversation(group)
self.groupConversations[group] = conv
if not stayHidden:
conv.show()
else:
conv.hide()
return conv
# ??? Why doesn't this inherit the basechat.ChatUI implementation?
def getPerson(self, name, client):
account = client.account
p = self.personCache.get((name, account))
if not p:
p = account.getPerson(name)
self.personCache[name, account] = p
return p
def getGroup(self, name, client):
account = client.account
g = self.groupCache.get((name, account))
if g is None:
g = account.getGroup(name)
self.groupCache[name, account] = g
return g | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/im/gtkchat.py | gtkchat.py |
#
from twisted.words.im.basechat import ContactsList, Conversation, GroupConversation,\
ChatUI
from twisted.words.im.locals import OFFLINE, ONLINE, AWAY
from java.awt import GridLayout, FlowLayout, BorderLayout, Container
import sys
from java.awt.event import ActionListener
from javax.swing import JTextField, JPasswordField, JComboBox, JPanel, JLabel,\
JTextArea, JFrame, JButton, BoxLayout, JTable, JScrollPane, \
ListSelectionModel
from javax.swing.table import DefaultTableModel
doublebuffered = 0
class UneditableTableModel(DefaultTableModel):
def isCellEditable(self, x, y):
return 0
class _AccountAdder:
def __init__(self, contactslist):
self.contactslist = contactslist
self.mainframe = JFrame("Add New Contact")
self.account = JComboBox(self.contactslist.clientsByName.keys())
self.contactname = JTextField()
self.buildpane()
def buildpane(self):
buttons = JPanel()
buttons.add(JButton("OK", actionPerformed=self.add))
buttons.add(JButton("Cancel", actionPerformed=self.cancel))
acct = JPanel(GridLayout(1, 2), doublebuffered)
acct.add(JLabel("Account"))
acct.add(self.account)
mainpane = self.mainframe.getContentPane()
mainpane.setLayout(BoxLayout(mainpane, BoxLayout.Y_AXIS))
mainpane.add(self.contactname)
mainpane.add(acct)
mainpane.add(buttons)
self.mainframe.pack()
self.mainframe.show()
#action listeners
def add(self, ae):
acct = self.contactslist.clientsByName[self.account.getSelectedItem()]
acct.addContact(self.contactname.getText())
self.mainframe.dispose()
def cancel(self, ae):
self.mainframe.dispose()
class ContactsListGUI(ContactsList):
"""A GUI object that displays a contacts list"""
def __init__(self, chatui):
ContactsList.__init__(self, chatui)
self.clientsByName = {}
self.mainframe = JFrame("Contacts List")
self.headers = ["Contact", "Status", "Idle", "Account"]
self.data = UneditableTableModel([], self.headers)
self.table = JTable(self.data,
columnSelectionAllowed = 0, #cannot select columns
selectionMode = ListSelectionModel.SINGLE_SELECTION)
self.buildpane()
self.mainframe.pack()
self.mainframe.show()
def setContactStatus(self, person):
ContactsList.setContactStatus(self, person)
self.update()
def registerAccountClient(self, client):
ContactsList.registerAccountClient(self, client)
if not client.accountName in self.clientsByName.keys():
self.clientsByName[client.accountName] = client
def unregisterAccount(self, client):
ContactsList.unregisterAccountClient(self, client)
if client.accountName in self.clientsByName.keys():
del self.clientsByName[client.accountName]
def contactChangedNick(self, person, newnick):
ContactsList.contactChangedNick(self, person, newnick)
self.update()
#GUI code
def buildpane(self):
buttons = JPanel(FlowLayout(), doublebuffered)
buttons.add(JButton("Send Message", actionPerformed=self.message))
buttons.add(JButton("Add Contact", actionPerformed=self.addContact))
#buttons.add(JButton("Quit", actionPerformed=self.quit))
mainpane = self.mainframe.getContentPane()
mainpane.setLayout(BoxLayout(mainpane, BoxLayout.Y_AXIS))
mainpane.add(JScrollPane(self.table))
mainpane.add(buttons)
self.update()
def update(self):
contactdata = []
for contact in self.onlineContacts.values():
if contact.status == AWAY:
stat = "(away)"
else:
stat = "(active)"
contactdata.append([contact.name, stat, contact.getIdleTime(),
contact.client.accountName])
self.data.setDataVector(contactdata, self.headers)
#callable actionlisteners
def message(self, ae):
row = self.table.getSelectedRow()
if row < 0:
print "Trying to send IM to person, but no person selected"
else:
person = self.onlineContacts[self.data.getValueAt(row, 0)]
self.chat.getConversation(person)
def addContact(self, ae):
_AccountAdder(self)
def quit(self, ae):
sys.exit()
class ConversationWindow(Conversation):
"""A GUI window of a conversation with a specific person"""
def __init__(self, person, chatui):
"""ConversationWindow(basesupport.AbstractPerson:person)"""
Conversation.__init__(self, person, chatui)
self.mainframe = JFrame("Conversation with "+person.name)
self.display = JTextArea(columns=100,
rows=15,
editable=0,
lineWrap=1)
self.typepad = JTextField()
self.buildpane()
self.lentext = 0
def buildpane(self):
buttons = JPanel(doublebuffered)
buttons.add(JButton("Send", actionPerformed=self.send))
buttons.add(JButton("Hide", actionPerformed=self.hidewindow))
mainpane = self.mainframe.getContentPane()
mainpane.setLayout(BoxLayout(mainpane, BoxLayout.Y_AXIS))
mainpane.add(JScrollPane(self.display))
self.typepad.actionPerformed = self.send
mainpane.add(self.typepad)
mainpane.add(buttons)
def show(self):
self.mainframe.pack()
self.mainframe.show()
def hide(self):
self.mainframe.hide()
def sendText(self, text):
self.displayText("\n"+self.person.client.name+": "+text)
Conversation.sendText(self, text)
def showMessage(self, text, metadata=None):
self.displayText("\n"+self.person.name+": "+text)
def contactChangedNick(self, person, newnick):
Conversation.contactChangedNick(self, person, newnick)
self.mainframe.setTitle("Conversation with "+newnick)
#GUI code
def displayText(self, text):
self.lentext = self.lentext + len(text)
self.display.append(text)
self.display.setCaretPosition(self.lentext)
#actionlisteners
def hidewindow(self, ae):
self.hide()
def send(self, ae):
text = self.typepad.getText()
self.typepad.setText("")
if text != "" and text != None:
self.sendText(text)
class GroupConversationWindow(GroupConversation):
"""A GUI window of a conversation witha group of people"""
def __init__(self, group, chatui):
GroupConversation.__init__(self, group, chatui)
self.mainframe = JFrame(self.group.name)
self.headers = ["Member"]
self.memberdata = UneditableTableModel([], self.headers)
self.display = JTextArea(columns=100, rows=15, editable=0, lineWrap=1)
self.typepad = JTextField()
self.buildpane()
self.lentext = 0
def show(self):
self.mainframe.pack()
self.mainframe.show()
def hide(self):
self.mainframe.hide()
def showGroupMessage(self, sender, text, metadata=None):
self.displayText(sender + ": " + text)
def setGroupMembers(self, members):
GroupConversation.setGroupMembers(self, members)
self.updatelist()
def setTopic(self, topic, author):
topictext = "Topic: " + topic + ", set by " + author
self.mainframe.setTitle(self.group.name + ": " + topictext)
self.displayText(topictext)
def memberJoined(self, member):
GroupConversation.memberJoined(self, member)
self.updatelist()
def memberChangedNick(self, oldnick, newnick):
GroupConversation.memberChangedNick(self, oldnick, newnick)
self.updatelist()
def memberLeft(self, member):
GroupConversation.memberLeft(self, member)
self.updatelist()
#GUI code
def buildpane(self):
buttons = JPanel(doublebuffered)
buttons.add(JButton("Hide", actionPerformed=self.hidewindow))
memberpane = JTable(self.memberdata)
memberframe = JScrollPane(memberpane)
chat = JPanel(doublebuffered)
chat.setLayout(BoxLayout(chat, BoxLayout.Y_AXIS))
chat.add(JScrollPane(self.display))
self.typepad.actionPerformed = self.send
chat.add(self.typepad)
chat.add(buttons)
mainpane = self.mainframe.getContentPane()
mainpane.setLayout(BoxLayout(mainpane, BoxLayout.X_AXIS))
mainpane.add(chat)
mainpane.add(memberframe)
def displayText(self, text):
self.lentext = self.lentext + len(text)
self.display.append(text)
self.display.setCaretPosition(self.lentext)
def updatelist(self):
self.memberdata.setDataVector([self.members], self.headers)
#actionListener
def send(self, ae):
text = self.typepad.getText()
self.typepad.setText("")
if text != "" and text != None:
GroupConversation.sendText(self, text)
def hidewindow(self, ae):
self.hide()
class JyChatUI(ChatUI):
def __init__(self):
ChatUI.__init__(self)
self.contactsList = ContactsListGUI(self)
def getConversation(self, person, stayHidden=0):
return ChatUI.getGroupConversation(self, person, ConversationWindow,
stayHidden)
def getGroupConversation(self, group, stayHidden=0):
return ChatUI.getGroupConversation(self, group,
GroupConversationWindow,
stayHidden) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/im/jychat.py | jychat.py |
#
"""
MSNP8 Protocol (client only) - semi-experimental
Stability: unstable.
This module provides support for clients using the MSN Protocol (MSNP8).
There are basically 3 servers involved in any MSN session:
I{Dispatch server}
The DispatchClient class handles connections to the
dispatch server, which basically delegates users to a
suitable notification server.
You will want to subclass this and handle the gotNotificationReferral
method appropriately.
I{Notification Server}
The NotificationClient class handles connections to the
notification server, which acts as a session server
(state updates, message negotiation etc...)
I{Switcboard Server}
The SwitchboardClient handles connections to switchboard
servers which are used to conduct conversations with other users.
There are also two classes (FileSend and FileReceive) used
for file transfers.
Clients handle events in two ways.
- each client request requiring a response will return a Deferred,
the callback for same will be fired when the server sends the
required response
- Events which are not in response to any client request have
respective methods which should be overridden and handled in
an adequate manner
Most client request callbacks require more than one argument,
and since Deferreds can only pass the callback one result,
most of the time the callback argument will be a tuple of
values (documented in the respective request method).
To make reading/writing code easier, callbacks can be defined in
a number of ways to handle this 'cleanly'. One way would be to
define methods like: def callBack(self, (arg1, arg2, arg)): ...
another way would be to do something like:
d.addCallback(lambda result: myCallback(*result)).
If the server sends an error response to a client request,
the errback of the corresponding Deferred will be called,
the argument being the corresponding error code.
B{NOTE}:
Due to the lack of an official spec for MSNP8, extra checking
than may be deemed necessary often takes place considering the
server is never 'wrong'. Thus, if gotBadLine (in any of the 3
main clients) is called, or an MSNProtocolError is raised, it's
probably a good idea to submit a bug report. ;)
Use of this module requires that PyOpenSSL is installed.
TODO
====
- check message hooks with invalid x-msgsinvite messages.
- font handling
- switchboard factory
@author: U{Sam Jordan<mailto:[email protected]>}
"""
from __future__ import nested_scopes
# Twisted imports
from twisted.internet import reactor
from twisted.internet.defer import Deferred
from twisted.internet.protocol import ClientFactory
from twisted.internet.ssl import ClientContextFactory
from twisted.python import failure, log
from twisted.protocols.basic import LineReceiver
from twisted.web.http import HTTPClient
# System imports
import types, operator, os, md5
from random import randint
from urllib import quote, unquote
MSN_PROTOCOL_VERSION = "MSNP8 CVR0" # protocol version
MSN_PORT = 1863 # default dispatch server port
MSN_MAX_MESSAGE = 1664 # max message length
MSN_CHALLENGE_STR = "Q1P7W2E4J9R8U3S5" # used for server challenges
MSN_CVR_STR = "0x0409 win 4.10 i386 MSNMSGR 5.0.0544 MSMSGS" # :(
# auth constants
LOGIN_SUCCESS = 1
LOGIN_FAILURE = 2
LOGIN_REDIRECT = 3
# list constants
FORWARD_LIST = 1
ALLOW_LIST = 2
BLOCK_LIST = 4
REVERSE_LIST = 8
# phone constants
HOME_PHONE = "PHH"
WORK_PHONE = "PHW"
MOBILE_PHONE = "PHM"
HAS_PAGER = "MOB"
# status constants
STATUS_ONLINE = 'NLN'
STATUS_OFFLINE = 'FLN'
STATUS_HIDDEN = 'HDN'
STATUS_IDLE = 'IDL'
STATUS_AWAY = 'AWY'
STATUS_BUSY = 'BSY'
STATUS_BRB = 'BRB'
STATUS_PHONE = 'PHN'
STATUS_LUNCH = 'LUN'
CR = "\r"
LF = "\n"
def checkParamLen(num, expected, cmd, error=None):
if error == None:
error = "Invalid Number of Parameters for %s" % cmd
if num != expected:
raise MSNProtocolError, error
def _parseHeader(h, v):
"""
Split a certin number of known
header values with the format:
field1=val,field2=val,field3=val into
a dict mapping fields to values.
@param h: the header's key
@param v: the header's value as a string
"""
if h in ('passporturls','authentication-info','www-authenticate'):
v = v.replace('Passport1.4','').lstrip()
fields = {}
for fieldPair in v.split(','):
try:
field,value = fieldPair.split('=',1)
fields[field.lower()] = value
except ValueError:
fields[field.lower()] = ''
return fields
else:
return v
def _parsePrimitiveHost(host):
# Ho Ho Ho
h,p = host.replace('https://','').split('/',1)
p = '/' + p
return h,p
def _login(userHandle, passwd, nexusServer, cached=0, authData=''):
"""
This function is used internally and should not ever be called
directly.
"""
cb = Deferred()
def _cb(server, auth):
loginFac = ClientFactory()
loginFac.protocol = lambda : PassportLogin(cb, userHandle, passwd, server, auth)
reactor.connectSSL(_parsePrimitiveHost(server)[0], 443, loginFac, ClientContextFactory())
if cached:
_cb(nexusServer, authData)
else:
fac = ClientFactory()
d = Deferred()
d.addCallbacks(_cb, callbackArgs=(authData,))
d.addErrback(lambda f: cb.errback(f))
fac.protocol = lambda : PassportNexus(d, nexusServer)
reactor.connectSSL(_parsePrimitiveHost(nexusServer)[0], 443, fac, ClientContextFactory())
return cb
class PassportNexus(HTTPClient):
"""
Used to obtain the URL of a valid passport
login HTTPS server.
This class is used internally and should
not be instantiated directly -- that is,
The passport logging in process is handled
transparantly by NotificationClient.
"""
def __init__(self, deferred, host):
self.deferred = deferred
self.host, self.path = _parsePrimitiveHost(host)
def connectionMade(self):
HTTPClient.connectionMade(self)
self.sendCommand('GET', self.path)
self.sendHeader('Host', self.host)
self.endHeaders()
self.headers = {}
def handleHeader(self, header, value):
h = header.lower()
self.headers[h] = _parseHeader(h, value)
def handleEndHeaders(self):
if self.connected:
self.transport.loseConnection()
if not self.headers.has_key('passporturls') or not self.headers['passporturls'].has_key('dalogin'):
self.deferred.errback(failure.Failure(failure.DefaultException("Invalid Nexus Reply")))
self.deferred.callback('https://' + self.headers['passporturls']['dalogin'])
def handleResponse(self, r):
pass
class PassportLogin(HTTPClient):
"""
This class is used internally to obtain
a login ticket from a passport HTTPS
server -- it should not be used directly.
"""
_finished = 0
def __init__(self, deferred, userHandle, passwd, host, authData):
self.deferred = deferred
self.userHandle = userHandle
self.passwd = passwd
self.authData = authData
self.host, self.path = _parsePrimitiveHost(host)
def connectionMade(self):
self.sendCommand('GET', self.path)
self.sendHeader('Authorization', 'Passport1.4 OrgVerb=GET,OrgURL=http://messenger.msn.com,' +
'sign-in=%s,pwd=%s,%s' % (quote(self.userHandle), self.passwd,self.authData))
self.sendHeader('Host', self.host)
self.endHeaders()
self.headers = {}
def handleHeader(self, header, value):
h = header.lower()
self.headers[h] = _parseHeader(h, value)
def handleEndHeaders(self):
if self._finished:
return
self._finished = 1 # I think we need this because of HTTPClient
if self.connected:
self.transport.loseConnection()
authHeader = 'authentication-info'
_interHeader = 'www-authenticate'
if self.headers.has_key(_interHeader):
authHeader = _interHeader
try:
info = self.headers[authHeader]
status = info['da-status']
handler = getattr(self, 'login_%s' % (status,), None)
if handler:
handler(info)
else:
raise Exception()
except Exception, e:
self.deferred.errback(failure.Failure(e))
def handleResponse(self, r):
pass
def login_success(self, info):
ticket = info['from-pp']
ticket = ticket[1:len(ticket)-1]
self.deferred.callback((LOGIN_SUCCESS, ticket))
def login_failed(self, info):
self.deferred.callback((LOGIN_FAILURE, unquote(info['cbtxt'])))
def login_redir(self, info):
self.deferred.callback((LOGIN_REDIRECT, self.headers['location'], self.authData))
class MSNProtocolError(Exception):
"""
This Exception is basically used for debugging
purposes, as the official MSN server should never
send anything _wrong_ and nobody in their right
mind would run their B{own} MSN server.
If it is raised by default command handlers
(handle_BLAH) the error will be logged.
"""
pass
class MSNCommandFailed(Exception):
"""
The server said that the command failed.
"""
def __init__(self, errorCode):
self.errorCode = errorCode
def __str__(self):
return ("Command failed: %s (error code %d)"
% (errorCodes[self.errorCode], self.errorCode))
class MSNMessage:
"""
I am the class used to represent an 'instant' message.
@ivar userHandle: The user handle (passport) of the sender
(this is only used when receiving a message)
@ivar screenName: The screen name of the sender (this is only used
when receiving a message)
@ivar message: The message
@ivar headers: The message headers
@type headers: dict
@ivar length: The message length (including headers and line endings)
@ivar ack: This variable is used to tell the server how to respond
once the message has been sent. If set to MESSAGE_ACK
(default) the server will respond with an ACK upon receiving
the message, if set to MESSAGE_NACK the server will respond
with a NACK upon failure to receive the message.
If set to MESSAGE_ACK_NONE the server will do nothing.
This is relevant for the return value of
SwitchboardClient.sendMessage (which will return
a Deferred if ack is set to either MESSAGE_ACK or MESSAGE_NACK
and will fire when the respective ACK or NACK is received).
If set to MESSAGE_ACK_NONE sendMessage will return None.
"""
MESSAGE_ACK = 'A'
MESSAGE_NACK = 'N'
MESSAGE_ACK_NONE = 'U'
ack = MESSAGE_ACK
def __init__(self, length=0, userHandle="", screenName="", message=""):
self.userHandle = userHandle
self.screenName = screenName
self.message = message
self.headers = {'MIME-Version' : '1.0', 'Content-Type' : 'text/plain'}
self.length = length
self.readPos = 0
def _calcMessageLen(self):
"""
used to calculte the number to send
as the message length when sending a message.
"""
return reduce(operator.add, [len(x[0]) + len(x[1]) + 4 for x in self.headers.items()]) + len(self.message) + 2
def setHeader(self, header, value):
""" set the desired header """
self.headers[header] = value
def getHeader(self, header):
"""
get the desired header value
@raise KeyError: if no such header exists.
"""
return self.headers[header]
def hasHeader(self, header):
""" check to see if the desired header exists """
return self.headers.has_key(header)
def getMessage(self):
""" return the message - not including headers """
return self.message
def setMessage(self, message):
""" set the message text """
self.message = message
class MSNContact:
"""
This class represents a contact (user).
@ivar userHandle: The contact's user handle (passport).
@ivar screenName: The contact's screen name.
@ivar groups: A list of all the group IDs which this
contact belongs to.
@ivar lists: An integer representing the sum of all lists
that this contact belongs to.
@ivar status: The contact's status code.
@type status: str if contact's status is known, None otherwise.
@ivar homePhone: The contact's home phone number.
@type homePhone: str if known, otherwise None.
@ivar workPhone: The contact's work phone number.
@type workPhone: str if known, otherwise None.
@ivar mobilePhone: The contact's mobile phone number.
@type mobilePhone: str if known, otherwise None.
@ivar hasPager: Whether or not this user has a mobile pager
(true=yes, false=no)
"""
def __init__(self, userHandle="", screenName="", lists=0, groups=[], status=None):
self.userHandle = userHandle
self.screenName = screenName
self.lists = lists
self.groups = [] # if applicable
self.status = status # current status
# phone details
self.homePhone = None
self.workPhone = None
self.mobilePhone = None
self.hasPager = None
def setPhone(self, phoneType, value):
"""
set phone numbers/values for this specific user.
for phoneType check the *_PHONE constants and HAS_PAGER
"""
t = phoneType.upper()
if t == HOME_PHONE:
self.homePhone = value
elif t == WORK_PHONE:
self.workPhone = value
elif t == MOBILE_PHONE:
self.mobilePhone = value
elif t == HAS_PAGER:
self.hasPager = value
else:
raise ValueError, "Invalid Phone Type"
def addToList(self, listType):
"""
Update the lists attribute to
reflect being part of the
given list.
"""
self.lists |= listType
def removeFromList(self, listType):
"""
Update the lists attribute to
reflect being removed from the
given list.
"""
self.lists ^= listType
class MSNContactList:
"""
This class represents a basic MSN contact list.
@ivar contacts: All contacts on my various lists
@type contacts: dict (mapping user handles to MSNContact objects)
@ivar version: The current contact list version (used for list syncing)
@ivar groups: a mapping of group ids to group names
(groups can only exist on the forward list)
@type groups: dict
B{Note}:
This is used only for storage and doesn't effect the
server's contact list.
"""
def __init__(self):
self.contacts = {}
self.version = 0
self.groups = {}
self.autoAdd = 0
self.privacy = 0
def _getContactsFromList(self, listType):
"""
Obtain all contacts which belong
to the given list type.
"""
return dict([(uH,obj) for uH,obj in self.contacts.items() if obj.lists & listType])
def addContact(self, contact):
"""
Add a contact
"""
self.contacts[contact.userHandle] = contact
def remContact(self, userHandle):
"""
Remove a contact
"""
try:
del self.contacts[userHandle]
except KeyError:
pass
def getContact(self, userHandle):
"""
Obtain the MSNContact object
associated with the given
userHandle.
@return: the MSNContact object if
the user exists, or None.
"""
try:
return self.contacts[userHandle]
except KeyError:
return None
def getBlockedContacts(self):
"""
Obtain all the contacts on my block list
"""
return self._getContactsFromList(BLOCK_LIST)
def getAuthorizedContacts(self):
"""
Obtain all the contacts on my auth list.
(These are contacts which I have verified
can view my state changes).
"""
return self._getContactsFromList(ALLOW_LIST)
def getReverseContacts(self):
"""
Get all contacts on my reverse list.
(These are contacts which have added me
to their forward list).
"""
return self._getContactsFromList(REVERSE_LIST)
def getContacts(self):
"""
Get all contacts on my forward list.
(These are the contacts which I have added
to my list).
"""
return self._getContactsFromList(FORWARD_LIST)
def setGroup(self, id, name):
"""
Keep a mapping from the given id
to the given name.
"""
self.groups[id] = name
def remGroup(self, id):
"""
Removed the stored group
mapping for the given id.
"""
try:
del self.groups[id]
except KeyError:
pass
for c in self.contacts:
if id in c.groups:
c.groups.remove(id)
class MSNEventBase(LineReceiver):
"""
This class provides support for handling / dispatching events and is the
base class of the three main client protocols (DispatchClient,
NotificationClient, SwitchboardClient)
"""
def __init__(self):
self.ids = {} # mapping of ids to Deferreds
self.currentID = 0
self.connected = 0
self.setLineMode()
self.currentMessage = None
def connectionLost(self, reason):
self.ids = {}
self.connected = 0
def connectionMade(self):
self.connected = 1
def _fireCallback(self, id, *args):
"""
Fire the callback for the given id
if one exists and return 1, else return false
"""
if self.ids.has_key(id):
self.ids[id][0].callback(args)
del self.ids[id]
return 1
return 0
def _nextTransactionID(self):
""" return a usable transaction ID """
self.currentID += 1
if self.currentID > 1000:
self.currentID = 1
return self.currentID
def _createIDMapping(self, data=None):
"""
return a unique transaction ID that is mapped internally to a
deferred .. also store arbitrary data if it is needed
"""
id = self._nextTransactionID()
d = Deferred()
self.ids[id] = (d, data)
return (id, d)
def checkMessage(self, message):
"""
process received messages to check for file invitations and
typing notifications and other control type messages
"""
raise NotImplementedError
def lineReceived(self, line):
if self.currentMessage:
self.currentMessage.readPos += len(line+CR+LF)
if line == "":
self.setRawMode()
if self.currentMessage.readPos == self.currentMessage.length:
self.rawDataReceived("") # :(
return
try:
header, value = line.split(':')
except ValueError:
raise MSNProtocolError, "Invalid Message Header"
self.currentMessage.setHeader(header, unquote(value).lstrip())
return
try:
cmd, params = line.split(' ', 1)
except ValueError:
raise MSNProtocolError, "Invalid Message, %s" % repr(line)
if len(cmd) != 3:
raise MSNProtocolError, "Invalid Command, %s" % repr(cmd)
if cmd.isdigit():
errorCode = int(cmd)
id = int(params.split()[0])
if id in self.ids:
self.ids[id][0].errback(MSNCommandFailed(errorCode))
del self.ids[id]
return
else: # we received an error which doesn't map to a sent command
self.gotError(errorCode)
return
handler = getattr(self, "handle_%s" % cmd.upper(), None)
if handler:
try:
handler(params.split())
except MSNProtocolError, why:
self.gotBadLine(line, why)
else:
self.handle_UNKNOWN(cmd, params.split())
def rawDataReceived(self, data):
extra = ""
self.currentMessage.readPos += len(data)
diff = self.currentMessage.readPos - self.currentMessage.length
if diff > 0:
self.currentMessage.message += data[:-diff]
extra = data[-diff:]
elif diff == 0:
self.currentMessage.message += data
else:
self.currentMessage += data
return
del self.currentMessage.readPos
m = self.currentMessage
self.currentMessage = None
self.setLineMode(extra)
if not self.checkMessage(m):
return
self.gotMessage(m)
### protocol command handlers - no need to override these.
def handle_MSG(self, params):
checkParamLen(len(params), 3, 'MSG')
try:
messageLen = int(params[2])
except ValueError:
raise MSNProtocolError, "Invalid Parameter for MSG length argument"
self.currentMessage = MSNMessage(length=messageLen, userHandle=params[0], screenName=unquote(params[1]))
def handle_UNKNOWN(self, cmd, params):
""" implement me in subclasses if you want to handle unknown events """
log.msg("Received unknown command (%s), params: %s" % (cmd, params))
### callbacks
def gotMessage(self, message):
"""
called when we receive a message - override in notification
and switchboard clients
"""
raise NotImplementedError
def gotBadLine(self, line, why):
""" called when a handler notifies me that this line is broken """
log.msg('Error in line: %s (%s)' % (line, why))
def gotError(self, errorCode):
"""
called when the server sends an error which is not in
response to a sent command (ie. it has no matching transaction ID)
"""
log.msg('Error %s' % (errorCodes[errorCode]))
class DispatchClient(MSNEventBase):
"""
This class provides support for clients connecting to the dispatch server
@ivar userHandle: your user handle (passport) needed before connecting.
"""
# eventually this may become an attribute of the
# factory.
userHandle = ""
def connectionMade(self):
MSNEventBase.connectionMade(self)
self.sendLine('VER %s %s' % (self._nextTransactionID(), MSN_PROTOCOL_VERSION))
### protocol command handlers ( there is no need to override these )
def handle_VER(self, params):
versions = params[1:]
if versions is None or ' '.join(versions) != MSN_PROTOCOL_VERSION:
self.transport.loseConnection()
raise MSNProtocolError, "Invalid version response"
id = self._nextTransactionID()
self.sendLine("CVR %s %s %s" % (id, MSN_CVR_STR, self.userHandle))
def handle_CVR(self, params):
self.sendLine("USR %s TWN I %s" % (self._nextTransactionID(), self.userHandle))
def handle_XFR(self, params):
if len(params) < 4:
raise MSNProtocolError, "Invalid number of parameters for XFR"
id, refType, addr = params[:3]
# was addr a host:port pair?
try:
host, port = addr.split(':')
except ValueError:
host = addr
port = MSN_PORT
if refType == "NS":
self.gotNotificationReferral(host, int(port))
### callbacks
def gotNotificationReferral(self, host, port):
"""
called when we get a referral to the notification server.
@param host: the notification server's hostname
@param port: the port to connect to
"""
pass
class NotificationClient(MSNEventBase):
"""
This class provides support for clients connecting
to the notification server.
"""
factory = None # sssh pychecker
def __init__(self, currentID=0):
MSNEventBase.__init__(self)
self.currentID = currentID
self._state = ['DISCONNECTED', {}]
def _setState(self, state):
self._state[0] = state
def _getState(self):
return self._state[0]
def _getStateData(self, key):
return self._state[1][key]
def _setStateData(self, key, value):
self._state[1][key] = value
def _remStateData(self, *args):
for key in args:
del self._state[1][key]
def connectionMade(self):
MSNEventBase.connectionMade(self)
self._setState('CONNECTED')
self.sendLine("VER %s %s" % (self._nextTransactionID(), MSN_PROTOCOL_VERSION))
def connectionLost(self, reason):
self._setState('DISCONNECTED')
self._state[1] = {}
MSNEventBase.connectionLost(self, reason)
def checkMessage(self, message):
""" hook used for detecting specific notification messages """
cTypes = [s.lstrip() for s in message.getHeader('Content-Type').split(';')]
if 'text/x-msmsgsprofile' in cTypes:
self.gotProfile(message)
return 0
return 1
### protocol command handlers - no need to override these
def handle_VER(self, params):
versions = params[1:]
if versions is None or ' '.join(versions) != MSN_PROTOCOL_VERSION:
self.transport.loseConnection()
raise MSNProtocolError, "Invalid version response"
self.sendLine("CVR %s %s %s" % (self._nextTransactionID(), MSN_CVR_STR, self.factory.userHandle))
def handle_CVR(self, params):
self.sendLine("USR %s TWN I %s" % (self._nextTransactionID(), self.factory.userHandle))
def handle_USR(self, params):
if len(params) != 4 and len(params) != 6:
raise MSNProtocolError, "Invalid Number of Parameters for USR"
mechanism = params[1]
if mechanism == "OK":
self.loggedIn(params[2], unquote(params[3]), int(params[4]))
elif params[2].upper() == "S":
# we need to obtain auth from a passport server
f = self.factory
d = _login(f.userHandle, f.password, f.passportServer, authData=params[3])
d.addCallback(self._passportLogin)
d.addErrback(self._passportError)
def _passportLogin(self, result):
if result[0] == LOGIN_REDIRECT:
d = _login(self.factory.userHandle, self.factory.password,
result[1], cached=1, authData=result[2])
d.addCallback(self._passportLogin)
d.addErrback(self._passportError)
elif result[0] == LOGIN_SUCCESS:
self.sendLine("USR %s TWN S %s" % (self._nextTransactionID(), result[1]))
elif result[0] == LOGIN_FAILURE:
self.loginFailure(result[1])
def _passportError(self, failure):
self.loginFailure("Exception while authenticating: %s" % failure)
def handle_CHG(self, params):
checkParamLen(len(params), 3, 'CHG')
id = int(params[0])
if not self._fireCallback(id, params[1]):
self.statusChanged(params[1])
def handle_ILN(self, params):
checkParamLen(len(params), 5, 'ILN')
self.gotContactStatus(params[1], params[2], unquote(params[3]))
def handle_CHL(self, params):
checkParamLen(len(params), 2, 'CHL')
self.sendLine("QRY %s [email protected] 32" % self._nextTransactionID())
self.transport.write(md5.md5(params[1] + MSN_CHALLENGE_STR).hexdigest())
def handle_QRY(self, params):
pass
def handle_NLN(self, params):
checkParamLen(len(params), 4, 'NLN')
self.contactStatusChanged(params[0], params[1], unquote(params[2]))
def handle_FLN(self, params):
checkParamLen(len(params), 1, 'FLN')
self.contactOffline(params[0])
def handle_LST(self, params):
# support no longer exists for manually
# requesting lists - why do I feel cleaner now?
if self._getState() != 'SYNC':
return
contact = MSNContact(userHandle=params[0], screenName=unquote(params[1]),
lists=int(params[2]))
if contact.lists & FORWARD_LIST:
contact.groups.extend(map(int, params[3].split(',')))
self._getStateData('list').addContact(contact)
self._setStateData('last_contact', contact)
sofar = self._getStateData('lst_sofar') + 1
if sofar == self._getStateData('lst_reply'):
# this is the best place to determine that
# a syn realy has finished - msn _may_ send
# BPR information for the last contact
# which is unfortunate because it means
# that the real end of a syn is non-deterministic.
# to handle this we'll keep 'last_contact' hanging
# around in the state data and update it if we need
# to later.
self._setState('SESSION')
contacts = self._getStateData('list')
phone = self._getStateData('phone')
id = self._getStateData('synid')
self._remStateData('lst_reply', 'lsg_reply', 'lst_sofar', 'phone', 'synid', 'list')
self._fireCallback(id, contacts, phone)
else:
self._setStateData('lst_sofar',sofar)
def handle_BLP(self, params):
# check to see if this is in response to a SYN
if self._getState() == 'SYNC':
self._getStateData('list').privacy = listCodeToID[params[0].lower()]
else:
id = int(params[0])
self._fireCallback(id, int(params[1]), listCodeToID[params[2].lower()])
def handle_GTC(self, params):
# check to see if this is in response to a SYN
if self._getState() == 'SYNC':
if params[0].lower() == "a":
self._getStateData('list').autoAdd = 0
elif params[0].lower() == "n":
self._getStateData('list').autoAdd = 1
else:
raise MSNProtocolError, "Invalid Paramater for GTC" # debug
else:
id = int(params[0])
if params[1].lower() == "a":
self._fireCallback(id, 0)
elif params[1].lower() == "n":
self._fireCallback(id, 1)
else:
raise MSNProtocolError, "Invalid Paramater for GTC" # debug
def handle_SYN(self, params):
id = int(params[0])
if len(params) == 2:
self._setState('SESSION')
self._fireCallback(id, None, None)
else:
contacts = MSNContactList()
contacts.version = int(params[1])
self._setStateData('list', contacts)
self._setStateData('lst_reply', int(params[2]))
self._setStateData('lsg_reply', int(params[3]))
self._setStateData('lst_sofar', 0)
self._setStateData('phone', [])
def handle_LSG(self, params):
if self._getState() == 'SYNC':
self._getStateData('list').groups[int(params[0])] = unquote(params[1])
# Please see the comment above the requestListGroups / requestList methods
# regarding support for this
#
#else:
# self._getStateData('groups').append((int(params[4]), unquote(params[5])))
# if params[3] == params[4]: # this was the last group
# self._fireCallback(int(params[0]), self._getStateData('groups'), int(params[1]))
# self._remStateData('groups')
def handle_PRP(self, params):
if self._getState() == 'SYNC':
self._getStateData('phone').append((params[0], unquote(params[1])))
else:
self._fireCallback(int(params[0]), int(params[1]), unquote(params[3]))
def handle_BPR(self, params):
numParams = len(params)
if numParams == 2: # part of a syn
self._getStateData('last_contact').setPhone(params[0], unquote(params[1]))
elif numParams == 4:
self.gotPhoneNumber(int(params[0]), params[1], params[2], unquote(params[3]))
def handle_ADG(self, params):
checkParamLen(len(params), 5, 'ADG')
id = int(params[0])
if not self._fireCallback(id, int(params[1]), unquote(params[2]), int(params[3])):
raise MSNProtocolError, "ADG response does not match up to a request" # debug
def handle_RMG(self, params):
checkParamLen(len(params), 3, 'RMG')
id = int(params[0])
if not self._fireCallback(id, int(params[1]), int(params[2])):
raise MSNProtocolError, "RMG response does not match up to a request" # debug
def handle_REG(self, params):
checkParamLen(len(params), 5, 'REG')
id = int(params[0])
if not self._fireCallback(id, int(params[1]), int(params[2]), unquote(params[3])):
raise MSNProtocolError, "REG response does not match up to a request" # debug
def handle_ADD(self, params):
numParams = len(params)
if numParams < 5 or params[1].upper() not in ('AL','BL','RL','FL'):
raise MSNProtocolError, "Invalid Paramaters for ADD" # debug
id = int(params[0])
listType = params[1].lower()
listVer = int(params[2])
userHandle = params[3]
groupID = None
if numParams == 6: # they sent a group id
if params[1].upper() != "FL":
raise MSNProtocolError, "Only forward list can contain groups" # debug
groupID = int(params[5])
if not self._fireCallback(id, listCodeToID[listType], userHandle, listVer, groupID):
self.userAddedMe(userHandle, unquote(params[4]), listVer)
def handle_REM(self, params):
numParams = len(params)
if numParams < 4 or params[1].upper() not in ('AL','BL','FL','RL'):
raise MSNProtocolError, "Invalid Paramaters for REM" # debug
id = int(params[0])
listType = params[1].lower()
listVer = int(params[2])
userHandle = params[3]
groupID = None
if numParams == 5:
if params[1] != "FL":
raise MSNProtocolError, "Only forward list can contain groups" # debug
groupID = int(params[4])
if not self._fireCallback(id, listCodeToID[listType], userHandle, listVer, groupID):
if listType.upper() == "RL":
self.userRemovedMe(userHandle, listVer)
def handle_REA(self, params):
checkParamLen(len(params), 4, 'REA')
id = int(params[0])
self._fireCallback(id, int(params[1]), unquote(params[3]))
def handle_XFR(self, params):
checkParamLen(len(params), 5, 'XFR')
id = int(params[0])
# check to see if they sent a host/port pair
try:
host, port = params[2].split(':')
except ValueError:
host = params[2]
port = MSN_PORT
if not self._fireCallback(id, host, int(port), params[4]):
raise MSNProtocolError, "Got XFR (referral) that I didn't ask for .. should this happen?" # debug
def handle_RNG(self, params):
checkParamLen(len(params), 6, 'RNG')
# check for host:port pair
try:
host, port = params[1].split(":")
port = int(port)
except ValueError:
host = params[1]
port = MSN_PORT
self.gotSwitchboardInvitation(int(params[0]), host, port, params[3], params[4],
unquote(params[5]))
def handle_OUT(self, params):
checkParamLen(len(params), 1, 'OUT')
if params[0] == "OTH":
self.multipleLogin()
elif params[0] == "SSD":
self.serverGoingDown()
else:
raise MSNProtocolError, "Invalid Parameters received for OUT" # debug
# callbacks
def loggedIn(self, userHandle, screenName, verified):
"""
Called when the client has logged in.
The default behaviour of this method is to
update the factory with our screenName and
to sync the contact list (factory.contacts).
When this is complete self.listSynchronized
will be called.
@param userHandle: our userHandle
@param screenName: our screenName
@param verified: 1 if our passport has been (verified), 0 if not.
(i'm not sure of the significace of this)
@type verified: int
"""
self.factory.screenName = screenName
if not self.factory.contacts:
listVersion = 0
else:
listVersion = self.factory.contacts.version
self.syncList(listVersion).addCallback(self.listSynchronized)
def loginFailure(self, message):
"""
Called when the client fails to login.
@param message: a message indicating the problem that was encountered
"""
pass
def gotProfile(self, message):
"""
Called after logging in when the server sends an initial
message with MSN/passport specific profile information
such as country, number of kids, etc.
Check the message headers for the specific values.
@param message: The profile message
"""
pass
def listSynchronized(self, *args):
"""
Lists are now synchronized by default upon logging in, this
method is called after the synchronization has finished
and the factory now has the up-to-date contacts.
"""
pass
def statusChanged(self, statusCode):
"""
Called when our status changes and it isn't in response to
a client command. By default we will update the status
attribute of the factory.
@param statusCode: 3-letter status code
"""
self.factory.status = statusCode
def gotContactStatus(self, statusCode, userHandle, screenName):
"""
Called after loggin in when the server sends status of online contacts.
By default we will update the status attribute of the contact stored
on the factory.
@param statusCode: 3-letter status code
@param userHandle: the contact's user handle (passport)
@param screenName: the contact's screen name
"""
self.factory.contacts.getContact(userHandle).status = statusCode
def contactStatusChanged(self, statusCode, userHandle, screenName):
"""
Called when we're notified that a contact's status has changed.
By default we will update the status attribute of the contact
stored on the factory.
@param statusCode: 3-letter status code
@param userHandle: the contact's user handle (passport)
@param screenName: the contact's screen name
"""
self.factory.contacts.getContact(userHandle).status = statusCode
def contactOffline(self, userHandle):
"""
Called when a contact goes offline. By default this method
will update the status attribute of the contact stored
on the factory.
@param userHandle: the contact's user handle
"""
self.factory.contacts.getContact(userHandle).status = STATUS_OFFLINE
def gotPhoneNumber(self, listVersion, userHandle, phoneType, number):
"""
Called when the server sends us phone details about
a specific user (for example after a user is added
the server will send their status, phone details etc.
By default we will update the list version for the
factory's contact list and update the phone details
for the specific user.
@param listVersion: the new list version
@param userHandle: the contact's user handle (passport)
@param phoneType: the specific phoneType
(*_PHONE constants or HAS_PAGER)
@param number: the value/phone number.
"""
self.factory.contacts.version = listVersion
self.factory.contacts.getContact(userHandle).setPhone(phoneType, number)
def userAddedMe(self, userHandle, screenName, listVersion):
"""
Called when a user adds me to their list. (ie. they have been added to
the reverse list. By default this method will update the version of
the factory's contact list -- that is, if the contact already exists
it will update the associated lists attribute, otherwise it will create
a new MSNContact object and store it.
@param userHandle: the userHandle of the user
@param screenName: the screen name of the user
@param listVersion: the new list version
@type listVersion: int
"""
self.factory.contacts.version = listVersion
c = self.factory.contacts.getContact(userHandle)
if not c:
c = MSNContact(userHandle=userHandle, screenName=screenName)
self.factory.contacts.addContact(c)
c.addToList(REVERSE_LIST)
def userRemovedMe(self, userHandle, listVersion):
"""
Called when a user removes us from their contact list
(they are no longer on our reverseContacts list.
By default this method will update the version of
the factory's contact list -- that is, the user will
be removed from the reverse list and if they are no longer
part of any lists they will be removed from the contact
list entirely.
@param userHandle: the contact's user handle (passport)
@param listVersion: the new list version
"""
self.factory.contacts.version = listVersion
c = self.factory.contacts.getContact(userHandle)
c.removeFromList(REVERSE_LIST)
if c.lists == 0:
self.factory.contacts.remContact(c.userHandle)
def gotSwitchboardInvitation(self, sessionID, host, port,
key, userHandle, screenName):
"""
Called when we get an invitation to a switchboard server.
This happens when a user requests a chat session with us.
@param sessionID: session ID number, must be remembered for logging in
@param host: the hostname of the switchboard server
@param port: the port to connect to
@param key: used for authorization when connecting
@param userHandle: the user handle of the person who invited us
@param screenName: the screen name of the person who invited us
"""
pass
def multipleLogin(self):
"""
Called when the server says there has been another login
under our account, the server should disconnect us right away.
"""
pass
def serverGoingDown(self):
"""
Called when the server has notified us that it is going down for
maintenance.
"""
pass
# api calls
def changeStatus(self, status):
"""
Change my current status. This method will add
a default callback to the returned Deferred
which will update the status attribute of the
factory.
@param status: 3-letter status code (as defined by
the STATUS_* constants)
@return: A Deferred, the callback of which will be
fired when the server confirms the change
of status. The callback argument will be
a tuple with the new status code as the
only element.
"""
id, d = self._createIDMapping()
self.sendLine("CHG %s %s" % (id, status))
def _cb(r):
self.factory.status = r[0]
return r
return d.addCallback(_cb)
# I am no longer supporting the process of manually requesting
# lists or list groups -- as far as I can see this has no use
# if lists are synchronized and updated correctly, which they
# should be. If someone has a specific justified need for this
# then please contact me and i'll re-enable/fix support for it.
#def requestList(self, listType):
# """
# request the desired list type
#
# @param listType: (as defined by the *_LIST constants)
# @return: A Deferred, the callback of which will be
# fired when the list has been retrieved.
# The callback argument will be a tuple with
# the only element being a list of MSNContact
# objects.
# """
# # this doesn't need to ever be used if syncing of the lists takes place
# # i.e. please don't use it!
# warnings.warn("Please do not use this method - use the list syncing process instead")
# id, d = self._createIDMapping()
# self.sendLine("LST %s %s" % (id, listIDToCode[listType].upper()))
# self._setStateData('list',[])
# return d
def setPrivacyMode(self, privLevel):
"""
Set my privacy mode on the server.
B{Note}:
This only keeps the current privacy setting on
the server for later retrieval, it does not
effect the way the server works at all.
@param privLevel: This parameter can be true, in which
case the server will keep the state as
'al' which the official client interprets
as -> allow messages from only users on
the allow list. Alternatively it can be
false, in which case the server will keep
the state as 'bl' which the official client
interprets as -> allow messages from all
users except those on the block list.
@return: A Deferred, the callback of which will be fired when
the server replies with the new privacy setting.
The callback argument will be a tuple, the 2 elements
of which being the list version and either 'al'
or 'bl' (the new privacy setting).
"""
id, d = self._createIDMapping()
if privLevel:
self.sendLine("BLP %s AL" % id)
else:
self.sendLine("BLP %s BL" % id)
return d
def syncList(self, version):
"""
Used for keeping an up-to-date contact list.
A callback is added to the returned Deferred
that updates the contact list on the factory
and also sets my state to STATUS_ONLINE.
B{Note}:
This is called automatically upon signing
in using the version attribute of
factory.contacts, so you may want to persist
this object accordingly. Because of this there
is no real need to ever call this method
directly.
@param version: The current known list version
@return: A Deferred, the callback of which will be
fired when the server sends an adequate reply.
The callback argument will be a tuple with two
elements, the new list (MSNContactList) and
your current state (a dictionary). If the version
you sent _was_ the latest list version, both elements
will be None. To just request the list send a version of 0.
"""
self._setState('SYNC')
id, d = self._createIDMapping(data=str(version))
self._setStateData('synid',id)
self.sendLine("SYN %s %s" % (id, version))
def _cb(r):
self.changeStatus(STATUS_ONLINE)
if r[0] is not None:
self.factory.contacts = r[0]
return r
return d.addCallback(_cb)
# I am no longer supporting the process of manually requesting
# lists or list groups -- as far as I can see this has no use
# if lists are synchronized and updated correctly, which they
# should be. If someone has a specific justified need for this
# then please contact me and i'll re-enable/fix support for it.
#def requestListGroups(self):
# """
# Request (forward) list groups.
#
# @return: A Deferred, the callback for which will be called
# when the server responds with the list groups.
# The callback argument will be a tuple with two elements,
# a dictionary mapping group IDs to group names and the
# current list version.
# """
#
# # this doesn't need to be used if syncing of the lists takes place (which it SHOULD!)
# # i.e. please don't use it!
# warnings.warn("Please do not use this method - use the list syncing process instead")
# id, d = self._createIDMapping()
# self.sendLine("LSG %s" % id)
# self._setStateData('groups',{})
# return d
def setPhoneDetails(self, phoneType, value):
"""
Set/change my phone numbers stored on the server.
@param phoneType: phoneType can be one of the following
constants - HOME_PHONE, WORK_PHONE,
MOBILE_PHONE, HAS_PAGER.
These are pretty self-explanatory, except
maybe HAS_PAGER which refers to whether or
not you have a pager.
@param value: for all of the *_PHONE constants the value is a
phone number (str), for HAS_PAGER accepted values
are 'Y' (for yes) and 'N' (for no).
@return: A Deferred, the callback for which will be fired when
the server confirms the change has been made. The
callback argument will be a tuple with 2 elements, the
first being the new list version (int) and the second
being the new phone number value (str).
"""
# XXX: Add a default callback which updates
# factory.contacts.version and the relevant phone
# number
id, d = self._createIDMapping()
self.sendLine("PRP %s %s %s" % (id, phoneType, quote(value)))
return d
def addListGroup(self, name):
"""
Used to create a new list group.
A default callback is added to the
returned Deferred which updates the
contacts attribute of the factory.
@param name: The desired name of the new group.
@return: A Deferred, the callbacck for which will be called
when the server clarifies that the new group has been
created. The callback argument will be a tuple with 3
elements: the new list version (int), the new group name
(str) and the new group ID (int).
"""
id, d = self._createIDMapping()
self.sendLine("ADG %s %s 0" % (id, quote(name)))
def _cb(r):
self.factory.contacts.version = r[0]
self.factory.contacts.setGroup(r[1], r[2])
return r
return d.addCallback(_cb)
def remListGroup(self, groupID):
"""
Used to remove a list group.
A default callback is added to the
returned Deferred which updates the
contacts attribute of the factory.
@param groupID: the ID of the desired group to be removed.
@return: A Deferred, the callback for which will be called when
the server clarifies the deletion of the group.
The callback argument will be a tuple with 2 elements:
the new list version (int) and the group ID (int) of
the removed group.
"""
id, d = self._createIDMapping()
self.sendLine("RMG %s %s" % (id, groupID))
def _cb(r):
self.factory.contacts.version = r[0]
self.factory.contacts.remGroup(r[1])
return r
return d.addCallback(_cb)
def renameListGroup(self, groupID, newName):
"""
Used to rename an existing list group.
A default callback is added to the returned
Deferred which updates the contacts attribute
of the factory.
@param groupID: the ID of the desired group to rename.
@param newName: the desired new name for the group.
@return: A Deferred, the callback for which will be called
when the server clarifies the renaming.
The callback argument will be a tuple of 3 elements,
the new list version (int), the group id (int) and
the new group name (str).
"""
id, d = self._createIDMapping()
self.sendLine("REG %s %s %s 0" % (id, groupID, quote(newName)))
def _cb(r):
self.factory.contacts.version = r[0]
self.factory.contacts.setGroup(r[1], r[2])
return r
return d.addCallback(_cb)
def addContact(self, listType, userHandle, groupID=0):
"""
Used to add a contact to the desired list.
A default callback is added to the returned
Deferred which updates the contacts attribute of
the factory with the new contact information.
If you are adding a contact to the forward list
and you want to associate this contact with multiple
groups then you will need to call this method for each
group you would like to add them to, changing the groupID
parameter. The default callback will take care of updating
the group information on the factory's contact list.
@param listType: (as defined by the *_LIST constants)
@param userHandle: the user handle (passport) of the contact
that is being added
@param groupID: the group ID for which to associate this contact
with. (default 0 - default group). Groups are only
valid for FORWARD_LIST.
@return: A Deferred, the callback for which will be called when
the server has clarified that the user has been added.
The callback argument will be a tuple with 4 elements:
the list type, the contact's user handle, the new list
version, and the group id (if relevant, otherwise it
will be None)
"""
id, d = self._createIDMapping()
listType = listIDToCode[listType].upper()
if listType == "FL":
self.sendLine("ADD %s FL %s %s %s" % (id, userHandle, userHandle, groupID))
else:
self.sendLine("ADD %s %s %s %s" % (id, listType, userHandle, userHandle))
def _cb(r):
self.factory.contacts.version = r[2]
c = self.factory.contacts.getContact(r[1])
if not c:
c = MSNContact(userHandle=r[1])
if r[3]:
c.groups.append(r[3])
c.addToList(r[0])
return r
return d.addCallback(_cb)
def remContact(self, listType, userHandle, groupID=0):
"""
Used to remove a contact from the desired list.
A default callback is added to the returned deferred
which updates the contacts attribute of the factory
to reflect the new contact information. If you are
removing from the forward list then you will need to
supply a groupID, if the contact is in more than one
group then they will only be removed from this group
and not the entire forward list, but if this is their
only group they will be removed from the whole list.
@param listType: (as defined by the *_LIST constants)
@param userHandle: the user handle (passport) of the
contact being removed
@param groupID: the ID of the group to which this contact
belongs (only relevant for FORWARD_LIST,
default is 0)
@return: A Deferred, the callback for which will be called when
the server has clarified that the user has been removed.
The callback argument will be a tuple of 4 elements:
the list type, the contact's user handle, the new list
version, and the group id (if relevant, otherwise it will
be None)
"""
id, d = self._createIDMapping()
listType = listIDToCode[listType].upper()
if listType == "FL":
self.sendLine("REM %s FL %s %s" % (id, userHandle, groupID))
else:
self.sendLine("REM %s %s %s" % (id, listType, userHandle))
def _cb(r):
l = self.factory.contacts
l.version = r[2]
c = l.getContact(r[1])
group = r[3]
shouldRemove = 1
if group: # they may not have been removed from the list
c.groups.remove(group)
if c.groups:
shouldRemove = 0
if shouldRemove:
c.removeFromList(r[0])
if c.lists == 0:
l.remContact(c.userHandle)
return r
return d.addCallback(_cb)
def changeScreenName(self, newName):
"""
Used to change your current screen name.
A default callback is added to the returned
Deferred which updates the screenName attribute
of the factory and also updates the contact list
version.
@param newName: the new screen name
@return: A Deferred, the callback for which will be called
when the server sends an adequate reply.
The callback argument will be a tuple of 2 elements:
the new list version and the new screen name.
"""
id, d = self._createIDMapping()
self.sendLine("REA %s %s %s" % (id, self.factory.userHandle, quote(newName)))
def _cb(r):
self.factory.contacts.version = r[0]
self.factory.screenName = r[1]
return r
return d.addCallback(_cb)
def requestSwitchboardServer(self):
"""
Used to request a switchboard server to use for conversations.
@return: A Deferred, the callback for which will be called when
the server responds with the switchboard information.
The callback argument will be a tuple with 3 elements:
the host of the switchboard server, the port and a key
used for logging in.
"""
id, d = self._createIDMapping()
self.sendLine("XFR %s SB" % id)
return d
def logOut(self):
"""
Used to log out of the notification server.
After running the method the server is expected
to close the connection.
"""
self.sendLine("OUT")
class NotificationFactory(ClientFactory):
"""
Factory for the NotificationClient protocol.
This is basically responsible for keeping
the state of the client and thus should be used
in a 1:1 situation with clients.
@ivar contacts: An MSNContactList instance reflecting
the current contact list -- this is
generally kept up to date by the default
command handlers.
@ivar userHandle: The client's userHandle, this is expected
to be set by the client and is used by the
protocol (for logging in etc).
@ivar screenName: The client's current screen-name -- this is
generally kept up to date by the default
command handlers.
@ivar password: The client's password -- this is (obviously)
expected to be set by the client.
@ivar passportServer: This must point to an msn passport server
(the whole URL is required)
@ivar status: The status of the client -- this is generally kept
up to date by the default command handlers
"""
contacts = None
userHandle = ''
screenName = ''
password = ''
passportServer = 'https://nexus.passport.com/rdr/pprdr.asp'
status = 'FLN'
protocol = NotificationClient
# XXX: A lot of the state currently kept in
# instances of SwitchboardClient is likely to
# be moved into a factory at some stage in the
# future
class SwitchboardClient(MSNEventBase):
"""
This class provides support for clients connecting to a switchboard server.
Switchboard servers are used for conversations with other people
on the MSN network. This means that the number of conversations at
any given time will be directly proportional to the number of
connections to varioius switchboard servers.
MSN makes no distinction between single and group conversations,
so any number of users may be invited to join a specific conversation
taking place on a switchboard server.
@ivar key: authorization key, obtained when receiving
invitation / requesting switchboard server.
@ivar userHandle: your user handle (passport)
@ivar sessionID: unique session ID, used if you are replying
to a switchboard invitation
@ivar reply: set this to 1 in connectionMade or before to signifiy
that you are replying to a switchboard invitation.
"""
key = 0
userHandle = ""
sessionID = ""
reply = 0
_iCookie = 0
def __init__(self):
MSNEventBase.__init__(self)
self.pendingUsers = {}
self.cookies = {'iCookies' : {}, 'external' : {}} # will maybe be moved to a factory in the future
def connectionMade(self):
MSNEventBase.connectionMade(self)
print 'sending initial stuff'
self._sendInit()
def connectionLost(self, reason):
self.cookies['iCookies'] = {}
self.cookies['external'] = {}
MSNEventBase.connectionLost(self, reason)
def _sendInit(self):
"""
send initial data based on whether we are replying to an invitation
or starting one.
"""
id = self._nextTransactionID()
if not self.reply:
self.sendLine("USR %s %s %s" % (id, self.userHandle, self.key))
else:
self.sendLine("ANS %s %s %s %s" % (id, self.userHandle, self.key, self.sessionID))
def _newInvitationCookie(self):
self._iCookie += 1
if self._iCookie > 1000:
self._iCookie = 1
return self._iCookie
def _checkTyping(self, message, cTypes):
""" helper method for checkMessage """
if 'text/x-msmsgscontrol' in cTypes and message.hasHeader('TypingUser'):
self.userTyping(message)
return 1
def _checkFileInvitation(self, message, info):
""" helper method for checkMessage """
guid = info.get('Application-GUID', '').lower()
name = info.get('Application-Name', '').lower()
# Both fields are required, but we'll let some lazy clients get away
# with only sending a name, if it is easy for us to recognize the
# name (the name is localized, so this check might fail for lazy,
# non-english clients, but I'm not about to include "file transfer"
# in 80 different languages here).
if name != "file transfer" and guid != classNameToGUID["file transfer"]:
return 0
try:
cookie = int(info['Invitation-Cookie'])
fileName = info['Application-File']
fileSize = int(info['Application-FileSize'])
except KeyError:
log.msg('Received munged file transfer request ... ignoring.')
return 0
self.gotSendRequest(fileName, fileSize, cookie, message)
return 1
def _checkFileResponse(self, message, info):
""" helper method for checkMessage """
try:
cmd = info['Invitation-Command'].upper()
cookie = int(info['Invitation-Cookie'])
except KeyError:
return 0
accept = (cmd == 'ACCEPT') and 1 or 0
requested = self.cookies['iCookies'].get(cookie)
if not requested:
return 1
requested[0].callback((accept, cookie, info))
del self.cookies['iCookies'][cookie]
return 1
def _checkFileInfo(self, message, info):
""" helper method for checkMessage """
try:
ip = info['IP-Address']
iCookie = int(info['Invitation-Cookie'])
aCookie = int(info['AuthCookie'])
cmd = info['Invitation-Command'].upper()
port = int(info['Port'])
except KeyError:
return 0
accept = (cmd == 'ACCEPT') and 1 or 0
requested = self.cookies['external'].get(iCookie)
if not requested:
return 1 # we didn't ask for this
requested[0].callback((accept, ip, port, aCookie, info))
del self.cookies['external'][iCookie]
return 1
def checkMessage(self, message):
"""
hook for detecting any notification type messages
(e.g. file transfer)
"""
cTypes = [s.lstrip() for s in message.getHeader('Content-Type').split(';')]
if self._checkTyping(message, cTypes):
return 0
if 'text/x-msmsgsinvite' in cTypes:
# header like info is sent as part of the message body.
info = {}
for line in message.message.split('\r\n'):
try:
key, val = line.split(':')
info[key] = val.lstrip()
except ValueError:
continue
if self._checkFileInvitation(message, info) or self._checkFileInfo(message, info) or self._checkFileResponse(message, info):
return 0
elif 'text/x-clientcaps' in cTypes:
# do something with capabilities
return 0
return 1
# negotiation
def handle_USR(self, params):
checkParamLen(len(params), 4, 'USR')
if params[1] == "OK":
self.loggedIn()
# invite a user
def handle_CAL(self, params):
checkParamLen(len(params), 3, 'CAL')
id = int(params[0])
if params[1].upper() == "RINGING":
self._fireCallback(id, int(params[2])) # session ID as parameter
# user joined
def handle_JOI(self, params):
checkParamLen(len(params), 2, 'JOI')
self.userJoined(params[0], unquote(params[1]))
# users participating in the current chat
def handle_IRO(self, params):
checkParamLen(len(params), 5, 'IRO')
self.pendingUsers[params[3]] = unquote(params[4])
if params[1] == params[2]:
self.gotChattingUsers(self.pendingUsers)
self.pendingUsers = {}
# finished listing users
def handle_ANS(self, params):
checkParamLen(len(params), 2, 'ANS')
if params[1] == "OK":
self.loggedIn()
def handle_ACK(self, params):
checkParamLen(len(params), 1, 'ACK')
self._fireCallback(int(params[0]), None)
def handle_NAK(self, params):
checkParamLen(len(params), 1, 'NAK')
self._fireCallback(int(params[0]), None)
def handle_BYE(self, params):
#checkParamLen(len(params), 1, 'BYE') # i've seen more than 1 param passed to this
self.userLeft(params[0])
# callbacks
def loggedIn(self):
"""
called when all login details have been negotiated.
Messages can now be sent, or new users invited.
"""
pass
def gotChattingUsers(self, users):
"""
called after connecting to an existing chat session.
@param users: A dict mapping user handles to screen names
(current users taking part in the conversation)
"""
pass
def userJoined(self, userHandle, screenName):
"""
called when a user has joined the conversation.
@param userHandle: the user handle (passport) of the user
@param screenName: the screen name of the user
"""
pass
def userLeft(self, userHandle):
"""
called when a user has left the conversation.
@param userHandle: the user handle (passport) of the user.
"""
pass
def gotMessage(self, message):
"""
called when we receive a message.
@param message: the associated MSNMessage object
"""
pass
def userTyping(self, message):
"""
called when we receive the special type of message notifying
us that a user is typing a message.
@param message: the associated MSNMessage object
"""
pass
def gotSendRequest(self, fileName, fileSize, iCookie, message):
"""
called when a contact is trying to send us a file.
To accept or reject this transfer see the
fileInvitationReply method.
@param fileName: the name of the file
@param fileSize: the size of the file
@param iCookie: the invitation cookie, used so the client can
match up your reply with this request.
@param message: the MSNMessage object which brought about this
invitation (it may contain more information)
"""
pass
# api calls
def inviteUser(self, userHandle):
"""
used to invite a user to the current switchboard server.
@param userHandle: the user handle (passport) of the desired user.
@return: A Deferred, the callback for which will be called
when the server notifies us that the user has indeed
been invited. The callback argument will be a tuple
with 1 element, the sessionID given to the invited user.
I'm not sure if this is useful or not.
"""
id, d = self._createIDMapping()
self.sendLine("CAL %s %s" % (id, userHandle))
return d
def sendMessage(self, message):
"""
used to send a message.
@param message: the corresponding MSNMessage object.
@return: Depending on the value of message.ack.
If set to MSNMessage.MESSAGE_ACK or
MSNMessage.MESSAGE_NACK a Deferred will be returned,
the callback for which will be fired when an ACK or
NACK is received - the callback argument will be
(None,). If set to MSNMessage.MESSAGE_ACK_NONE then
the return value is None.
"""
if message.ack not in ('A','N'):
id, d = self._nextTransactionID(), None
else:
id, d = self._createIDMapping()
if message.length == 0:
message.length = message._calcMessageLen()
self.sendLine("MSG %s %s %s" % (id, message.ack, message.length))
# apparently order matters with at least MIME-Version and Content-Type
self.sendLine('MIME-Version: %s' % message.getHeader('MIME-Version'))
self.sendLine('Content-Type: %s' % message.getHeader('Content-Type'))
# send the rest of the headers
for header in [h for h in message.headers.items() if h[0].lower() not in ('mime-version','content-type')]:
self.sendLine("%s: %s" % (header[0], header[1]))
self.transport.write(CR+LF)
self.transport.write(message.message)
return d
def sendTypingNotification(self):
"""
used to send a typing notification. Upon receiving this
message the official client will display a 'user is typing'
message to all other users in the chat session for 10 seconds.
The official client sends one of these every 5 seconds (I think)
as long as you continue to type.
"""
m = MSNMessage()
m.ack = m.MESSAGE_ACK_NONE
m.setHeader('Content-Type', 'text/x-msmsgscontrol')
m.setHeader('TypingUser', self.userHandle)
m.message = "\r\n"
self.sendMessage(m)
def sendFileInvitation(self, fileName, fileSize):
"""
send an notification that we want to send a file.
@param fileName: the file name
@param fileSize: the file size
@return: A Deferred, the callback of which will be fired
when the user responds to this invitation with an
appropriate message. The callback argument will be
a tuple with 3 elements, the first being 1 or 0
depending on whether they accepted the transfer
(1=yes, 0=no), the second being an invitation cookie
to identify your follow-up responses and the third being
the message 'info' which is a dict of information they
sent in their reply (this doesn't really need to be used).
If you wish to proceed with the transfer see the
sendTransferInfo method.
"""
cookie = self._newInvitationCookie()
d = Deferred()
m = MSNMessage()
m.setHeader('Content-Type', 'text/x-msmsgsinvite; charset=UTF-8')
m.message += 'Application-Name: File Transfer\r\n'
m.message += 'Application-GUID: %s\r\n' % (classNameToGUID["file transfer"],)
m.message += 'Invitation-Command: INVITE\r\n'
m.message += 'Invitation-Cookie: %s\r\n' % str(cookie)
m.message += 'Application-File: %s\r\n' % fileName
m.message += 'Application-FileSize: %s\r\n\r\n' % str(fileSize)
m.ack = m.MESSAGE_ACK_NONE
self.sendMessage(m)
self.cookies['iCookies'][cookie] = (d, m)
return d
def fileInvitationReply(self, iCookie, accept=1):
"""
used to reply to a file transfer invitation.
@param iCookie: the invitation cookie of the initial invitation
@param accept: whether or not you accept this transfer,
1 = yes, 0 = no, default = 1.
@return: A Deferred, the callback for which will be fired when
the user responds with the transfer information.
The callback argument will be a tuple with 5 elements,
whether or not they wish to proceed with the transfer
(1=yes, 0=no), their ip, the port, the authentication
cookie (see FileReceive/FileSend) and the message
info (dict) (in case they send extra header-like info
like Internal-IP, this doesn't necessarily need to be
used). If you wish to proceed with the transfer see
FileReceive.
"""
d = Deferred()
m = MSNMessage()
m.setHeader('Content-Type', 'text/x-msmsgsinvite; charset=UTF-8')
m.message += 'Invitation-Command: %s\r\n' % (accept and 'ACCEPT' or 'CANCEL')
m.message += 'Invitation-Cookie: %s\r\n' % str(iCookie)
if not accept:
m.message += 'Cancel-Code: REJECT\r\n'
m.message += 'Launch-Application: FALSE\r\n'
m.message += 'Request-Data: IP-Address:\r\n'
m.message += '\r\n'
m.ack = m.MESSAGE_ACK_NONE
self.sendMessage(m)
self.cookies['external'][iCookie] = (d, m)
return d
def sendTransferInfo(self, accept, iCookie, authCookie, ip, port):
"""
send information relating to a file transfer session.
@param accept: whether or not to go ahead with the transfer
(1=yes, 0=no)
@param iCookie: the invitation cookie of previous replies
relating to this transfer
@param authCookie: the authentication cookie obtained from
an FileSend instance
@param ip: your ip
@param port: the port on which an FileSend protocol is listening.
"""
m = MSNMessage()
m.setHeader('Content-Type', 'text/x-msmsgsinvite; charset=UTF-8')
m.message += 'Invitation-Command: %s\r\n' % (accept and 'ACCEPT' or 'CANCEL')
m.message += 'Invitation-Cookie: %s\r\n' % iCookie
m.message += 'IP-Address: %s\r\n' % ip
m.message += 'Port: %s\r\n' % port
m.message += 'AuthCookie: %s\r\n' % authCookie
m.message += '\r\n'
m.ack = m.MESSAGE_NACK
self.sendMessage(m)
class FileReceive(LineReceiver):
"""
This class provides support for receiving files from contacts.
@ivar fileSize: the size of the receiving file. (you will have to set this)
@ivar connected: true if a connection has been established.
@ivar completed: true if the transfer is complete.
@ivar bytesReceived: number of bytes (of the file) received.
This does not include header data.
"""
def __init__(self, auth, myUserHandle, file, directory="", overwrite=0):
"""
@param auth: auth string received in the file invitation.
@param myUserHandle: your userhandle.
@param file: A string or file object represnting the file
to save data to.
@param directory: optional parameter specifiying the directory.
Defaults to the current directory.
@param overwrite: if true and a file of the same name exists on
your system, it will be overwritten. (0 by default)
"""
self.auth = auth
self.myUserHandle = myUserHandle
self.fileSize = 0
self.connected = 0
self.completed = 0
self.directory = directory
self.bytesReceived = 0
self.overwrite = overwrite
# used for handling current received state
self.state = 'CONNECTING'
self.segmentLength = 0
self.buffer = ''
if isinstance(file, types.StringType):
path = os.path.join(directory, file)
if os.path.exists(path) and not self.overwrite:
log.msg('File already exists...')
raise IOError, "File Exists" # is this all we should do here?
self.file = open(os.path.join(directory, file), 'wb')
else:
self.file = file
def connectionMade(self):
self.connected = 1
self.state = 'INHEADER'
self.sendLine('VER MSNFTP')
def connectionLost(self, reason):
self.connected = 0
self.file.close()
def parseHeader(self, header):
""" parse the header of each 'message' to obtain the segment length """
if ord(header[0]) != 0: # they requested that we close the connection
self.transport.loseConnection()
return
try:
extra, factor = header[1:]
except ValueError:
# munged header, ending transfer
self.transport.loseConnection()
raise
extra = ord(extra)
factor = ord(factor)
return factor * 256 + extra
def lineReceived(self, line):
temp = line.split()
if len(temp) == 1:
params = []
else:
params = temp[1:]
cmd = temp[0]
handler = getattr(self, "handle_%s" % cmd.upper(), None)
if handler:
handler(params) # try/except
else:
self.handle_UNKNOWN(cmd, params)
def rawDataReceived(self, data):
bufferLen = len(self.buffer)
if self.state == 'INHEADER':
delim = 3-bufferLen
self.buffer += data[:delim]
if len(self.buffer) == 3:
self.segmentLength = self.parseHeader(self.buffer)
if not self.segmentLength:
return # hrm
self.buffer = ""
self.state = 'INSEGMENT'
extra = data[delim:]
if len(extra) > 0:
self.rawDataReceived(extra)
return
elif self.state == 'INSEGMENT':
dataSeg = data[:(self.segmentLength-bufferLen)]
self.buffer += dataSeg
self.bytesReceived += len(dataSeg)
if len(self.buffer) == self.segmentLength:
self.gotSegment(self.buffer)
self.buffer = ""
if self.bytesReceived == self.fileSize:
self.completed = 1
self.buffer = ""
self.file.close()
self.sendLine("BYE 16777989")
return
self.state = 'INHEADER'
extra = data[(self.segmentLength-bufferLen):]
if len(extra) > 0:
self.rawDataReceived(extra)
return
def handle_VER(self, params):
checkParamLen(len(params), 1, 'VER')
if params[0].upper() == "MSNFTP":
self.sendLine("USR %s %s" % (self.myUserHandle, self.auth))
else:
log.msg('they sent the wrong version, time to quit this transfer')
self.transport.loseConnection()
def handle_FIL(self, params):
checkParamLen(len(params), 1, 'FIL')
try:
self.fileSize = int(params[0])
except ValueError: # they sent the wrong file size - probably want to log this
self.transport.loseConnection()
return
self.setRawMode()
self.sendLine("TFR")
def handle_UNKNOWN(self, cmd, params):
log.msg('received unknown command (%s), params: %s' % (cmd, params))
def gotSegment(self, data):
""" called when a segment (block) of data arrives. """
self.file.write(data)
class FileSend(LineReceiver):
"""
This class provides support for sending files to other contacts.
@ivar bytesSent: the number of bytes that have currently been sent.
@ivar completed: true if the send has completed.
@ivar connected: true if a connection has been established.
@ivar targetUser: the target user (contact).
@ivar segmentSize: the segment (block) size.
@ivar auth: the auth cookie (number) to use when sending the
transfer invitation
"""
def __init__(self, file):
"""
@param file: A string or file object represnting the file to send.
"""
if isinstance(file, types.StringType):
self.file = open(file, 'rb')
else:
self.file = file
self.fileSize = 0
self.bytesSent = 0
self.completed = 0
self.connected = 0
self.targetUser = None
self.segmentSize = 2045
self.auth = randint(0, 2**30)
self._pendingSend = None # :(
def connectionMade(self):
self.connected = 1
def connectionLost(self, reason):
if self._pendingSend.active():
self._pendingSend.cancel()
self._pendingSend = None
if self.bytesSent == self.fileSize:
self.completed = 1
self.connected = 0
self.file.close()
def lineReceived(self, line):
temp = line.split()
if len(temp) == 1:
params = []
else:
params = temp[1:]
cmd = temp[0]
handler = getattr(self, "handle_%s" % cmd.upper(), None)
if handler:
handler(params)
else:
self.handle_UNKNOWN(cmd, params)
def handle_VER(self, params):
checkParamLen(len(params), 1, 'VER')
if params[0].upper() == "MSNFTP":
self.sendLine("VER MSNFTP")
else: # they sent some weird version during negotiation, i'm quitting.
self.transport.loseConnection()
def handle_USR(self, params):
checkParamLen(len(params), 2, 'USR')
self.targetUser = params[0]
if self.auth == int(params[1]):
self.sendLine("FIL %s" % (self.fileSize))
else: # they failed the auth test, disconnecting.
self.transport.loseConnection()
def handle_TFR(self, params):
checkParamLen(len(params), 0, 'TFR')
# they are ready for me to start sending
self.sendPart()
def handle_BYE(self, params):
self.completed = (self.bytesSent == self.fileSize)
self.transport.loseConnection()
def handle_CCL(self, params):
self.completed = (self.bytesSent == self.fileSize)
self.transport.loseConnection()
def handle_UNKNOWN(self, cmd, params):
log.msg('received unknown command (%s), params: %s' % (cmd, params))
def makeHeader(self, size):
""" make the appropriate header given a specific segment size. """
quotient, remainder = divmod(size, 256)
return chr(0) + chr(remainder) + chr(quotient)
def sendPart(self):
""" send a segment of data """
if not self.connected:
self._pendingSend = None
return # may be buggy (if handle_CCL/BYE is called but self.connected is still 1)
data = self.file.read(self.segmentSize)
if data:
dataSize = len(data)
header = self.makeHeader(dataSize)
self.bytesSent += dataSize
self.transport.write(header + data)
self._pendingSend = reactor.callLater(0, self.sendPart)
else:
self._pendingSend = None
self.completed = 1
# mapping of error codes to error messages
errorCodes = {
200 : "Syntax error",
201 : "Invalid parameter",
205 : "Invalid user",
206 : "Domain name missing",
207 : "Already logged in",
208 : "Invalid username",
209 : "Invalid screen name",
210 : "User list full",
215 : "User already there",
216 : "User already on list",
217 : "User not online",
218 : "Already in mode",
219 : "User is in the opposite list",
223 : "Too many groups",
224 : "Invalid group",
225 : "User not in group",
229 : "Group name too long",
230 : "Cannot remove group 0",
231 : "Invalid group",
280 : "Switchboard failed",
281 : "Transfer to switchboard failed",
300 : "Required field missing",
301 : "Too many FND responses",
302 : "Not logged in",
500 : "Internal server error",
501 : "Database server error",
502 : "Command disabled",
510 : "File operation failed",
520 : "Memory allocation failed",
540 : "Wrong CHL value sent to server",
600 : "Server is busy",
601 : "Server is unavaliable",
602 : "Peer nameserver is down",
603 : "Database connection failed",
604 : "Server is going down",
605 : "Server unavailable",
707 : "Could not create connection",
710 : "Invalid CVR parameters",
711 : "Write is blocking",
712 : "Session is overloaded",
713 : "Too many active users",
714 : "Too many sessions",
715 : "Not expected",
717 : "Bad friend file",
731 : "Not expected",
800 : "Requests too rapid",
910 : "Server too busy",
911 : "Authentication failed",
912 : "Server too busy",
913 : "Not allowed when offline",
914 : "Server too busy",
915 : "Server too busy",
916 : "Server too busy",
917 : "Server too busy",
918 : "Server too busy",
919 : "Server too busy",
920 : "Not accepting new users",
921 : "Server too busy",
922 : "Server too busy",
923 : "No parent consent",
924 : "Passport account not yet verified"
}
# mapping of status codes to readable status format
statusCodes = {
STATUS_ONLINE : "Online",
STATUS_OFFLINE : "Offline",
STATUS_HIDDEN : "Appear Offline",
STATUS_IDLE : "Idle",
STATUS_AWAY : "Away",
STATUS_BUSY : "Busy",
STATUS_BRB : "Be Right Back",
STATUS_PHONE : "On the Phone",
STATUS_LUNCH : "Out to Lunch"
}
# mapping of list ids to list codes
listIDToCode = {
FORWARD_LIST : 'fl',
BLOCK_LIST : 'bl',
ALLOW_LIST : 'al',
REVERSE_LIST : 'rl'
}
# mapping of list codes to list ids
listCodeToID = {}
for id,code in listIDToCode.items():
listCodeToID[code] = id
del id, code
# Mapping of class GUIDs to simple english names
guidToClassName = {
"{5D3E02AB-6190-11d3-BBBB-00C04F795683}": "file transfer",
}
# Reverse of the above
classNameToGUID = {}
for guid, name in guidToClassName.iteritems():
classNameToGUID[name] = guid | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/protocols/msn.py | msn.py |
from __future__ import nested_scopes
from twisted.internet import reactor, defer, protocol
from twisted.python import log
import struct
import md5
import string
import socket
import random
import time
import types
import re
def logPacketData(data):
lines = len(data)/16
if lines*16 != len(data): lines=lines+1
for i in range(lines):
d = tuple(data[16*i:16*i+16])
hex = map(lambda x: "%02X"%ord(x),d)
text = map(lambda x: (len(repr(x))>3 and '.') or x, d)
log.msg(' '.join(hex)+ ' '*3*(16-len(d)) +''.join(text))
log.msg('')
def SNAC(fam,sub,id,data,flags=[0,0]):
header="!HHBBL"
head=struct.pack(header,fam,sub,
flags[0],flags[1],
id)
return head+str(data)
def readSNAC(data):
header="!HHBBL"
head=list(struct.unpack(header,data[:10]))
return head+[data[10:]]
def TLV(type,value):
header="!HH"
head=struct.pack(header,type,len(value))
return head+str(value)
def readTLVs(data,count=None):
header="!HH"
dict={}
while data and len(dict)!=count:
head=struct.unpack(header,data[:4])
dict[head[0]]=data[4:4+head[1]]
data=data[4+head[1]:]
if not count:
return dict
return dict,data
def encryptPasswordMD5(password,key):
m=md5.new()
m.update(key)
m.update(md5.new(password).digest())
m.update("AOL Instant Messenger (SM)")
return m.digest()
def encryptPasswordICQ(password):
key=[0xF3,0x26,0x81,0xC4,0x39,0x86,0xDB,0x92,0x71,0xA3,0xB9,0xE6,0x53,0x7A,0x95,0x7C]
bytes=map(ord,password)
r=""
for i in range(len(bytes)):
r=r+chr(bytes[i]^key[i%len(key)])
return r
def dehtml(text):
text=string.replace(text,"<br>","\n")
text=string.replace(text,"<BR>","\n")
text=string.replace(text,"<Br>","\n") # XXX make this a regexp
text=string.replace(text,"<bR>","\n")
text=re.sub('<.*?>','',text)
text=string.replace(text,'>','>')
text=string.replace(text,'<','<')
text=string.replace(text,' ',' ')
text=string.replace(text,'"','"')
text=string.replace(text,'&','&')
return text
def html(text):
text=string.replace(text,'"','"')
text=string.replace(text,'&','&')
text=string.replace(text,'<','<')
text=string.replace(text,'>','>')
text=string.replace(text,"\n","<br>")
return '<html><body bgcolor="white"><font color="black">%s</font></body></html>'%text
class OSCARUser:
def __init__(self, name, warn, tlvs):
self.name = name
self.warning = warn
self.flags = []
self.caps = []
for k,v in tlvs.items():
if k == 1: # user flags
v=struct.unpack('!H',v)[0]
for o, f in [(1,'trial'),
(2,'unknown bit 2'),
(4,'aol'),
(8,'unknown bit 4'),
(16,'aim'),
(32,'away'),
(1024,'activebuddy')]:
if v&o: self.flags.append(f)
elif k == 2: # member since date
self.memberSince = struct.unpack('!L',v)[0]
elif k == 3: # on-since
self.onSince = struct.unpack('!L',v)[0]
elif k == 4: # idle time
self.idleTime = struct.unpack('!H',v)[0]
elif k == 5: # unknown
pass
elif k == 6: # icq online status
if v[2] == '\x00':
self.icqStatus = 'online'
elif v[2] == '\x01':
self.icqStatus = 'away'
elif v[2] == '\x02':
self.icqStatus = 'dnd'
elif v[2] == '\x04':
self.icqStatus = 'out'
elif v[2] == '\x10':
self.icqStatus = 'busy'
else:
self.icqStatus = 'unknown'
elif k == 10: # icq ip address
self.icqIPaddy = socket.inet_ntoa(v)
elif k == 12: # icq random stuff
self.icqRandom = v
elif k == 13: # capabilities
caps=[]
while v:
c=v[:16]
if c==CAP_ICON: caps.append("icon")
elif c==CAP_IMAGE: caps.append("image")
elif c==CAP_VOICE: caps.append("voice")
elif c==CAP_CHAT: caps.append("chat")
elif c==CAP_GET_FILE: caps.append("getfile")
elif c==CAP_SEND_FILE: caps.append("sendfile")
elif c==CAP_SEND_LIST: caps.append("sendlist")
elif c==CAP_GAMES: caps.append("games")
else: caps.append(("unknown",c))
v=v[16:]
caps.sort()
self.caps=caps
elif k == 14: pass
elif k == 15: # session length (aim)
self.sessionLength = struct.unpack('!L',v)[0]
elif k == 16: # session length (aol)
self.sessionLength = struct.unpack('!L',v)[0]
elif k == 30: # no idea
pass
else:
log.msg("unknown tlv for user %s\nt: %s\nv: %s"%(self.name,k,repr(v)))
def __str__(self):
s = '<OSCARUser %s' % self.name
o = []
if self.warning!=0: o.append('warning level %s'%self.warning)
if hasattr(self, 'flags'): o.append('flags %s'%self.flags)
if hasattr(self, 'sessionLength'): o.append('online for %i minutes' % (self.sessionLength/60,))
if hasattr(self, 'idleTime'): o.append('idle for %i minutes' % self.idleTime)
if self.caps: o.append('caps %s'%self.caps)
if o:
s=s+', '+', '.join(o)
s=s+'>'
return s
class SSIGroup:
def __init__(self, name, tlvs = {}):
self.name = name
#self.tlvs = []
#self.userIDs = []
self.usersToID = {}
self.users = []
#if not tlvs.has_key(0xC8): return
#buddyIDs = tlvs[0xC8]
#while buddyIDs:
# bid = struct.unpack('!H',buddyIDs[:2])[0]
# buddyIDs = buddyIDs[2:]
# self.users.append(bid)
def findIDFor(self, user):
return self.usersToID[user]
def addUser(self, buddyID, user):
self.usersToID[user] = buddyID
self.users.append(user)
user.group = self
def oscarRep(self, groupID, buddyID):
tlvData = TLV(0xc8, reduce(lambda x,y:x+y, [struct.pack('!H',self.usersToID[x]) for x in self.users]))
return struct.pack('!H', len(self.name)) + self.name + \
struct.pack('!HH', groupID, buddyID) + '\000\001' + tlvData
class SSIBuddy:
def __init__(self, name, tlvs = {}):
self.name = name
self.tlvs = tlvs
for k,v in tlvs.items():
if k == 0x013c: # buddy comment
self.buddyComment = v
elif k == 0x013d: # buddy alerts
actionFlag = ord(v[0])
whenFlag = ord(v[1])
self.alertActions = []
self.alertWhen = []
if actionFlag&1:
self.alertActions.append('popup')
if actionFlag&2:
self.alertActions.append('sound')
if whenFlag&1:
self.alertWhen.append('online')
if whenFlag&2:
self.alertWhen.append('unidle')
if whenFlag&4:
self.alertWhen.append('unaway')
elif k == 0x013e:
self.alertSound = v
def oscarRep(self, groupID, buddyID):
tlvData = reduce(lambda x,y: x+y, map(lambda (k,v):TLV(k,v), self.tlvs.items()), '\000\000')
return struct.pack('!H', len(self.name)) + self.name + \
struct.pack('!HH', groupID, buddyID) + '\000\000' + tlvData
class OscarConnection(protocol.Protocol):
def connectionMade(self):
self.state=""
self.seqnum=0
self.buf=''
self.stopKeepAliveID = None
self.setKeepAlive(4*60) # 4 minutes
def connectionLost(self, reason):
log.msg("Connection Lost! %s" % self)
self.stopKeepAlive()
# def connectionFailed(self):
# log.msg("Connection Failed! %s" % self)
# self.stopKeepAlive()
def sendFLAP(self,data,channel = 0x02):
header="!cBHH"
self.seqnum=(self.seqnum+1)%0xFFFF
seqnum=self.seqnum
head=struct.pack(header,'*', channel,
seqnum, len(data))
self.transport.write(head+str(data))
# if isinstance(self, ChatService):
# logPacketData(head+str(data))
def readFlap(self):
header="!cBHH"
if len(self.buf)<6: return
flap=struct.unpack(header,self.buf[:6])
if len(self.buf)<6+flap[3]: return
data,self.buf=self.buf[6:6+flap[3]],self.buf[6+flap[3]:]
return [flap[1],data]
def dataReceived(self,data):
# if isinstance(self, ChatService):
# logPacketData(data)
self.buf=self.buf+data
flap=self.readFlap()
while flap:
func=getattr(self,"oscar_%s"%self.state,None)
if not func:
log.msg("no func for state: %s" % self.state)
state=func(flap)
if state:
self.state=state
flap=self.readFlap()
def setKeepAlive(self,t):
self.keepAliveDelay=t
self.stopKeepAlive()
self.stopKeepAliveID = reactor.callLater(t, self.sendKeepAlive)
def sendKeepAlive(self):
self.sendFLAP("",0x05)
self.stopKeepAliveID = reactor.callLater(self.keepAliveDelay, self.sendKeepAlive)
def stopKeepAlive(self):
if self.stopKeepAliveID:
self.stopKeepAliveID.cancel()
self.stopKeepAliveID = None
def disconnect(self):
"""
send the disconnect flap, and sever the connection
"""
self.sendFLAP('', 0x04)
def f(reason): pass
self.connectionLost = f
self.transport.loseConnection()
class SNACBased(OscarConnection):
snacFamilies = {
# family : (version, toolID, toolVersion)
}
def __init__(self,cookie):
self.cookie=cookie
self.lastID=0
self.supportedFamilies = ()
self.requestCallbacks={} # request id:Deferred
def sendSNAC(self,fam,sub,data,flags=[0,0]):
"""
send a snac and wait for the response by returning a Deferred.
"""
reqid=self.lastID
self.lastID=reqid+1
d = defer.Deferred()
d.reqid = reqid
#d.addErrback(self._ebDeferredError,fam,sub,data) # XXX for testing
self.requestCallbacks[reqid] = d
self.sendFLAP(SNAC(fam,sub,reqid,data))
return d
def _ebDeferredError(self, error, fam, sub, data):
log.msg('ERROR IN DEFERRED %s' % error)
log.msg('on sending of message, family 0x%02x, subtype 0x%02x' % (fam, sub))
log.msg('data: %s' % repr(data))
def sendSNACnr(self,fam,sub,data,flags=[0,0]):
"""
send a snac, but don't bother adding a deferred, we don't care.
"""
self.sendFLAP(SNAC(fam,sub,0x10000*fam+sub,data))
def oscar_(self,data):
self.sendFLAP("\000\000\000\001"+TLV(6,self.cookie), 0x01)
return "Data"
def oscar_Data(self,data):
snac=readSNAC(data[1])
if self.requestCallbacks.has_key(snac[4]):
d = self.requestCallbacks[snac[4]]
del self.requestCallbacks[snac[4]]
if snac[1]!=1:
d.callback(snac)
else:
d.errback(snac)
return
func=getattr(self,'oscar_%02X_%02X'%(snac[0],snac[1]),None)
if not func:
self.oscar_unknown(snac)
else:
func(snac[2:])
return "Data"
def oscar_unknown(self,snac):
log.msg("unknown for %s" % self)
log.msg(snac)
def oscar_01_03(self, snac):
numFamilies = len(snac[3])/2
self.supportedFamilies = struct.unpack("!"+str(numFamilies)+'H', snac[3])
d = ''
for fam in self.supportedFamilies:
if self.snacFamilies.has_key(fam):
d=d+struct.pack('!2H',fam,self.snacFamilies[fam][0])
self.sendSNACnr(0x01,0x17, d)
def oscar_01_0A(self,snac):
"""
change of rate information.
"""
# this can be parsed, maybe we can even work it in
pass
def oscar_01_18(self,snac):
"""
host versions, in the same format as we sent
"""
self.sendSNACnr(0x01,0x06,"") #pass
def clientReady(self):
"""
called when the client is ready to be online
"""
d = ''
for fam in self.supportedFamilies:
if self.snacFamilies.has_key(fam):
version, toolID, toolVersion = self.snacFamilies[fam]
d = d + struct.pack('!4H',fam,version,toolID,toolVersion)
self.sendSNACnr(0x01,0x02,d)
class BOSConnection(SNACBased):
snacFamilies = {
0x01:(3, 0x0110, 0x059b),
0x13:(3, 0x0110, 0x059b),
0x02:(1, 0x0110, 0x059b),
0x03:(1, 0x0110, 0x059b),
0x04:(1, 0x0110, 0x059b),
0x06:(1, 0x0110, 0x059b),
0x08:(1, 0x0104, 0x0001),
0x09:(1, 0x0110, 0x059b),
0x0a:(1, 0x0110, 0x059b),
0x0b:(1, 0x0104, 0x0001),
0x0c:(1, 0x0104, 0x0001)
}
capabilities = None
def __init__(self,username,cookie):
SNACBased.__init__(self,cookie)
self.username=username
self.profile = None
self.awayMessage = None
self.services = {}
if not self.capabilities:
self.capabilities = [CAP_CHAT]
def parseUser(self,data,count=None):
l=ord(data[0])
name=data[1:1+l]
warn,foo=struct.unpack("!HH",data[1+l:5+l])
warn=int(warn/10)
tlvs=data[5+l:]
if count:
tlvs,rest = readTLVs(tlvs,foo)
else:
tlvs,rest = readTLVs(tlvs), None
u = OSCARUser(name, warn, tlvs)
if rest == None:
return u
else:
return u, rest
def oscar_01_05(self, snac, d = None):
"""
data for a new service connection
d might be a deferred to be called back when the service is ready
"""
tlvs = readTLVs(snac[3][2:])
service = struct.unpack('!H',tlvs[0x0d])[0]
ip = tlvs[5]
cookie = tlvs[6]
#c = serviceClasses[service](self, cookie, d)
c = protocol.ClientCreator(reactor, serviceClasses[service], self, cookie, d)
def addService(x):
self.services[service] = x
c.connectTCP(ip, 5190).addCallback(addService)
#self.services[service] = c
def oscar_01_07(self,snac):
"""
rate paramaters
"""
self.sendSNACnr(0x01,0x08,"\x00\x01\x00\x02\x00\x03\x00\x04\x00\x05") # ack
self.initDone()
self.sendSNACnr(0x13,0x02,'') # SSI rights info
self.sendSNACnr(0x02,0x02,'') # location rights info
self.sendSNACnr(0x03,0x02,'') # buddy list rights
self.sendSNACnr(0x04,0x04,'') # ICBM parms
self.sendSNACnr(0x09,0x02,'') # BOS rights
def oscar_01_10(self,snac):
"""
we've been warned
"""
skip = struct.unpack('!H',snac[3][:2])[0]
newLevel = struct.unpack('!H',snac[3][2+skip:4+skip])[0]/10
if len(snac[3])>4+skip:
by = self.parseUser(snac[3][4+skip:])
else:
by = None
self.receiveWarning(newLevel, by)
def oscar_01_13(self,snac):
"""
MOTD
"""
pass # we don't care for now
def oscar_02_03(self, snac):
"""
location rights response
"""
tlvs = readTLVs(snac[3])
self.maxProfileLength = tlvs[1]
def oscar_03_03(self, snac):
"""
buddy list rights response
"""
tlvs = readTLVs(snac[3])
self.maxBuddies = tlvs[1]
self.maxWatchers = tlvs[2]
def oscar_03_0B(self, snac):
"""
buddy update
"""
self.updateBuddy(self.parseUser(snac[3]))
def oscar_03_0C(self, snac):
"""
buddy offline
"""
self.offlineBuddy(self.parseUser(snac[3]))
# def oscar_04_03(self, snac):
def oscar_04_05(self, snac):
"""
ICBM parms response
"""
self.sendSNACnr(0x04,0x02,'\x00\x00\x00\x00\x00\x0b\x1f@\x03\xe7\x03\xe7\x00\x00\x00\x00') # IM rights
def oscar_04_07(self, snac):
"""
ICBM message (instant message)
"""
data = snac[3]
cookie, data = data[:8], data[8:]
channel = struct.unpack('!H',data[:2])[0]
data = data[2:]
user, data = self.parseUser(data, 1)
tlvs = readTLVs(data)
if channel == 1: # message
flags = []
multiparts = []
for k, v in tlvs.items():
if k == 2:
while v:
v = v[2:] # skip bad data
messageLength, charSet, charSubSet = struct.unpack('!3H', v[:6])
messageLength -= 4
message = [v[6:6+messageLength]]
if charSet == 0:
pass # don't add anything special
elif charSet == 2:
message.append('unicode')
elif charSet == 3:
message.append('iso-8859-1')
elif charSet == 0xffff:
message.append('none')
if charSubSet == 0xb:
message.append('macintosh')
if messageLength > 0: multiparts.append(tuple(message))
v = v[6+messageLength:]
elif k == 3:
flags.append('acknowledge')
elif k == 4:
flags.append('auto')
elif k == 6:
flags.append('offline')
elif k == 8:
iconLength, foo, iconSum, iconStamp = struct.unpack('!LHHL',v)
if iconLength:
flags.append('icon')
flags.append((iconLength, iconSum, iconStamp))
elif k == 9:
flags.append('buddyrequest')
elif k == 0xb: # unknown
pass
elif k == 0x17:
flags.append('extradata')
flags.append(v)
else:
log.msg('unknown TLV for incoming IM, %04x, %s' % (k,repr(v)))
# unknown tlv for user SNewdorf
# t: 29
# v: '\x00\x00\x00\x05\x02\x01\xd2\x04r\x00\x01\x01\x10/\x8c\x8b\x8a\x1e\x94*\xbc\x80}\x8d\xc4;\x1dEM'
# XXX what is this?
self.receiveMessage(user, multiparts, flags)
elif channel == 2: # rondevouz
status = struct.unpack('!H',tlvs[5][:2])[0]
requestClass = tlvs[5][10:26]
moreTLVs = readTLVs(tlvs[5][26:])
if requestClass == CAP_CHAT: # a chat request
exchange = struct.unpack('!H',moreTLVs[10001][:2])[0]
name = moreTLVs[10001][3:-2]
instance = struct.unpack('!H',moreTLVs[10001][-2:])[0]
if not self.services.has_key(SERVICE_CHATNAV):
self.connectService(SERVICE_CHATNAV,1).addCallback(lambda x: self.services[SERVICE_CHATNAV].getChatInfo(exchange, name, instance).\
addCallback(self._cbGetChatInfoForInvite, user, moreTLVs[12]))
else:
self.services[SERVICE_CHATNAV].getChatInfo(exchange, name, instance).\
addCallback(self._cbGetChatInfoForInvite, user, moreTLVs[12])
elif requestClass == CAP_SEND_FILE:
if moreTLVs.has_key(11): # cancel
log.msg('cancelled file request')
log.msg(status)
return # handle this later
name = moreTLVs[10001][9:-7]
desc = moreTLVs[12]
log.msg('file request from %s, %s, %s' % (user, name, desc))
self.receiveSendFileRequest(user, name, desc, cookie)
else:
log.msg('unsupported rondevouz: %s' % requestClass)
log.msg(repr(moreTLVs))
else:
log.msg('unknown channel %02x' % channel)
log.msg(tlvs)
def _cbGetChatInfoForInvite(self, info, user, message):
apply(self.receiveChatInvite, (user,message)+info)
def oscar_09_03(self, snac):
"""
BOS rights response
"""
tlvs = readTLVs(snac[3])
self.maxPermitList = tlvs[1]
self.maxDenyList = tlvs[2]
def oscar_0B_02(self, snac):
"""
stats reporting interval
"""
self.reportingInterval = struct.unpack('!H',snac[3][:2])[0]
def oscar_13_03(self, snac):
"""
SSI rights response
"""
#tlvs = readTLVs(snac[3])
pass # we don't know how to parse this
# methods to be called by the client, and their support methods
def requestSelfInfo(self):
"""
ask for the OSCARUser for ourselves
"""
d = defer.Deferred()
self.sendSNAC(0x01, 0x0E, '').addCallback(self._cbRequestSelfInfo, d)
return d
def _cbRequestSelfInfo(self, snac, d):
d.callback(self.parseUser(snac[5]))
def initSSI(self):
"""
this sends the rate request for family 0x13 (Server Side Information)
so we can then use it
"""
return self.sendSNAC(0x13, 0x02, '').addCallback(self._cbInitSSI)
def _cbInitSSI(self, snac, d):
return {} # don't even bother parsing this
def requestSSI(self, timestamp = 0, revision = 0):
"""
request the server side information
if the deferred gets None, it means the SSI is the same
"""
return self.sendSNAC(0x13, 0x05,
struct.pack('!LH',timestamp,revision)).addCallback(self._cbRequestSSI)
def _cbRequestSSI(self, snac, args = ()):
if snac[1] == 0x0f: # same SSI as we have
return
itemdata = snac[5][3:]
if args:
revision, groups, permit, deny, permitMode, visibility = args
else:
version, revision = struct.unpack('!BH', snac[5][:3])
groups = {}
permit = []
deny = []
permitMode = None
visibility = None
while len(itemdata)>4:
nameLength = struct.unpack('!H', itemdata[:2])[0]
name = itemdata[2:2+nameLength]
groupID, buddyID, itemType, restLength = \
struct.unpack('!4H', itemdata[2+nameLength:10+nameLength])
tlvs = readTLVs(itemdata[10+nameLength:10+nameLength+restLength])
itemdata = itemdata[10+nameLength+restLength:]
if itemType == 0: # buddies
groups[groupID].addUser(buddyID, SSIBuddy(name, tlvs))
elif itemType == 1: # group
g = SSIGroup(name, tlvs)
if groups.has_key(0): groups[0].addUser(groupID, g)
groups[groupID] = g
elif itemType == 2: # permit
permit.append(name)
elif itemType == 3: # deny
deny.append(name)
elif itemType == 4: # permit deny info
if not tlvs.has_key(0xcb):
continue # this happens with ICQ
permitMode = {1:'permitall',2:'denyall',3:'permitsome',4:'denysome',5:'permitbuddies'}[ord(tlvs[0xca])]
visibility = {'\xff\xff\xff\xff':'all','\x00\x00\x00\x04':'notaim'}[tlvs[0xcb]]
elif itemType == 5: # unknown (perhaps idle data)?
pass
else:
log.msg('%s %s %s %s %s' % (name, groupID, buddyID, itemType, tlvs))
timestamp = struct.unpack('!L',itemdata)[0]
if not timestamp: # we've got more packets coming
# which means add some deferred stuff
d = defer.Deferred()
self.requestCallbacks[snac[4]] = d
d.addCallback(self._cbRequestSSI, (revision, groups, permit, deny, permitMode, visibility))
return d
return (groups[0].users,permit,deny,permitMode,visibility,timestamp,revision)
def activateSSI(self):
"""
active the data stored on the server (use buddy list, permit deny settings, etc.)
"""
self.sendSNACnr(0x13,0x07,'')
def startModifySSI(self):
"""
tell the OSCAR server to be on the lookout for SSI modifications
"""
self.sendSNACnr(0x13,0x11,'')
def addItemSSI(self, item, groupID = None, buddyID = None):
"""
add an item to the SSI server. if buddyID == 0, then this should be a group.
this gets a callback when it's finished, but you can probably ignore it.
"""
if groupID is None:
if isinstance(item, SSIGroup):
groupID = 0
else:
groupID = item.group.group.findIDFor(item.group)
if buddyID is None:
buddyID = item.group.findIDFor(item)
return self.sendSNAC(0x13,0x08, item.oscarRep(groupID, buddyID))
def modifyItemSSI(self, item, groupID = None, buddyID = None):
if groupID is None:
if isinstance(item, SSIGroup):
groupID = 0
else:
groupID = item.group.group.findIDFor(item.group)
if buddyID is None:
buddyID = item.group.findIDFor(item)
return self.sendSNAC(0x13,0x09, item.oscarRep(groupID, buddyID))
def delItemSSI(self, item, groupID = None, buddyID = None):
if groupID is None:
if isinstance(item, SSIGroup):
groupID = 0
else:
groupID = item.group.group.findIDFor(item.group)
if buddyID is None:
buddyID = item.group.findIDFor(item)
return self.sendSNAC(0x13,0x0A, item.oscarRep(groupID, buddyID))
def endModifySSI(self):
self.sendSNACnr(0x13,0x12,'')
def setProfile(self, profile):
"""
set the profile.
send None to not set a profile (different from '' for a blank one)
"""
self.profile = profile
tlvs = ''
if self.profile is not None:
tlvs = TLV(1,'text/aolrtf; charset="us-ascii"') + \
TLV(2,self.profile)
tlvs = tlvs + TLV(5, ''.join(self.capabilities))
self.sendSNACnr(0x02, 0x04, tlvs)
def setAway(self, away = None):
"""
set the away message, or return (if away == None)
"""
self.awayMessage = away
tlvs = TLV(3,'text/aolrtf; charset="us-ascii"') + \
TLV(4,away or '')
self.sendSNACnr(0x02, 0x04, tlvs)
def setIdleTime(self, idleTime):
"""
set our idle time. don't call more than once with a non-0 idle time.
"""
self.sendSNACnr(0x01, 0x11, struct.pack('!L',idleTime))
def sendMessage(self, user, message, wantAck = 0, autoResponse = 0, offline = 0 ): \
#haveIcon = 0, ):
"""
send a message to user (not an OSCARUseR).
message can be a string, or a multipart tuple.
if wantAck, we return a Deferred that gets a callback when the message is sent.
if autoResponse, this message is an autoResponse, as if from an away message.
if offline, this is an offline message (ICQ only, I think)
"""
data = ''.join([chr(random.randrange(0, 127)) for i in range(8)]) # cookie
data = data + '\x00\x01' + chr(len(user)) + user
if not type(message) in (types.TupleType, types.ListType):
message = [[message,]]
if type(message[0][0]) == types.UnicodeType:
message[0].append('unicode')
messageData = ''
for part in message:
charSet = 0
if 'unicode' in part[1:]:
charSet = 2
part[0] = part[0].encode('utf-8')
elif 'iso-8859-1' in part[1:]:
charSet = 3
part[0] = part[0].encode('iso-8859-1')
elif 'none' in part[1:]:
charSet = 0xffff
if 'macintosh' in part[1:]:
charSubSet = 0xb
else:
charSubSet = 0
messageData = messageData + '\x01\x01' + \
struct.pack('!3H',len(part[0])+4,charSet,charSubSet)
messageData = messageData + part[0]
data = data + TLV(2, '\x05\x01\x00\x03\x01\x01\x02'+messageData)
if wantAck:
data = data + TLV(3,'')
if autoResponse:
data = data + TLV(4,'')
if offline:
data = data + TLV(6,'')
if wantAck:
return self.sendSNAC(0x04, 0x06, data).addCallback(self._cbSendMessageAck, user, message)
self.sendSNACnr(0x04, 0x06, data)
def _cbSendMessageAck(self, snac, user, message):
return user, message
def connectService(self, service, wantCallback = 0, extraData = ''):
"""
connect to another service
if wantCallback, we return a Deferred that gets called back when the service is online.
if extraData, append that to our request.
"""
if wantCallback:
d = defer.Deferred()
self.sendSNAC(0x01,0x04,struct.pack('!H',service) + extraData).addCallback(self._cbConnectService, d)
return d
else:
self.sendSNACnr(0x01,0x04,struct.pack('!H',service))
def _cbConnectService(self, snac, d):
self.oscar_01_05(snac[2:], d)
def createChat(self, shortName):
"""
create a chat room
"""
if self.services.has_key(SERVICE_CHATNAV):
return self.services[SERVICE_CHATNAV].createChat(shortName)
else:
return self.connectService(SERVICE_CHATNAV,1).addCallback(lambda s: s.createChat(shortName))
def joinChat(self, exchange, fullName, instance):
"""
join a chat room
"""
#d = defer.Deferred()
return self.connectService(0x0e, 1, TLV(0x01, struct.pack('!HB',exchange, len(fullName)) + fullName +
struct.pack('!H', instance))).addCallback(self._cbJoinChat) #, d)
#return d
def _cbJoinChat(self, chat):
del self.services[SERVICE_CHAT]
return chat
def warnUser(self, user, anon = 0):
return self.sendSNAC(0x04, 0x08, '\x00'+chr(anon)+chr(len(user))+user).addCallback(self._cbWarnUser)
def _cbWarnUser(self, snac):
oldLevel, newLevel = struct.unpack('!2H', snac[5])
return oldLevel, newLevel
def getInfo(self, user):
#if user.
return self.sendSNAC(0x02, 0x05, '\x00\x01'+chr(len(user))+user).addCallback(self._cbGetInfo)
def _cbGetInfo(self, snac):
user, rest = self.parseUser(snac[5],1)
tlvs = readTLVs(rest)
return tlvs.get(0x02,None)
def getAway(self, user):
return self.sendSNAC(0x02, 0x05, '\x00\x03'+chr(len(user))+user).addCallback(self._cbGetAway)
def _cbGetAway(self, snac):
user, rest = self.parseUser(snac[5],1)
tlvs = readTLVs(rest)
return tlvs.get(0x04,None) # return None if there is no away message
#def acceptSendFileRequest(self,
# methods to be overriden by the client
def initDone(self):
"""
called when we get the rate information, which means we should do other init. stuff.
"""
log.msg('%s initDone' % self)
pass
def updateBuddy(self, user):
"""
called when a buddy changes status, with the OSCARUser for that buddy.
"""
log.msg('%s updateBuddy %s' % (self, user))
pass
def offlineBuddy(self, user):
"""
called when a buddy goes offline
"""
log.msg('%s offlineBuddy %s' % (self, user))
pass
def receiveMessage(self, user, multiparts, flags):
"""
called when someone sends us a message
"""
pass
def receiveWarning(self, newLevel, user):
"""
called when someone warns us.
user is either None (if it was anonymous) or an OSCARUser
"""
pass
def receiveChatInvite(self, user, message, exchange, fullName, instance, shortName, inviteTime):
"""
called when someone invites us to a chat room
"""
pass
def chatReceiveMessage(self, chat, user, message):
"""
called when someone in a chatroom sends us a message in the chat
"""
pass
def chatMemberJoined(self, chat, member):
"""
called when a member joins the chat
"""
pass
def chatMemberLeft(self, chat, member):
"""
called when a member leaves the chat
"""
pass
def receiveSendFileRequest(self, user, file, description, cookie):
"""
called when someone tries to send a file to us
"""
pass
class OSCARService(SNACBased):
def __init__(self, bos, cookie, d = None):
SNACBased.__init__(self, cookie)
self.bos = bos
self.d = d
def connectionLost(self, reason):
for k,v in self.bos.services.items():
if v == self:
del self.bos.services[k]
return
def clientReady(self):
SNACBased.clientReady(self)
if self.d:
self.d.callback(self)
self.d = None
class ChatNavService(OSCARService):
snacFamilies = {
0x01:(3, 0x0010, 0x059b),
0x0d:(1, 0x0010, 0x059b)
}
def oscar_01_07(self, snac):
# rate info
self.sendSNACnr(0x01, 0x08, '\000\001\000\002\000\003\000\004\000\005')
self.sendSNACnr(0x0d, 0x02, '')
def oscar_0D_09(self, snac):
self.clientReady()
def getChatInfo(self, exchange, name, instance):
d = defer.Deferred()
self.sendSNAC(0x0d,0x04,struct.pack('!HB',exchange,len(name)) + \
name + struct.pack('!HB',instance,2)). \
addCallback(self._cbGetChatInfo, d)
return d
def _cbGetChatInfo(self, snac, d):
data = snac[5][4:]
exchange, length = struct.unpack('!HB',data[:3])
fullName = data[3:3+length]
instance = struct.unpack('!H',data[3+length:5+length])[0]
tlvs = readTLVs(data[8+length:])
shortName = tlvs[0x6a]
inviteTime = struct.unpack('!L',tlvs[0xca])[0]
info = (exchange,fullName,instance,shortName,inviteTime)
d.callback(info)
def createChat(self, shortName):
#d = defer.Deferred()
data = '\x00\x04\x06create\xff\xff\x01\x00\x03'
data = data + TLV(0xd7, 'en')
data = data + TLV(0xd6, 'us-ascii')
data = data + TLV(0xd3, shortName)
return self.sendSNAC(0x0d, 0x08, data).addCallback(self._cbCreateChat)
#return d
def _cbCreateChat(self, snac): #d):
exchange, length = struct.unpack('!HB',snac[5][4:7])
fullName = snac[5][7:7+length]
instance = struct.unpack('!H',snac[5][7+length:9+length])[0]
#d.callback((exchange, fullName, instance))
return exchange, fullName, instance
class ChatService(OSCARService):
snacFamilies = {
0x01:(3, 0x0010, 0x059b),
0x0E:(1, 0x0010, 0x059b)
}
def __init__(self,bos,cookie, d = None):
OSCARService.__init__(self,bos,cookie,d)
self.exchange = None
self.fullName = None
self.instance = None
self.name = None
self.members = None
clientReady = SNACBased.clientReady # we'll do our own callback
def oscar_01_07(self,snac):
self.sendSNAC(0x01,0x08,"\000\001\000\002\000\003\000\004\000\005")
self.clientReady()
def oscar_0E_02(self, snac):
# try: # this is EVIL
# data = snac[3][4:]
# self.exchange, length = struct.unpack('!HB',data[:3])
# self.fullName = data[3:3+length]
# self.instance = struct.unpack('!H',data[3+length:5+length])[0]
# tlvs = readTLVs(data[8+length:])
# self.name = tlvs[0xd3]
# self.d.callback(self)
# except KeyError:
data = snac[3]
self.exchange, length = struct.unpack('!HB',data[:3])
self.fullName = data[3:3+length]
self.instance = struct.unpack('!H',data[3+length:5+length])[0]
tlvs = readTLVs(data[8+length:])
self.name = tlvs[0xd3]
self.d.callback(self)
def oscar_0E_03(self,snac):
users=[]
rest=snac[3]
while rest:
user, rest = self.bos.parseUser(rest, 1)
users.append(user)
if not self.fullName:
self.members = users
else:
self.members.append(users[0])
self.bos.chatMemberJoined(self,users[0])
def oscar_0E_04(self,snac):
user=self.bos.parseUser(snac[3])
for u in self.members:
if u.name == user.name: # same person!
self.members.remove(u)
self.bos.chatMemberLeft(self,user)
def oscar_0E_06(self,snac):
data = snac[3]
user,rest=self.bos.parseUser(snac[3][14:],1)
tlvs = readTLVs(rest[8:])
message=tlvs[1]
self.bos.chatReceiveMessage(self,user,message)
def sendMessage(self,message):
tlvs=TLV(0x02,"us-ascii")+TLV(0x03,"en")+TLV(0x01,message)
self.sendSNAC(0x0e,0x05,
"\x46\x30\x38\x30\x44\x00\x63\x00\x00\x03\x00\x01\x00\x00\x00\x06\x00\x00\x00\x05"+
struct.pack("!H",len(tlvs))+
tlvs)
def leaveChat(self):
self.disconnect()
class OscarAuthenticator(OscarConnection):
BOSClass = BOSConnection
def __init__(self,username,password,deferred=None,icq=0):
self.username=username
self.password=password
self.deferred=deferred
self.icq=icq # icq mode is disabled
#if icq and self.BOSClass==BOSConnection:
# self.BOSClass=ICQConnection
def oscar_(self,flap):
if not self.icq:
self.sendFLAP("\000\000\000\001", 0x01)
self.sendFLAP(SNAC(0x17,0x06,0,
TLV(TLV_USERNAME,self.username)+
TLV(0x004B,'')))
self.state="Key"
else:
encpass=encryptPasswordICQ(self.password)
self.sendFLAP('\000\000\000\001'+
TLV(0x01,self.username)+
TLV(0x02,encpass)+
TLV(0x03,'ICQ Inc. - Product of ICQ (TM).2001b.5.18.1.3659.85')+
TLV(0x16,"\x01\x0a")+
TLV(0x17,"\x00\x05")+
TLV(0x18,"\x00\x12")+
TLV(0x19,"\000\001")+
TLV(0x1a,"\x0eK")+
TLV(0x14,"\x00\x00\x00U")+
TLV(0x0f,"en")+
TLV(0x0e,"us"),0x01)
self.state="Cookie"
def oscar_Key(self,data):
snac=readSNAC(data[1])
key=snac[5][2:]
encpass=encryptPasswordMD5(self.password,key)
self.sendFLAP(SNAC(0x17,0x02,0,
TLV(TLV_USERNAME,self.username)+
TLV(TLV_PASSWORD,encpass)+
TLV(0x004C, '')+ # unknown
TLV(TLV_CLIENTNAME,"AOL Instant Messenger (SM), version 4.8.2790/WIN32")+
TLV(0x0016,"\x01\x09")+
TLV(TLV_CLIENTMAJOR,"\000\004")+
TLV(TLV_CLIENTMINOR,"\000\010")+
TLV(0x0019,"\000\000")+
TLV(TLV_CLIENTSUB,"\x0A\xE6")+
TLV(0x0014,"\x00\x00\x00\xBB")+
TLV(TLV_LANG,"en")+
TLV(TLV_COUNTRY,"us")+
TLV(TLV_USESSI,"\001")))
return "Cookie"
def oscar_Cookie(self,data):
snac=readSNAC(data[1])
if self.icq:
i=snac[5].find("\000")
snac[5]=snac[5][i:]
tlvs=readTLVs(snac[5])
if tlvs.has_key(6):
self.cookie=tlvs[6]
server,port=string.split(tlvs[5],":")
d = self.connectToBOS(server, int(port))
d.addErrback(lambda x: log.msg("Connection Failed! Reason: %s" % x))
if self.deferred:
d.chainDeferred(self.deferred)
self.disconnect()
elif tlvs.has_key(8):
errorcode=tlvs[8]
errorurl=tlvs[4]
if errorcode=='\000\030':
error="You are attempting to sign on again too soon. Please try again later."
elif errorcode=='\000\005':
error="Invalid Username or Password."
else: error=repr(errorcode)
self.error(error,errorurl)
else:
log.msg('hmm, weird tlvs for %s cookie packet' % str(self))
log.msg(tlvs)
log.msg('snac')
log.msg(str(snac))
return "None"
def oscar_None(self,data): pass
def connectToBOS(self, server, port):
c = protocol.ClientCreator(reactor, self.BOSClass, self.username, self.cookie)
return c.connectTCP(server, int(port))
def error(self,error,url):
log.msg("ERROR! %s %s" % (error,url))
if self.deferred: self.deferred.errback((error,url))
self.transport.loseConnection()
FLAP_CHANNEL_NEW_CONNECTION = 0x01
FLAP_CHANNEL_DATA = 0x02
FLAP_CHANNEL_ERROR = 0x03
FLAP_CHANNEL_CLOSE_CONNECTION = 0x04
SERVICE_CHATNAV = 0x0d
SERVICE_CHAT = 0x0e
serviceClasses = {
SERVICE_CHATNAV:ChatNavService,
SERVICE_CHAT:ChatService
}
TLV_USERNAME = 0x0001
TLV_CLIENTNAME = 0x0003
TLV_COUNTRY = 0x000E
TLV_LANG = 0x000F
TLV_CLIENTMAJOR = 0x0017
TLV_CLIENTMINOR = 0x0018
TLV_CLIENTSUB = 0x001A
TLV_PASSWORD = 0x0025
TLV_USESSI = 0x004A
CAP_ICON = '\011F\023FL\177\021\321\202"DEST\000\000'
CAP_VOICE = '\011F\023AL\177\021\321\202"DEST\000\000'
CAP_IMAGE = '\011F\023EL\177\021\321\202"DEST\000\000'
CAP_CHAT = 't\217$ b\207\021\321\202"DEST\000\000'
CAP_GET_FILE = '\011F\023HL\177\021\321\202"DEST\000\000'
CAP_SEND_FILE = '\011F\023CL\177\021\321\202"DEST\000\000'
CAP_GAMES = '\011F\023GL\177\021\321\202"DEST\000\000'
CAP_SEND_LIST = '\011F\023KL\177\021\321\202"DEST\000\000'
CAP_SERV_REL = '\011F\023IL\177\021\321\202"DEST\000\000' | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/protocols/oscar.py | oscar.py |
# twisted imports
from twisted.internet import reactor, protocol
from twisted.python import log
# base imports
import struct
import string
import time
import base64
import os
import StringIO
SIGNON,DATA,ERROR,SIGNOFF,KEEP_ALIVE=range(1,6)
PERMITALL,DENYALL,PERMITSOME,DENYSOME=range(1,5)
DUMMY_CHECKSUM = -559038737 # 0xdeadbeef
def quote(s):
rep=['\\','$','{','}','[',']','(',')','"']
for r in rep:
s=string.replace(s,r,"\\"+r)
return "\""+s+"\""
def unquote(s):
if s=="": return ""
if s[0]!='"': return s
r=string.replace
s=s[1:-1]
s=r(s,"\\\\","\\")
s=r(s,"\\$","$")
s=r(s,"\\{","{")
s=r(s,"\\}","}")
s=r(s,"\\[","[")
s=r(s,"\\]","]")
s=r(s,"\\(","(")
s=r(s,"\\)",")")
s=r(s,"\\\"","\"")
return s
def unquotebeg(s):
for i in range(1,len(s)):
if s[i]=='"' and s[i-1]!='\\':
q=unquote(s[:i+1])
return [q,s[i+2:]]
def unroast(pw):
roaststring="Tic/Toc"
pw=string.lower(pw[2:])
r=""
count=0
hex=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"]
while pw:
st,pw=pw[:2],pw[2:]
value=(16*hex.index(st[0]))+hex.index(st[1])
xor=ord(roaststring[count])
count=(count+1)%len(roaststring)
r=r+chr(value^xor)
return r
def roast(pw):
# contributed by jemfinch on #python
key="Tic/Toc"
ro="0x"
i=0
ascii=map(ord,pw)
for c in ascii:
ro=ro+'%02x'%(c^ord(key[i%len(key)]))
i=i+1
return string.lower(ro)
def checksum(b):
return DUMMY_CHECKSUM # do it like gaim does, since the checksum
# formula doesn't work
## # used in file transfers
## check0 = check1 = 0x00ff
## for i in range(len(b)):
## if i%2:
## if ord(b[i])>check1:
## check1=check1+0x100 # wrap
## if check0==0:
## check0=0x00ff
## if check1==0x100:
## check1=check1-1
## else:
## check0=check0-1
## check1=check1-ord(b[i])
## else:
## if ord(b[i])>check0: # wrap
## check0=check0+0x100
## if check1==0:
## check1=0x00ff
## if check0==0x100:
## check0=check0-1
## else:
## check1=check1-1
## check0=check0-ord(b[i])
## check0=check0 & 0xff
## check1=check1 & 0xff
## checksum=(long(check0)*0x1000000)+(long(check1)*0x10000)
## return checksum
def checksum_file(f):
return DUMMY_CHECKSUM # do it like gaim does, since the checksum
# formula doesn't work
## check0=check1=0x00ff
## i=0
## while 1:
## b=f.read()
## if not b: break
## for char in b:
## i=not i
## if i:
## if ord(char)>check1:
## check1=check1+0x100 # wrap
## if check0==0:
## check0=0x00ff
## if check1==0x100:
## check1=check1-1
## else:
## check0=check0-1
## check1=check1-ord(char)
## else:
## if ord(char)>check0: # wrap
## check0=check0+0x100
## if check1==0:
## check1=0x00ff
## if check0==0x100:
## check0=check0-1
## else:
## check1=check1-1
## check0=check0-ord(char)
## check0=check0 & 0xff
## check1=check1 & 0xff
## checksum=(long(check0)*0x1000000)+(long(check1)*0x10000)
## return checksum
def normalize(s):
s=string.lower(s)
s=string.replace(s," ","")
return s
class TOCParseError(ValueError):
pass
class TOC(protocol.Protocol):
users={}
def connectionMade(self):
# initialization of protocol
self._buf=""
self._ourseqnum=0L
self._theirseqnum=0L
self._mode="Flapon"
self._onlyflaps=0
self._laststatus={} # the last status for a user
self.username=None
self.permitmode=PERMITALL
self.permitlist=[]
self.denylist=[]
self.buddylist=[]
self.signontime=0
self.idletime=0
self.userinfo="<br>"
self.userclass=" O"
self.away=""
self.saved=None
def _debug(self,data):
log.msg(data)
def connectionLost(self, reason):
self._debug("dropped connection from %s" % self.username)
try:
del self.factory.users[self.username]
except:
pass
for k in self.factory.chatroom.keys():
try:
self.factory.chatroom[k].leave(self)
except TOCParseError:
pass
if self.saved:
self.factory.savedusers[self.username]=self.saved
self.updateUsers()
def sendFlap(self,type,data):
"""
send a FLAP to the client
"""
send="*"
self._debug(data)
if type==DATA:
data=data+"\000"
length=len(data)
send=send+struct.pack("!BHH",type,self._ourseqnum,length)
send=send+data
self._ourseqnum=self._ourseqnum+1
if self._ourseqnum>(256L**4):
self._ourseqnum=0
self.transport.write(send)
def dataReceived(self,data):
self._buf=self._buf+data
try:
func=getattr(self,"mode%s"%self._mode)
except:
return
self._mode=func()
if self._onlyflaps and self.isFlap(): self.dataReceived("")
def isFlap(self):
"""
tests to see if a flap is actually on the buffer
"""
if self._buf=='': return 0
if self._buf[0]!="*": return 0
if len(self._buf)<6: return 0
foo,type,seqnum,length=struct.unpack("!BBHH",self._buf[:6])
if type not in range(1,6): return 0
if len(self._buf)<6+length: return 0
return 1
def readFlap(self):
"""
read the first FLAP off self._buf, raising errors if it isn't in the right form.
the FLAP is the basic TOC message format, and is logically equivilant to a packet in TCP
"""
if self._buf=='': return None
if self._buf[0]!="*":
raise TOCParseError
if len(self._buf)<6: return None
foo,type,seqnum,length=struct.unpack("!BBHH",self._buf[:6])
if len(self._buf)<6+length: return None
data=self._buf[6:6+length]
self._buf=self._buf[6+length:]
if data and data[-1]=="\000":
data=data[:-1]
self._debug([type,data])
return [type,data]
#def modeWeb(self):
# try:
# line,rest=string.split(self._buf,"\n",1)
# get,username,http=string.split(line," ",2)
# except:
# return "Web" # not enough data
# foo,type,username=string.split(username,"/")
# if type=="info":
# user=self.factory.users[username]
# text="<HTML><HEAD><TITLE>User Information for %s</TITLE></HEAD><BODY>Username: <B>%s</B><br>\nWarning Level: <B>%s%</B><br>\n Online Since: <B>%s</B><br>\nIdle Minutes: <B>%s</B><br>\n<hr><br>\n%s\n<hr><br>\n"%(user.saved.nick, user.saved.nick, user.saved.evilness, time.asctime(user.signontime), int((time.time()-user.idletime)/60), user.userinfo)
# self.transport.write("HTTP/1.1 200 OK\n")
# self.transport.write("Content-Type: text/html\n")
# self.transport.write("Content-Length: %s\n\n"%len(text))
# self.transport.write(text)
# self.loseConnection()
def modeFlapon(self):
#if self._buf[:3]=="GET": self.modeWeb() # TODO: get this working
if len(self._buf)<10: return "Flapon" # not enough bytes
flapon,self._buf=self._buf[:10],self._buf[10:]
if flapon!="FLAPON\r\n\r\n":
raise TOCParseError
self.sendFlap(SIGNON,"\000\000\000\001")
self._onlyflaps=1
return "Signon"
def modeSignon(self):
flap=self.readFlap()
if flap==None:
return "Signon"
if flap[0]!=SIGNON: raise TOCParseError
version,tlv,unlength=struct.unpack("!LHH",flap[1][:8])
if version!=1 or tlv!=1 or unlength+8!=len(flap[1]):
raise TOCParseError
self.username=normalize(flap[1][8:])
if self.username in self.factory.savedusers.keys():
self.saved=self.factory.savedusers[self.username]
else:
self.saved=SavedUser()
self.saved.nick=self.username
return "TocSignon"
def modeTocSignon(self):
flap=self.readFlap()
if flap==None:
return "TocSignon"
if flap[0]!=DATA: raise TOCParseError
data=string.split(flap[1]," ")
if data[0]!="toc_signon": raise TOCParseError
for i in data:
if not i:data.remove(i)
password=unroast(data[4])
if not(self.authorize(data[1],int(data[2]),data[3],password)):
self.sendError(BAD_NICKNAME)
self.transport.loseConnection()
return
self.sendFlap(DATA,"SIGN_ON:TOC1.0")
self.sendFlap(DATA,"NICK:%s"%self.saved.nick)
self.sendFlap(DATA,"CONFIG:%s"%self.saved.config)
# sending user configuration goes here
return "Connected"
def authorize(self,server,port,username,password):
if self.saved.password=="":
self.saved.password=password
return 1
else:
return self.saved.password==password
def modeConnected(self):
flap=self.readFlap()
while flap!=None:
if flap[0] not in [DATA,KEEP_ALIVE]: raise TOCParseError
flapdata=string.split(flap[1]," ",1)
tocname=flapdata[0][4:]
if len(flapdata)==2:
data=flapdata[1]
else:
data=""
func=getattr(self,"toc_"+tocname,None)
if func!=None:
func(data)
else:
self.toc_unknown(tocname,data)
flap=self.readFlap()
return "Connected"
def toc_unknown(self,tocname,data):
self._debug("unknown! %s %s" % (tocname,data))
def toc_init_done(self,data):
"""
called when all the setup is done.
toc_init_done
"""
self.signontime=int(time.time())
self.factory.users[self.username]=self
self.updateUsers()
def toc_add_permit(self,data):
"""
adds users to the permit list. if the list is null, then set the mode to DENYALL
"""
if data=="":
self.permitmode=DENYALL
self.permitlist=[]
self.denylist=[]
else:
self.permitmode=PERMITSOME
self.denylist=[]
users=string.split(data," ")
map(self.permitlist.append,users)
self.updateUsers()
def toc_add_deny(self,data):
"""
adds users to the deny list. if the list is null, then set the mode to PERMITALL
"""
if data=="":
self.permitmode=PERMITALL
self.permitlist=[]
self.denylist=[]
else:
self.permitmode=DENYSOME
self.permitlist=[]
users=string.split(data," ")
map(self.denylist.append,users)
self.updateUsers()
def toc_evil(self,data):
"""
warns a user.
toc_evil <username> <anon|norm>
"""
username,nora=string.split(data," ")
if nora=="anon":
user=""
else:
user=self.saved.nick
if not(self.factory.users.has_key(username)):
self.sendError(CANT_WARN,username)
return
if self.factory.users[username].saved.evilness>=100:
self.sendError(CANT_WARN,username)
return
self.factory.users[username].evilFrom(user)
def toc_add_buddy(self,data):
"""
adds users to the buddy list
toc_add_buddy <buddyname1> [<buddyname2>] [<buddyname3>]...
"""
buddies=map(normalize,string.split(data," "))
for b in buddies:
if b not in self.buddylist:
self.buddylist.append(b)
for buddy in buddies:
try:
buddy=self.factory.users[buddy]
except:
pass
else:
self.buddyUpdate(buddy)
def toc_remove_buddy(self,data):
"""
removes users from the buddy list
toc_remove_buddy <buddyname1> [<buddyname2>] [<buddyname3>]...
"""
buddies=string.split(data," ")
for buddy in buddies:
try:
self.buddylist.remove(normalize(buddy))
except: pass
def toc_send_im(self,data):
"""
incoming instant message
toc_send_im <screenname> <quoted message> [auto]
"""
username,data=string.split(data," ",1)
auto=0
if data[-4:]=="auto":
auto=1
data=data[:-5]
data=unquote(data)
if not(self.factory.users.has_key(username)):
self.sendError(NOT_AVAILABLE,username)
return
user=self.factory.users[username]
if not(self.canContact(user)):
self.sendError(NOT_AVAILABLE,username)
return
user.hearWhisper(self,data,auto)
def toc_set_info(self,data):
"""
set the users information, retrivable with toc_get_info
toc_set_info <user info (quoted)>
"""
info=unquote(data)
self._userinfo=info
def toc_set_idle(self,data):
"""
set/unset idle
toc_set_idle <seconds>
"""
seconds=int(data)
self.idletime=time.time()-seconds # time when they started being idle
self.updateUsers()
def toc_set_away(self,data):
"""
set/unset away message
toc_set_away [<away message>]
"""
away=unquote(data)
if not self.away and away: # setting an away message
self.away=away
self.userclass=self.userclass+'U'
self.updateUsers()
elif self.away and not away: # coming back
self.away=""
self.userclass=self.userclass[:2]
self.updateUsers()
else:
raise TOCParseError
def toc_chat_join(self,data):
"""
joins the chat room.
toc_chat_join <exchange> <room name>
"""
exchange,name=string.split(data," ",1)
self.factory.getChatroom(int(exchange),unquote(name)).join(self)
def toc_chat_invite(self,data):
"""
invite others to the room.
toc_chat_invite <room id> <invite message> <buddy 1> [<buddy2>]...
"""
id,data=string.split(data," ",1)
id=int(id)
message,data=unquotebeg(data)
buddies=string.split(data," ")
for b in buddies:
room=self.factory.chatroom[id]
bud=self.factory.users[b]
bud.chatInvite(room,self,message)
def toc_chat_accept(self,data):
"""
accept an invitation.
toc_chat_accept <room id>
"""
id=int(data)
self.factory.chatroom[id].join(self)
def toc_chat_send(self,data):
"""
send a message to the chat room.
toc_chat_send <room id> <message>
"""
id,message=string.split(data," ",1)
id=int(id)
message=unquote(message)
self.factory.chatroom[id].say(self,message)
def toc_chat_whisper(self,data):
id,user,message=string.split(data," ",2)
id=int(id)
room=self.factory.chatroom[id]
message=unquote(message)
self.factory.users[user].chatWhisper(room,self,message)
def toc_chat_leave(self,data):
"""
leave the room.
toc_chat_leave <room id>
"""
id=int(data)
self.factory.chatroom[id].leave(self)
def toc_set_config(self,data):
"""
set the saved config. this gets send when you log in.
toc_set_config <config>
"""
self.saved.config=unquote(data)
def toc_get_info(self,data):
"""
get the user info for a user
toc_get_info <username>
"""
if not self.factory.users.has_key(data):
self.sendError(901,data)
return
self.sendFlap(2,"GOTO_URL:TIC:info/%s"%data)
def toc_format_nickname(self,data):
"""
change the format of your nickname.
toc_format_nickname <new format>
"""
# XXX may not work
nick=unquote(data)
if normalize(nick)==self.username:
self.saved.nick=nick
self.sendFlap(2,"ADMIN_NICK_STATUS:0")
else:
self.sendError(BAD_INPUT)
def toc_change_passwd(self,data):
orig,data=unquotebeg(data)
new=unquote(data)
if orig==self.saved.password:
self.saved.password=new
self.sendFlap(2,"ADMIN_PASSWD_STATUS:0")
else:
self.sendError(BAD_INPUT)
def sendError(self,code,*varargs):
"""
send an error to the user. listing of error messages is below.
"""
send="ERROR:%s"%code
for v in varargs:
send=send+":"+v
self.sendFlap(DATA,send)
def updateUsers(self):
"""
Update the users who have us on their buddylist.
Called when the user changes anything (idle,away) so people can get updates.
"""
for user in self.factory.users.values():
if self.username in user.buddylist and self.canContact(user):
user.buddyUpdate(self)
def getStatus(self,user):
if self.canContact(user):
if self in self.factory.users.values():ol='T'
else: ol='F'
idle=0
if self.idletime:
idle=int((time.time()-self.idletime)/60)
return (self.saved.nick,ol,self.saved.evilness,self.signontime,idle,self.userclass)
else:
return (self.saved.nick,'F',0,0,0,self.userclass)
def canContact(self,user):
if self.permitmode==PERMITALL: return 1
elif self.permitmode==DENYALL: return 0
elif self.permitmode==PERMITSOME:
if user.username in self.permitlist: return 1
else: return 0
elif self.permitmode==DENYSOME:
if user.username in self.denylist: return 0
else: return 1
else:
assert 0,"bad permitmode %s" % self.permitmode
def buddyUpdate(self,user):
"""
Update the buddy. Called from updateUsers()
"""
if not self.canContact(user): return
status=user.getStatus(self)
if not self._laststatus.has_key(user):
self._laststatus[user]=()
if self._laststatus[user]!=status:
send="UPDATE_BUDDY:%s:%s:%s:%s:%s:%s"%status
self.sendFlap(DATA,send)
self._laststatus[user]=status
def hearWhisper(self,user,data,auto=0):
"""
Called when you get an IM. If auto=1, it's an autoreply from an away message.
"""
if not self.canContact(user): return
if auto: auto='T'
else: auto='F'
send="IM_IN:%s:%s:%s"%(user.saved.nick,auto,data)
self.sendFlap(DATA,send)
def evilFrom(self,user):
if user=="":
percent=0.03
else:
percent=0.1
self.saved.evilness=self.saved.evilness+int((100-self.saved.evilness)*percent)
self.sendFlap(2,"EVILED:%s:%s"%(self.saved.evilness,user))
self.updateUsers()
def chatJoin(self,room):
self.sendFlap(2,"CHAT_JOIN:%s:%s"%(room.id,room.name))
f="CHAT_UPDATE_BUDDY:%s:T"%room.id
for u in room.users:
if u!=self:
u.chatUserUpdate(room,self)
f=f+":"+u.saved.nick
self.sendFlap(2,f)
def chatInvite(self,room,user,message):
if not self.canContact(user): return
self.sendFlap(2,"CHAT_INVITE:%s:%s:%s:%s"%(room.name,room.id,user.saved.nick,message))
def chatUserUpdate(self,room,user):
if user in room.users:
inroom='T'
else:
inroom='F'
self.sendFlap(2,"CHAT_UPDATE_BUDDY:%s:%s:%s"%(room.id,inroom,user.saved.nick))
def chatMessage(self,room,user,message):
if not self.canContact(user): return
self.sendFlap(2,"CHAT_IN:%s:%s:F:%s"%(room.id,user.saved.nick,message))
def chatWhisper(self,room,user,message):
if not self.canContact(user): return
self.sendFlap(2,"CHAT_IN:%s:%s:T:%s"%(room.id,user.saved.nick,message))
def chatLeave(self,room):
self.sendFlap(2,"CHAT_LEFT:%s"%(room.id))
class Chatroom:
def __init__(self,fac,exchange,name,id):
self.exchange=exchange
self.name=name
self.id=id
self.factory=fac
self.users=[]
def join(self,user):
if user in self.users:
return
self.users.append(user)
user.chatJoin(self)
def leave(self,user):
if user not in self.users:
raise TOCParseError
self.users.remove(user)
user.chatLeave(self)
for u in self.users:
u.chatUserUpdate(self,user)
if len(self.users)==0:
self.factory.remChatroom(self)
def say(self,user,message):
for u in self.users:
u.chatMessage(self,user,message)
class SavedUser:
def __init__(self):
self.config=""
self.nick=""
self.password=""
self.evilness=0
class TOCFactory(protocol.Factory):
def __init__(self):
self.users={}
self.savedusers={}
self.chatroom={}
self.chatroomid=0
def buildProtocol(self,addr):
p=TOC()
p.factory=self
return p
def getChatroom(self,exchange,name):
for i in self.chatroom.values():
if normalize(i.name)==normalize(name):
return i
self.chatroom[self.chatroomid]=Chatroom(self,exchange,name,self.chatroomid)
self.chatroomid=self.chatroomid+1
return self.chatroom[self.chatroomid-1]
def remChatroom(self,room):
id=room.id
del self.chatroom[id]
MAXARGS={}
MAXARGS["CONFIG"]=0
MAXARGS["NICK"]=0
MAXARGS["IM_IN"]=2
MAXARGS["UPDATE_BUDDY"]=5
MAXARGS["ERROR"]=-1
MAXARGS["EVILED"]=1
MAXARGS["CHAT_JOIN"]=1
MAXARGS["CHAT_IN"]=3
MAXARGS["CHAT_UPDATE_BUDDY"]=-1
MAXARGS["CHAT_INVITE"]=3
MAXARGS["CHAT_LEFT"]=0
MAXARGS["ADMIN_NICK_STATUS"]=0
MAXARGS["ADMIN_PASSWD_STATUS"]=0
class TOCClient(protocol.Protocol):
def __init__(self,username,password,authhost="login.oscar.aol.com",authport=5190):
self.username=normalize(username) # our username
self._password=password # our password
self._mode="SendNick" # current mode
self._ourseqnum=19071 # current sequence number (for sendFlap)
self._authhost=authhost # authorization host
self._authport=authport # authorization port
self._online=0 # are we online?
self._buddies=[] # the current buddy list
self._privacymode=PERMITALL # current privacy mode
self._permitlist=[] # list of users on the permit list
self._roomnames={} # the names for each of the rooms we're in
self._receivedchatmembers={} # have we gotten who's in our room yet?
self._denylist=[]
self._cookies={} # for file transfers
self._buf='' # current data buffer
self._awaymessage=''
def _debug(self,data):
log.msg(data)
def sendFlap(self,type,data):
if type==DATA:
data=data+"\000"
length=len(data)
s="*"
s=s+struct.pack("!BHH",type,self._ourseqnum,length)
s=s+data
self._ourseqnum=self._ourseqnum+1
if self._ourseqnum>(256*256+256):
self._ourseqnum=0
self._debug(data)
self.transport.write(s)
def isFlap(self):
"""
tests to see if a flap is actually on the buffer
"""
if self._buf=='': return 0
if self._buf[0]!="*": return 0
if len(self._buf)<6: return 0
foo,type,seqnum,length=struct.unpack("!BBHH",self._buf[:6])
if type not in range(1,6): return 0
if len(self._buf)<6+length: return 0
return 1
def readFlap(self):
if self._buf=='': return None
if self._buf[0]!="*":
raise TOCParseError
if len(self._buf)<6: return None
foo,type,seqnum,length=struct.unpack("!BBHH",self._buf[:6])
if len(self._buf)<6+length: return None
data=self._buf[6:6+length]
self._buf=self._buf[6+length:]
if data and data[-1]=="\000":
data=data[:-1]
return [type,data]
def connectionMade(self):
self._debug("connection made! %s" % self.transport)
self.transport.write("FLAPON\r\n\r\n")
def connectionLost(self, reason):
self._debug("connection lost!")
self._online=0
def dataReceived(self,data):
self._buf=self._buf+data
while self.isFlap():
flap=self.readFlap()
func=getattr(self,"mode%s"%self._mode)
func(flap)
def modeSendNick(self,flap):
if flap!=[1,"\000\000\000\001"]: raise TOCParseError
s="\000\000\000\001\000\001"+struct.pack("!H",len(self.username))+self.username
self.sendFlap(1,s)
s="toc_signon %s %s %s %s english \"penguin\""%(self._authhost,\
self._authport,self.username,roast(self._password))
self.sendFlap(2,s)
self._mode="Data"
def modeData(self,flap):
if not flap[1]:
return
if not ':' in flap[1]:
self._debug("bad SNAC:%s"%(flap[1]))
return
command,rest=string.split(flap[1],":",1)
if MAXARGS.has_key(command):
maxsplit=MAXARGS[command]
else:
maxsplit=-1
if maxsplit==-1:
l=tuple(string.split(rest,":"))
elif maxsplit==0:
l=(rest,)
else:
l=tuple(string.split(rest,":",maxsplit))
self._debug("%s %s"%(command,l))
try:
func=getattr(self,"toc%s"%command)
self._debug("calling %s"%func)
except:
self._debug("calling %s"%self.tocUNKNOWN)
self.tocUNKNOWN(command,l)
return
func(l)
def tocUNKNOWN(self,command,data):
pass
def tocSIGN_ON(self,data):
if data!=("TOC1.0",): raise TOCParseError
self._debug("Whee, signed on!")
if self._buddies: self.add_buddy(self._buddies)
self._online=1
self.onLine()
def tocNICK(self,data):
"""
Handle a message that looks like::
NICK:<format of nickname>
"""
self.username=data[0]
def tocCONFIG(self,data):
"""
Handle a message that looks like::
CONFIG:<config>
Format of config data:
- g: group. all users until next g or end of config are in this group
- b: buddy
- p: person on the permit list
- d: person on the deny list
- m: permit/deny mode (1: permit all, 2: deny all, 3: permit some, 4: deny some)
"""
data=data[0]
if data and data[0]=="{":data=data[1:-1]
lines=string.split(data,"\n")
buddylist={}
currentgroup=""
permit=[]
deny=[]
mode=1
for l in lines:
if l:
code,data=l[0],l[2:]
if code=='g': # group
currentgroup=data
buddylist[currentgroup]=[]
elif code=='b':
buddylist[currentgroup].append(data)
elif code=='p':
permit.append(data)
elif code=='d':
deny.append(data)
elif code=='m':
mode=int(data)
self.gotConfig(mode,buddylist,permit,deny)
def tocIM_IN(self,data):
"""
Handle a message that looks like::
IM_IN:<user>:<autoreply T|F>:message
"""
user=data[0]
autoreply=(data[1]=='T')
message=data[2]
self.hearMessage(user,message,autoreply)
def tocUPDATE_BUDDY(self,data):
"""
Handle a message that looks like::
UPDATE_BUDDY:<username>:<online T|F>:<warning level>:<signon time>:<idle time (minutes)>:<user class>
"""
data=list(data)
online=(data[1]=='T')
if len(data[5])==2:
data[5]=data[5]+" "
away=(data[5][-1]=='U')
if data[5][-1]=='U':
data[5]=data[5][:-1]
self.updateBuddy(data[0],online,int(data[2]),int(data[3]),int(data[4]),data[5],away)
def tocERROR(self,data):
"""
Handle a message that looks like::
ERROR:<error code>:<misc. data>
"""
code,args=data[0],data[1:]
self.hearError(int(code),args)
def tocEVILED(self,data):
"""
Handle a message that looks like::
EVILED:<current warning level>:<user who warned us>
"""
self.hearWarning(data[0],data[1])
def tocCHAT_JOIN(self,data):
"""
Handle a message that looks like::
CHAT_JOIN:<room id>:<room name>
"""
#self.chatJoined(int(data[0]),data[1])
self._roomnames[int(data[0])]=data[1]
self._receivedchatmembers[int(data[0])]=0
def tocCHAT_UPDATE_BUDDY(self,data):
"""
Handle a message that looks like::
CHAT_UPDATE_BUDDY:<room id>:<in room? T/F>:<user 1>:<user 2>...
"""
roomid=int(data[0])
inroom=(data[1]=='T')
if self._receivedchatmembers[roomid]:
for u in data[2:]:
self.chatUpdate(roomid,u,inroom)
else:
self._receivedchatmembers[roomid]=1
self.chatJoined(roomid,self._roomnames[roomid],list(data[2:]))
def tocCHAT_IN(self,data):
"""
Handle a message that looks like::
CHAT_IN:<room id>:<username>:<whisper T/F>:<message>
whisper isn't used
"""
whisper=(data[2]=='T')
if whisper:
self.chatHearWhisper(int(data[0]),data[1],data[3])
else:
self.chatHearMessage(int(data[0]),data[1],data[3])
def tocCHAT_INVITE(self,data):
"""
Handle a message that looks like::
CHAT_INVITE:<room name>:<room id>:<username>:<message>
"""
self.chatInvited(int(data[1]),data[0],data[2],data[3])
def tocCHAT_LEFT(self,data):
"""
Handle a message that looks like::
CHAT_LEFT:<room id>
"""
self.chatLeft(int(data[0]))
del self._receivedchatmembers[int(data[0])]
del self._roomnames[int(data[0])]
def tocRVOUS_PROPOSE(self,data):
"""
Handle a message that looks like::
RVOUS_PROPOSE:<user>:<uuid>:<cookie>:<seq>:<rip>:<pip>:<vip>:<port>
[:tlv tag1:tlv value1[:tlv tag2:tlv value2[:...]]]
"""
user,uid,cookie,seq,rip,pip,vip,port=data[:8]
cookie=base64.decodestring(cookie)
port=int(port)
tlvs={}
for i in range(8,len(data),2):
key=data[i]
value=base64.decodestring(data[i+1])
tlvs[key]=value
name=UUIDS[uid]
try:
func=getattr(self,"toc%s"%name)
except:
self._debug("no function for UID %s" % uid)
return
func(user,cookie,seq,pip,vip,port,tlvs)
def tocSEND_FILE(self,user,cookie,seq,pip,vip,port,tlvs):
if tlvs.has_key('12'):
description=tlvs['12']
else:
description=""
subtype,numfiles,size=struct.unpack("!HHI",tlvs['10001'][:8])
name=tlvs['10001'][8:-4]
while name[-1]=='\000':
name=name[:-1]
self._cookies[cookie]=[user,SEND_FILE_UID,pip,port,{'name':name}]
self.rvousProposal("send",cookie,user,vip,port,description=description,
name=name,files=numfiles,size=size)
def tocGET_FILE(self,user,cookie,seq,pip,vip,port,tlvs):
return
# XXX add this back in
#reactor.clientTCP(pip,port,GetFileTransfer(self,cookie,os.path.expanduser("~")))
#self.rvous_accept(user,cookie,GET_FILE_UID)
def onLine(self):
"""
called when we are first online
"""
pass
def gotConfig(self,mode,buddylist,permit,deny):
"""
called when we get a configuration from the server
mode := permit/deny mode
buddylist := current buddylist
permit := permit list
deny := deny list
"""
pass
def hearError(self,code,args):
"""
called when an error is received
code := error code
args := misc. arguments (username, etc.)
"""
pass
def hearWarning(self,newamount,username):
"""
called when we get warned
newamount := the current warning level
username := the user who warned us, or '' if it's anonymous
"""
pass
def hearMessage(self,username,message,autoreply):
"""
called when you receive an IM
username := the user who the IM is from
message := the message
autoreply := true if the message is an autoreply from an away message
"""
pass
def updateBuddy(self,username,online,evilness,signontime,idletime,userclass,away):
"""
called when a buddy changes state
username := the user whos state changed
online := true if the user is online
evilness := the users current warning level
signontime := the time the user signed on (UNIX epoch)
idletime := the time the user has been idle (minutes)
away := true if the user is away
userclass := the class of the user (generally " O")
"""
pass
def chatJoined(self,roomid,roomname,users):
"""
we just joined a chat room
roomid := the AIM id for the room
roomname := the name for the room
users := a list of the users already in the room
"""
pass
def chatUpdate(self,roomid,username,inroom):
"""
a user has joined the room
roomid := the AIM id for the room
username := the username
inroom := true if the user is in the room
"""
pass
def chatHearMessage(self,roomid,username,message):
"""
a message was sent to the room
roomid := the AIM id for the room
username := the user who sent the message
message := the message
"""
pass
def chatHearWhisper(self,roomid,username,message):
"""
someone whispered to us in a chatroom
roomid := the AIM for the room
username := the user who whispered to us
message := the message
"""
pass
def chatInvited(self,roomid,roomname,username,message):
"""
we were invited to a chat room
roomid := the AIM id for the room
roomname := the name of the room
username := the user who invited us
message := the invite message
"""
pass
def chatLeft(self,roomid):
"""
we left the room
roomid := the AIM id for the room
"""
pass
def rvousProposal(self,type,cookie,user,vip,port,**kw):
"""
we were asked for a rondevouz
type := the type of rondevous. currently, one of ["send"]
cookie := the cookie. pass this to rvous_accept()
user := the user who asked us
vip := their verified_ip
port := the port they want us to conenct to
kw := misc. args
"""
pass #self.rvous_accept(cookie)
def receiveBytes(self,user,file,chunk,sofar,total):
"""
we received part of a file from a file transfer
file := the name of the file
chunk := the chunk of data
sofar := how much data we've gotten so far
total := the total amount of data
"""
pass #print user,file,sofar,total
def isaway(self):
"""
return our away status
"""
return len(self._awaymessage)>0
def set_config(self,mode,buddylist,permit,deny):
"""
set the server configuration
mode := permit mode
buddylist := buddy list
permit := permit list
deny := deny list
"""
s="m %s\n"%mode
for g in buddylist.keys():
s=s+"g %s\n"%g
for u in buddylist[g]:
s=s+"b %s\n"%u
for p in permit:
s=s+"p %s\n"%p
for d in deny:
s=s+"d %s\n"%d
#s="{\n"+s+"\n}"
self.sendFlap(2,"toc_set_config %s"%quote(s))
def add_buddy(self,buddies):
s=""
if type(buddies)==type(""): buddies=[buddies]
for b in buddies:
s=s+" "+normalize(b)
self.sendFlap(2,"toc_add_buddy%s"%s)
def del_buddy(self,buddies):
s=""
if type(buddies)==type(""): buddies=[buddies]
for b in buddies:
s=s+" "+b
self.sendFlap(2,"toc_remove_buddy%s"%s)
def add_permit(self,users):
if type(users)==type(""): users=[users]
s=""
if self._privacymode!=PERMITSOME:
self._privacymode=PERMITSOME
self._permitlist=[]
for u in users:
u=normalize(u)
if u not in self._permitlist:self._permitlist.append(u)
s=s+" "+u
if not s:
self._privacymode=DENYALL
self._permitlist=[]
self._denylist=[]
self.sendFlap(2,"toc_add_permit"+s)
def del_permit(self,users):
if type(users)==type(""): users=[users]
p=self._permitlist[:]
for u in users:
u=normalize(u)
if u in p:
p.remove(u)
self.add_permit([])
self.add_permit(p)
def add_deny(self,users):
if type(users)==type(""): users=[users]
s=""
if self._privacymode!=DENYSOME:
self._privacymode=DENYSOME
self._denylist=[]
for u in users:
u=normalize(u)
if u not in self._denylist:self._denylist.append(u)
s=s+" "+u
if not s:
self._privacymode=PERMITALL
self._permitlist=[]
self._denylist=[]
self.sendFlap(2,"toc_add_deny"+s)
def del_deny(self,users):
if type(users)==type(""): users=[users]
d=self._denylist[:]
for u in users:
u=normalize(u)
if u in d:
d.remove(u)
self.add_deny([])
if d:
self.add_deny(d)
def signon(self):
"""
called to finish the setup, and signon to the network
"""
self.sendFlap(2,"toc_init_done")
self.sendFlap(2,"toc_set_caps %s" % (SEND_FILE_UID,)) # GET_FILE_UID)
def say(self,user,message,autoreply=0):
"""
send a message
user := the user to send to
message := the message
autoreply := true if the message is an autoreply (good for away messages)
"""
if autoreply: a=" auto"
else: a=''
self.sendFlap(2,"toc_send_im %s %s%s"%(normalize(user),quote(message),a))
def idle(self,idletime=0):
"""
change idle state
idletime := the seconds that the user has been away, or 0 if they're back
"""
self.sendFlap(2,"toc_set_idle %s" % int(idletime))
def evil(self,user,anon=0):
"""
warn a user
user := the user to warn
anon := if true, an anonymous warning
"""
self.sendFlap(2,"toc_evil %s %s"%(normalize(user), (not anon and "anon") or "norm"))
def away(self,message=''):
"""
change away state
message := the message, or '' to come back from awayness
"""
self._awaymessage=message
if message:
message=' '+quote(message)
self.sendFlap(2,"toc_set_away%s"%message)
def chat_join(self,exchange,roomname):
"""
join a chat room
exchange := should almost always be 4
roomname := room name
"""
roomname=string.replace(roomname," ","")
self.sendFlap(2,"toc_chat_join %s %s"%(int(exchange),roomname))
def chat_say(self,roomid,message):
"""
send a message to a chatroom
roomid := the AIM id for the room
message := the message to send
"""
self.sendFlap(2,"toc_chat_send %s %s"%(int(roomid),quote(message)))
def chat_whisper(self,roomid,user,message):
"""
whisper to another user in a chatroom
roomid := the AIM id for the room
user := the user to whisper to
message := the message to send
"""
self.sendFlap(2,"toc_chat_whisper %s %s %s"%(int(roomid),normalize(user),quote(message)))
def chat_leave(self,roomid):
"""
leave a chat room.
roomid := the AIM id for the room
"""
self.sendFlap(2,"toc_chat_leave %s" % int(roomid))
def chat_invite(self,roomid,usernames,message):
"""
invite a user[s] to the chat room
roomid := the AIM id for the room
usernames := either a string (one username) or a list (more than one)
message := the message to invite them with
"""
if type(usernames)==type(""): # a string, one username
users=usernames
else:
users=""
for u in usernames:
users=users+u+" "
users=users[:-1]
self.sendFlap(2,"toc_chat_invite %s %s %s" % (int(roomid),quote(message),users))
def chat_accept(self,roomid):
"""
accept an invite to a chat room
roomid := the AIM id for the room
"""
self.sendFlap(2,"toc_chat_accept %s"%int(roomid))
def rvous_accept(self,cookie):
user,uuid,pip,port,d=self._cookies[cookie]
self.sendFlap(2,"toc_rvous_accept %s %s %s" % (normalize(user),
cookie,uuid))
if uuid==SEND_FILE_UID:
protocol.ClientCreator(reactor, SendFileTransfer,self,cookie,user,d["name"]).connectTCP(pip,port)
def rvous_cancel(self,cookie):
user,uuid,pip,port,d=self._cookies[cookie]
self.sendFlap(2,"toc_rvous_accept %s %s %s" % (normalize(user),
cookie,uuid))
del self._cookies[cookie]
class SendFileTransfer(protocol.Protocol):
header_fmt="!4s2H8s6H10I32s3c69s16s2H64s"
def __init__(self,client,cookie,user,filename):
self.client=client
self.cookie=cookie
self.user=user
self.filename=filename
self.hdr=[0,0,0]
self.sofar=0
def dataReceived(self,data):
if not self.hdr[2]==0x202:
self.hdr=list(struct.unpack(self.header_fmt,data[:256]))
self.hdr[2]=0x202
self.hdr[3]=self.cookie
self.hdr[4]=0
self.hdr[5]=0
self.transport.write(apply(struct.pack,[self.header_fmt]+self.hdr))
data=data[256:]
if self.hdr[6]==1:
self.name=self.filename
else:
self.name=self.filename+self.hdr[-1]
while self.name[-1]=="\000":
self.name=self.name[:-1]
if not data: return
self.sofar=self.sofar+len(data)
self.client.receiveBytes(self.user,self.name,data,self.sofar,self.hdr[11])
if self.sofar==self.hdr[11]: # end of this file
self.hdr[2]=0x204
self.hdr[7]=self.hdr[7]-1
self.hdr[9]=self.hdr[9]-1
self.hdr[19]=DUMMY_CHECKSUM # XXX really calculate this
self.hdr[18]=self.hdr[18]+1
self.hdr[21]="\000"
self.transport.write(apply(struct.pack,[self.header_fmt]+self.hdr))
self.sofar=0
if self.hdr[7]==0:
self.transport.loseConnection()
class GetFileTransfer(protocol.Protocol):
header_fmt="!4s 2H 8s 6H 10I 32s 3c 69s 16s 2H 64s"
def __init__(self,client,cookie,dir):
self.client=client
self.cookie=cookie
self.dir=dir
self.buf=""
def connectionMade(self):
def func(f,path,names):
names.sort(lambda x,y:cmp(string.lower(x),string.lower(y)))
for n in names:
name=os.path.join(path,n)
lt=time.localtime(os.path.getmtime(name))
size=os.path.getsize(name)
f[1]=f[1]+size
f.append("%02d/%02d/%4d %02d:%02d %8d %s" %
(lt[1],lt[2],lt[0],lt[3],lt[4],size,name[f[0]:]))
f=[len(self.dir)+1,0]
os.path.walk(self.dir,func,f)
size=f[1]
self.listing=string.join(f[2:],"\r\n")+"\r\n"
open("\\listing.txt","w").write(self.listing)
hdr=["OFT2",256,0x1108,self.cookie,0,0,len(f)-2,len(f)-2,1,1,size,
len(self.listing),os.path.getmtime(self.dir),
checksum(self.listing),0,0,0,0,0,0,"OFT_Windows ICBMFT V1.1 32",
"\002",chr(0x1a),chr(0x10),"","",0,0,""]
self.transport.write(apply(struct.pack,[self.header_fmt]+hdr))
def dataReceived(self,data):
self.buf=self.buf+data
while len(self.buf)>=256:
hdr=list(struct.unpack(self.header_fmt,self.buf[:256]))
self.buf=self.buf[256:]
if hdr[2]==0x1209:
self.file=StringIO.StringIO(self.listing)
self.transport.registerProducer(self,0)
elif hdr[2]==0x120b: pass
elif hdr[2]==0x120c: # file request
file=hdr[-1]
for k,v in [["\000",""],["\001",os.sep]]:
file=string.replace(file,k,v)
self.name=os.path.join(self.dir,file)
self.file=open(self.name,'rb')
hdr[2]=0x0101
hdr[6]=hdr[7]=1
hdr[10]=hdr[11]=os.path.getsize(self.name)
hdr[12]=os.path.getmtime(self.name)
hdr[13]=checksum_file(self.file)
self.file.seek(0)
hdr[18]=hdr[19]=0
hdr[21]=chr(0x20)
self.transport.write(apply(struct.pack,[self.header_fmt]+hdr))
log.msg("got file request for %s"%file,hex(hdr[13]))
elif hdr[2]==0x0202:
log.msg("sending file")
self.transport.registerProducer(self,0)
elif hdr[2]==0x0204:
log.msg("real checksum: %s"%hex(hdr[19]))
del self.file
elif hdr[2]==0x0205: # resume
already=hdr[18]
if already:
data=self.file.read(already)
else:
data=""
log.msg("restarting at %s"%already)
hdr[2]=0x0106
hdr[19]=checksum(data)
self.transport.write(apply(struct.pack,[self.header_fmt]+hdr))
elif hdr[2]==0x0207:
self.transport.registerProducer(self,0)
else:
log.msg("don't understand 0x%04x"%hdr[2])
log.msg(hdr)
def resumeProducing(self):
data=self.file.read(4096)
log.msg(len(data))
if not data:
self.transport.unregisterProducer()
self.transport.write(data)
def pauseProducing(self): pass
def stopProducing(self): del self.file
# UUIDs
SEND_FILE_UID = "09461343-4C7F-11D1-8222-444553540000"
GET_FILE_UID = "09461348-4C7F-11D1-8222-444553540000"
UUIDS={
SEND_FILE_UID:"SEND_FILE",
GET_FILE_UID:"GET_FILE"
}
# ERRORS
# general
NOT_AVAILABLE=901
CANT_WARN=902
MESSAGES_TOO_FAST=903
# admin
BAD_INPUT=911
BAD_ACCOUNT=912
REQUEST_ERROR=913
SERVICE_UNAVAILABLE=914
# chat
NO_CHAT_IN=950
# im and info
SEND_TOO_FAST=960
MISSED_BIG_IM=961
MISSED_FAST_IM=962
# directory
DIR_FAILURE=970
TOO_MANY_MATCHES=971
NEED_MORE_QUALIFIERS=972
DIR_UNAVAILABLE=973
NO_EMAIL_LOOKUP=974
KEYWORD_IGNORED=975
NO_KEYWORDS=976
BAD_LANGUAGE=977
BAD_COUNTRY=978
DIR_FAIL_UNKNOWN=979
# authorization
BAD_NICKNAME=980
SERVICE_TEMP_UNAVAILABLE=981
WARNING_TOO_HIGH=982
CONNECTING_TOO_QUICK=983
UNKNOWN_SIGNON=989
STD_MESSAGE={}
STD_MESSAGE[NOT_AVAILABLE]="%s not currently available"
STD_MESSAGE[CANT_WARN]="Warning of %s not currently available"
STD_MESSAGE[MESSAGES_TOO_FAST]="A message has been dropped, you are exceeding the server speed limit"
STD_MESSAGE[BAD_INPUT]="Error validating input"
STD_MESSAGE[BAD_ACCOUNT]="Invalid account"
STD_MESSAGE[REQUEST_ERROR]="Error encountered while processing request"
STD_MESSAGE[SERVICE_UNAVAILABLE]="Service unavailable"
STD_MESSAGE[NO_CHAT_IN]="Chat in %s is unavailable"
STD_MESSAGE[SEND_TOO_FAST]="You are sending messages too fast to %s"
STD_MESSAGE[MISSED_BIG_IM]="You missed an IM from %s because it was too big"
STD_MESSAGE[MISSED_FAST_IM]="You missed an IM from %s because it was sent too fast"
# skipping directory for now
STD_MESSAGE[BAD_NICKNAME]="Incorrect nickname or password"
STD_MESSAGE[SERVICE_TEMP_UNAVAILABLE]="The service is temporarily unavailable"
STD_MESSAGE[WARNING_TOO_HIGH]="Your warning level is currently too high to sign on"
STD_MESSAGE[CONNECTING_TOO_QUICK]="You have been connecting and disconnecting too frequently. Wait 10 minutes and try again. If you continue to try, you will need to wait even longer."
STD_MESSAGE[UNKNOWN_SIGNON]="An unknown signon error has occurred %s" | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/protocols/toc.py | toc.py |
__version__ = '$Revision: 1.94 $'[11:-2]
from twisted.internet import reactor, protocol
from twisted.persisted import styles
from twisted.protocols import basic
from twisted.python import log, reflect, text
# System Imports
import errno
import os
import random
import re
import stat
import string
import struct
import sys
import time
import types
import traceback
import socket
from os import path
NUL = chr(0)
CR = chr(015)
NL = chr(012)
LF = NL
SPC = chr(040)
CHANNEL_PREFIXES = '&#!+'
class IRCBadMessage(Exception):
pass
class IRCPasswordMismatch(Exception):
pass
def parsemsg(s):
"""Breaks a message from an IRC server into its prefix, command, and arguments.
"""
prefix = ''
trailing = []
if not s:
raise IRCBadMessage("Empty line.")
if s[0] == ':':
prefix, s = s[1:].split(' ', 1)
if s.find(' :') != -1:
s, trailing = s.split(' :', 1)
args = s.split()
args.append(trailing)
else:
args = s.split()
command = args.pop(0)
return prefix, command, args
def split(str, length = 80):
"""I break a message into multiple lines.
I prefer to break at whitespace near str[length]. I also break at \\n.
@returns: list of strings
"""
if length <= 0:
raise ValueError("Length must be a number greater than zero")
r = []
while len(str) > length:
w, n = str[:length].rfind(' '), str[:length].find('\n')
if w == -1 and n == -1:
line, str = str[:length], str[length:]
else:
i = n == -1 and w or n
line, str = str[:i], str[i+1:]
r.append(line)
if len(str):
r.extend(str.split('\n'))
return r
class IRC(protocol.Protocol):
"""Internet Relay Chat server protocol.
"""
buffer = ""
hostname = None
encoding = None
def connectionMade(self):
self.channels = []
if self.hostname is None:
self.hostname = socket.getfqdn()
def sendLine(self, line):
if self.encoding is not None:
if isinstance(line, unicode):
line = line.encode(self.encoding)
self.transport.write("%s%s%s" % (line, CR, LF))
def sendMessage(self, command, *parameter_list, **prefix):
"""Send a line formatted as an IRC message.
First argument is the command, all subsequent arguments
are parameters to that command. If a prefix is desired,
it may be specified with the keyword argument 'prefix'.
"""
if not command:
raise ValueError, "IRC message requires a command."
if ' ' in command or command[0] == ':':
# Not the ONLY way to screw up, but provides a little
# sanity checking to catch likely dumb mistakes.
raise ValueError, "Somebody screwed up, 'cuz this doesn't" \
" look like a command to me: %s" % command
line = string.join([command] + list(parameter_list))
if prefix.has_key('prefix'):
line = ":%s %s" % (prefix['prefix'], line)
self.sendLine(line)
if len(parameter_list) > 15:
log.msg("Message has %d parameters (RFC allows 15):\n%s" %
(len(parameter_list), line))
def dataReceived(self, data):
"""This hack is to support mIRC, which sends LF only,
even though the RFC says CRLF. (Also, the flexibility
of LineReceiver to turn "line mode" on and off was not
required.)
"""
lines = (self.buffer + data).split(LF)
# Put the (possibly empty) element after the last LF back in the
# buffer
self.buffer = lines.pop()
for line in lines:
if len(line) <= 2:
# This is a blank line, at best.
continue
if line[-1] == CR:
line = line[:-1]
prefix, command, params = parsemsg(line)
# mIRC is a big pile of doo-doo
command = command.upper()
# DEBUG: log.msg( "%s %s %s" % (prefix, command, params))
self.handleCommand(command, prefix, params)
def handleCommand(self, command, prefix, params):
"""Determine the function to call for the given command and call
it with the given arguments.
"""
method = getattr(self, "irc_%s" % command, None)
try:
if method is not None:
method(prefix, params)
else:
self.irc_unknown(prefix, command, params)
except:
log.deferr()
def irc_unknown(self, prefix, command, params):
"""Implement me!"""
raise NotImplementedError(command, prefix, params)
# Helper methods
def privmsg(self, sender, recip, message):
"""Send a message to a channel or user
@type sender: C{str} or C{unicode}
@param sender: Who is sending this message. Should be of the form
username!ident@hostmask (unless you know better!).
@type recip: C{str} or C{unicode}
@param recip: The recipient of this message. If a channel, it
must start with a channel prefix.
@type message: C{str} or C{unicode}
@param message: The message being sent.
"""
self.sendLine(":%s PRIVMSG %s :%s" % (sender, recip, lowQuote(message)))
def notice(self, sender, recip, message):
"""Send a \"notice\" to a channel or user.
Notices differ from privmsgs in that the RFC claims they are different.
Robots are supposed to send notices and not respond to them. Clients
typically display notices differently from privmsgs.
@type sender: C{str} or C{unicode}
@param sender: Who is sending this message. Should be of the form
username!ident@hostmask (unless you know better!).
@type recip: C{str} or C{unicode}
@param recip: The recipient of this message. If a channel, it
must start with a channel prefix.
@type message: C{str} or C{unicode}
@param message: The message being sent.
"""
self.sendLine(":%s NOTICE %s :%s" % (sender, recip, message))
def action(self, sender, recip, message):
"""Send an action to a channel or user.
@type sender: C{str} or C{unicode}
@param sender: Who is sending this message. Should be of the form
username!ident@hostmask (unless you know better!).
@type recip: C{str} or C{unicode}
@param recip: The recipient of this message. If a channel, it
must start with a channel prefix.
@type message: C{str} or C{unicode}
@param message: The action being sent.
"""
self.sendLine(":%s ACTION %s :%s" % (sender, recip, message))
def topic(self, user, channel, topic, author=None):
"""Send the topic to a user.
@type user: C{str} or C{unicode}
@param user: The user receiving the topic. Only their nick name, not
the full hostmask.
@type channel: C{str} or C{unicode}
@param channel: The channel for which this is the topic.
@type topic: C{str} or C{unicode} or C{None}
@param topic: The topic string, unquoted, or None if there is
no topic.
@type author: C{str} or C{unicode}
@param author: If the topic is being changed, the full username and hostmask
of the person changing it.
"""
if author is None:
if topic is None:
self.sendLine(':%s %s %s %s :%s' % (
self.hostname, RPL_NOTOPIC, user, channel, 'No topic is set.'))
else:
self.sendLine(":%s %s %s %s :%s" % (
self.hostname, RPL_TOPIC, user, channel, lowQuote(topic)))
else:
self.sendLine(":%s TOPIC %s :%s" % (author, channel, lowQuote(topic)))
def topicAuthor(self, user, channel, author, date):
"""
Send the author of and time at which a topic was set for the given
channel.
This sends a 333 reply message, which is not part of the IRC RFC.
@type user: C{str} or C{unicode}
@param user: The user receiving the topic. Only their nick name, not
the full hostmask.
@type channel: C{str} or C{unicode}
@param channel: The channel for which this information is relevant.
@type author: C{str} or C{unicode}
@param author: The nickname (without hostmask) of the user who last
set the topic.
@type date: C{int}
@param date: A POSIX timestamp (number of seconds since the epoch)
at which the topic was last set.
"""
self.sendLine(':%s %d %s %s %s %d' % (
self.hostname, 333, user, channel, author, date))
def names(self, user, channel, names):
"""Send the names of a channel's participants to a user.
@type user: C{str} or C{unicode}
@param user: The user receiving the name list. Only their nick
name, not the full hostmask.
@type channel: C{str} or C{unicode}
@param channel: The channel for which this is the namelist.
@type names: C{list} of C{str} or C{unicode}
@param names: The names to send.
"""
# XXX If unicode is given, these limits are not quite correct
prefixLength = len(channel) + len(user) + 10
namesLength = 512 - prefixLength
L = []
count = 0
for n in names:
if count + len(n) + 1 > namesLength:
self.sendLine(":%s %s %s = %s :%s" % (
self.hostname, RPL_NAMREPLY, user, channel, ' '.join(L)))
L = [n]
count = len(n)
else:
L.append(n)
count += len(n) + 1
if L:
self.sendLine(":%s %s %s = %s :%s" % (
self.hostname, RPL_NAMREPLY, user, channel, ' '.join(L)))
self.sendLine(":%s %s %s %s :End of /NAMES list" % (
self.hostname, RPL_ENDOFNAMES, user, channel))
def who(self, user, channel, memberInfo):
"""
Send a list of users participating in a channel.
@type user: C{str} or C{unicode}
@param user: The user receiving this member information. Only their
nick name, not the full hostmask.
@type channel: C{str} or C{unicode}
@param channel: The channel for which this is the member
information.
@type memberInfo: C{list} of C{tuples}
@param memberInfo: For each member of the given channel, a 7-tuple
containing their username, their hostmask, the server to which they
are connected, their nickname, the letter "H" or "G" (wtf do these
mean?), the hopcount from C{user} to this member, and this member's
real name.
"""
for info in memberInfo:
(username, hostmask, server, nickname, flag, hops, realName) = info
assert flag in ("H", "G")
self.sendLine(":%s %s %s %s %s %s %s %s %s :%d %s" % (
self.hostname, RPL_WHOREPLY, user, channel,
username, hostmask, server, nickname, flag, hops, realName))
self.sendLine(":%s %s %s %s :End of /WHO list." % (
self.hostname, RPL_ENDOFWHO, user, channel))
def whois(self, user, nick, username, hostname, realName, server, serverInfo, oper, idle, signOn, channels):
"""
Send information about the state of a particular user.
@type user: C{str} or C{unicode}
@param user: The user receiving this information. Only their nick
name, not the full hostmask.
@type nick: C{str} or C{unicode}
@param nick: The nickname of the user this information describes.
@type username: C{str} or C{unicode}
@param username: The user's username (eg, ident response)
@type hostname: C{str}
@param hostname: The user's hostmask
@type realName: C{str} or C{unicode}
@param realName: The user's real name
@type server: C{str} or C{unicode}
@param server: The name of the server to which the user is connected
@type serverInfo: C{str} or C{unicode}
@param serverInfo: A descriptive string about that server
@type oper: C{bool}
@param oper: Indicates whether the user is an IRC operator
@type idle: C{int}
@param idle: The number of seconds since the user last sent a message
@type signOn: C{int}
@param signOn: A POSIX timestamp (number of seconds since the epoch)
indicating the time the user signed on
@type channels: C{list} of C{str} or C{unicode}
@param channels: A list of the channels which the user is participating in
"""
self.sendLine(":%s %s %s %s %s %s * :%s" % (
self.hostname, RPL_WHOISUSER, user, nick, username, hostname, realName))
self.sendLine(":%s %s %s %s %s :%s" % (
self.hostname, RPL_WHOISSERVER, user, nick, server, serverInfo))
if oper:
self.sendLine(":%s %s %s %s :is an IRC operator" % (
self.hostname, RPL_WHOISOPERATOR, user, nick))
self.sendLine(":%s %s %s %s %d %d :seconds idle, signon time" % (
self.hostname, RPL_WHOISIDLE, user, nick, idle, signOn))
self.sendLine(":%s %s %s %s :%s" % (
self.hostname, RPL_WHOISCHANNELS, user, nick, ' '.join(channels)))
self.sendLine(":%s %s %s %s :End of WHOIS list." % (
self.hostname, RPL_ENDOFWHOIS, user, nick))
def join(self, who, where):
"""Send a join message.
@type who: C{str} or C{unicode}
@param who: The name of the user joining. Should be of the form
username!ident@hostmask (unless you know better!).
@type where: C{str} or C{unicode}
@param where: The channel the user is joining.
"""
self.sendLine(":%s JOIN %s" % (who, where))
def part(self, who, where, reason=None):
"""Send a part message.
@type who: C{str} or C{unicode}
@param who: The name of the user joining. Should be of the form
username!ident@hostmask (unless you know better!).
@type where: C{str} or C{unicode}
@param where: The channel the user is joining.
@type reason: C{str} or C{unicode}
@param reason: A string describing the misery which caused
this poor soul to depart.
"""
if reason:
self.sendLine(":%s PART %s :%s" % (who, where, reason))
else:
self.sendLine(":%s PART %s" % (who, where))
def channelMode(self, user, channel, mode, *args):
"""
Send information about the mode of a channel.
@type user: C{str} or C{unicode}
@param user: The user receiving the name list. Only their nick
name, not the full hostmask.
@type channel: C{str} or C{unicode}
@param channel: The channel for which this is the namelist.
@type mode: C{str}
@param mode: A string describing this channel's modes.
@param args: Any additional arguments required by the modes.
"""
self.sendLine(":%s %s %s %s %s %s" % (
self.hostname, RPL_CHANNELMODEIS, user, channel, mode, ' '.join(args)))
class IRCClient(basic.LineReceiver):
"""Internet Relay Chat client protocol, with sprinkles.
In addition to providing an interface for an IRC client protocol,
this class also contains reasonable implementations of many common
CTCP methods.
TODO
====
- Limit the length of messages sent (because the IRC server probably
does).
- Add flood protection/rate limiting for my CTCP replies.
- NickServ cooperation. (a mix-in?)
- Heartbeat. The transport may die in such a way that it does not realize
it is dead until it is written to. Sending something (like \"PING
this.irc-host.net\") during idle peroids would alleviate that. If
you're concerned with the stability of the host as well as that of the
transport, you might care to watch for the corresponding PONG.
@ivar nickname: Nickname the client will use.
@ivar password: Password used to log on to the server. May be C{None}.
@ivar realname: Supplied to the server during login as the \"Real name\"
or \"ircname\". May be C{None}.
@ivar username: Supplied to the server during login as the \"User name\".
May be C{None}
@ivar userinfo: Sent in reply to a X{USERINFO} CTCP query. If C{None}, no
USERINFO reply will be sent.
\"This is used to transmit a string which is settable by
the user (and never should be set by the client).\"
@ivar fingerReply: Sent in reply to a X{FINGER} CTCP query. If C{None}, no
FINGER reply will be sent.
@type fingerReply: Callable or String
@ivar versionName: CTCP VERSION reply, client name. If C{None}, no VERSION
reply will be sent.
@ivar versionNum: CTCP VERSION reply, client version,
@ivar versionEnv: CTCP VERSION reply, environment the client is running in.
@ivar sourceURL: CTCP SOURCE reply, a URL where the source code of this
client may be found. If C{None}, no SOURCE reply will be sent.
@ivar lineRate: Minimum delay between lines sent to the server. If
C{None}, no delay will be imposed.
@type lineRate: Number of Seconds.
"""
motd = ""
nickname = 'irc'
password = None
realname = None
username = None
### Responses to various CTCP queries.
userinfo = None
# fingerReply is a callable returning a string, or a str()able object.
fingerReply = None
versionName = None
versionNum = None
versionEnv = None
sourceURL = "http://twistedmatrix.com/downloads/"
dcc_destdir = '.'
dcc_sessions = None
# If this is false, no attempt will be made to identify
# ourself to the server.
performLogin = 1
lineRate = None
_queue = None
_queueEmptying = None
delimiter = '\n' # '\r\n' will also work (see dataReceived)
__pychecker__ = 'unusednames=params,prefix,channel'
def _reallySendLine(self, line):
return basic.LineReceiver.sendLine(self, lowQuote(line) + '\r')
def sendLine(self, line):
if self.lineRate is None:
self._reallySendLine(line)
else:
self._queue.append(line)
if not self._queueEmptying:
self._sendLine()
def _sendLine(self):
if self._queue:
self._reallySendLine(self._queue.pop(0))
self._queueEmptying = reactor.callLater(self.lineRate,
self._sendLine)
else:
self._queueEmptying = None
### Interface level client->user output methods
###
### You'll want to override these.
### Methods relating to the server itself
def created(self, when):
"""Called with creation date information about the server, usually at logon.
@type when: C{str}
@param when: A string describing when the server was created, probably.
"""
def yourHost(self, info):
"""Called with daemon information about the server, usually at logon.
@type info: C{str}
@param when: A string describing what software the server is running, probably.
"""
def myInfo(self, servername, version, umodes, cmodes):
"""Called with information about the server, usually at logon.
@type servername: C{str}
@param servername: The hostname of this server.
@type version: C{str}
@param version: A description of what software this server runs.
@type umodes: C{str}
@param umodes: All the available user modes.
@type cmodes: C{str}
@param cmodes: All the available channel modes.
"""
def luserClient(self, info):
"""Called with information about the number of connections, usually at logon.
@type info: C{str}
@param info: A description of the number of clients and servers
connected to the network, probably.
"""
def bounce(self, info):
"""Called with information about where the client should reconnect.
@type info: C{str}
@param info: A plaintext description of the address that should be
connected to.
"""
def isupport(self, options):
"""Called with various information about what the server supports.
@type options: C{list} of C{str}
@param options: Descriptions of features or limits of the server, possibly
in the form "NAME=VALUE".
"""
def luserChannels(self, channels):
"""Called with the number of channels existant on the server.
@type channels: C{int}
"""
def luserOp(self, ops):
"""Called with the number of ops logged on to the server.
@type ops: C{int}
"""
def luserMe(self, info):
"""Called with information about the server connected to.
@type info: C{str}
@param info: A plaintext string describing the number of users and servers
connected to this server.
"""
### Methods involving me directly
def privmsg(self, user, channel, message):
"""Called when I have a message from a user to me or a channel.
"""
pass
def joined(self, channel):
"""Called when I finish joining a channel.
channel has the starting character (# or &) intact.
"""
pass
def left(self, channel):
"""Called when I have left a channel.
channel has the starting character (# or &) intact.
"""
pass
def noticed(self, user, channel, message):
"""Called when I have a notice from a user to me or a channel.
By default, this is equivalent to IRCClient.privmsg, but if your
client makes any automated replies, you must override this!
From the RFC::
The difference between NOTICE and PRIVMSG is that
automatic replies MUST NEVER be sent in response to a
NOTICE message. [...] The object of this rule is to avoid
loops between clients automatically sending something in
response to something it received.
"""
self.privmsg(user, channel, message)
def modeChanged(self, user, channel, set, modes, args):
"""Called when a channel's modes are changed
@type user: C{str}
@param user: The user and hostmask which instigated this change.
@type channel: C{str}
@param channel: The channel for which the modes are changing.
@type set: C{bool} or C{int}
@param set: true if the mode is being added, false if it is being
removed.
@type modes: C{str}
@param modes: The mode or modes which are being changed.
@type args: C{tuple}
@param args: Any additional information required for the mode
change.
"""
def pong(self, user, secs):
"""Called with the results of a CTCP PING query.
"""
pass
def signedOn(self):
"""Called after sucessfully signing on to the server.
"""
pass
def kickedFrom(self, channel, kicker, message):
"""Called when I am kicked from a channel.
"""
pass
def nickChanged(self, nick):
"""Called when my nick has been changed.
"""
self.nickname = nick
### Things I observe other people doing in a channel.
def userJoined(self, user, channel):
"""Called when I see another user joining a channel.
"""
pass
def userLeft(self, user, channel):
"""Called when I see another user leaving a channel.
"""
pass
def userQuit(self, user, quitMessage):
"""Called when I see another user disconnect from the network.
"""
pass
def userKicked(self, kickee, channel, kicker, message):
"""Called when I observe someone else being kicked from a channel.
"""
pass
def action(self, user, channel, data):
"""Called when I see a user perform an ACTION on a channel.
"""
pass
def topicUpdated(self, user, channel, newTopic):
"""In channel, user changed the topic to newTopic.
Also called when first joining a channel.
"""
pass
def userRenamed(self, oldname, newname):
"""A user changed their name from oldname to newname.
"""
pass
### Information from the server.
def receivedMOTD(self, motd):
"""I received a message-of-the-day banner from the server.
motd is a list of strings, where each string was sent as a seperate
message from the server. To display, you might want to use::
string.join(motd, '\\n')
to get a nicely formatted string.
"""
pass
### user input commands, client->server
### Your client will want to invoke these.
def join(self, channel, key=None):
if channel[0] not in '&#!+': channel = '#' + channel
if key:
self.sendLine("JOIN %s %s" % (channel, key))
else:
self.sendLine("JOIN %s" % (channel,))
def leave(self, channel, reason=None):
if channel[0] not in '&#!+': channel = '#' + channel
if reason:
self.sendLine("PART %s :%s" % (channel, reason))
else:
self.sendLine("PART %s" % (channel,))
def kick(self, channel, user, reason=None):
if channel[0] not in '&#!+': channel = '#' + channel
if reason:
self.sendLine("KICK %s %s :%s" % (channel, user, reason))
else:
self.sendLine("KICK %s %s" % (channel, user))
part = leave
def topic(self, channel, topic=None):
"""Attempt to set the topic of the given channel, or ask what it is.
If topic is None, then I sent a topic query instead of trying to set
the topic. The server should respond with a TOPIC message containing
the current topic of the given channel.
"""
# << TOPIC #xtestx :fff
if channel[0] not in '&#!+': channel = '#' + channel
if topic != None:
self.sendLine("TOPIC %s :%s" % (channel, topic))
else:
self.sendLine("TOPIC %s" % (channel,))
def mode(self, chan, set, modes, limit = None, user = None, mask = None):
"""Change the modes on a user or channel."""
if set:
line = 'MODE %s +%s' % (chan, modes)
else:
line = 'MODE %s -%s' % (chan, modes)
if limit is not None:
line = '%s %d' % (line, limit)
elif user is not None:
line = '%s %s' % (line, user)
elif mask is not None:
line = '%s %s' % (line, mask)
self.sendLine(line)
def say(self, channel, message, length = None):
if channel[0] not in '&#!+': channel = '#' + channel
self.msg(channel, message, length)
def msg(self, user, message, length = None):
"""Send a message to a user or channel.
@type user: C{str}
@param user: The username or channel name to which to direct the
message.
@type message: C{str}
@param message: The text to send
@type length: C{int}
@param length: The maximum number of octets to send at a time. This
has the effect of turning a single call to msg() into multiple
commands to the server. This is useful when long messages may be
sent that would otherwise cause the server to kick us off or silently
truncate the text we are sending. If None is passed, the entire
message is always send in one command.
"""
fmt = "PRIVMSG %s :%%s" % (user,)
if length is None:
self.sendLine(fmt % (message,))
else:
# NOTE: minimumLength really equals len(fmt) - 2 (for '%s') + n
# where n is how many bytes sendLine sends to end the line.
# n was magic numbered to 2, I think incorrectly
minimumLength = len(fmt)
if length <= minimumLength:
raise ValueError("Maximum length must exceed %d for message "
"to %s" % (minimumLength, user))
lines = split(message, length - minimumLength)
map(lambda line, self=self, fmt=fmt: self.sendLine(fmt % line),
lines)
def notice(self, user, message):
self.sendLine("NOTICE %s :%s" % (user, message))
def away(self, message=''):
self.sendLine("AWAY :%s" % message)
def register(self, nickname, hostname='foo', servername='bar'):
if self.password is not None:
self.sendLine("PASS %s" % self.password)
self.setNick(nickname)
if self.username is None:
self.username = nickname
self.sendLine("USER %s foo bar :%s" % (self.username, self.realname))
def setNick(self, nickname):
self.nickname = nickname
self.sendLine("NICK %s" % nickname)
def quit(self, message = ''):
self.sendLine("QUIT :%s" % message)
### user input commands, client->client
def me(self, channel, action):
"""Strike a pose.
"""
if channel[0] not in '&#!+': channel = '#' + channel
self.ctcpMakeQuery(channel, [('ACTION', action)])
_pings = None
_MAX_PINGRING = 12
def ping(self, user, text = None):
"""Measure round-trip delay to another IRC client.
"""
if self._pings is None:
self._pings = {}
if text is None:
chars = string.letters + string.digits + string.punctuation
key = ''.join([random.choice(chars) for i in range(12)])
else:
key = str(text)
self._pings[(user, key)] = time.time()
self.ctcpMakeQuery(user, [('PING', key)])
if len(self._pings) > self._MAX_PINGRING:
# Remove some of the oldest entries.
byValue = [(v, k) for (k, v) in self._pings.items()]
byValue.sort()
excess = self._MAX_PINGRING - len(self._pings)
for i in xrange(excess):
del self._pings[byValue[i][1]]
def dccSend(self, user, file):
if type(file) == types.StringType:
file = open(file, 'r')
size = fileSize(file)
name = getattr(file, "name", "file@%s" % (id(file),))
factory = DccSendFactory(file)
port = reactor.listenTCP(0, factory, 1)
raise NotImplementedError,(
"XXX!!! Help! I need to bind a socket, have it listen, and tell me its address. "
"(and stop accepting once we've made a single connection.)")
my_address = struct.pack("!I", my_address)
args = ['SEND', name, my_address, str(port)]
if not (size is None):
args.append(size)
args = string.join(args, ' ')
self.ctcpMakeQuery(user, [('DCC', args)])
def dccResume(self, user, fileName, port, resumePos):
"""Send a DCC RESUME request to another user."""
self.ctcpMakeQuery(user, [
('DCC', ['RESUME', fileName, port, resumePos])])
def dccAcceptResume(self, user, fileName, port, resumePos):
"""Send a DCC ACCEPT response to clients who have requested a resume.
"""
self.ctcpMakeQuery(user, [
('DCC', ['ACCEPT', fileName, port, resumePos])])
### server->client messages
### You might want to fiddle with these,
### but it is safe to leave them alone.
def irc_ERR_NICKNAMEINUSE(self, prefix, params):
self.register(self.nickname+'_')
def irc_ERR_PASSWDMISMATCH(self, prefix, params):
raise IRCPasswordMismatch("Password Incorrect.")
def irc_RPL_WELCOME(self, prefix, params):
self.signedOn()
def irc_JOIN(self, prefix, params):
nick = string.split(prefix,'!')[0]
channel = params[-1]
if nick == self.nickname:
self.joined(channel)
else:
self.userJoined(nick, channel)
def irc_PART(self, prefix, params):
nick = string.split(prefix,'!')[0]
channel = params[0]
if nick == self.nickname:
self.left(channel)
else:
self.userLeft(nick, channel)
def irc_QUIT(self, prefix, params):
nick = string.split(prefix,'!')[0]
self.userQuit(nick, params[0])
def irc_MODE(self, prefix, params):
channel, rest = params[0], params[1:]
set = rest[0][0] == '+'
modes = rest[0][1:]
args = rest[1:]
self.modeChanged(prefix, channel, set, modes, tuple(args))
def irc_PING(self, prefix, params):
self.sendLine("PONG %s" % params[-1])
def irc_PRIVMSG(self, prefix, params):
user = prefix
channel = params[0]
message = params[-1]
if not message: return # don't raise an exception if some idiot sends us a blank message
if message[0]==X_DELIM:
m = ctcpExtract(message)
if m['extended']:
self.ctcpQuery(user, channel, m['extended'])
if not m['normal']:
return
message = string.join(m['normal'], ' ')
self.privmsg(user, channel, message)
def irc_NOTICE(self, prefix, params):
user = prefix
channel = params[0]
message = params[-1]
if message[0]==X_DELIM:
m = ctcpExtract(message)
if m['extended']:
self.ctcpReply(user, channel, m['extended'])
if not m['normal']:
return
message = string.join(m['normal'], ' ')
self.noticed(user, channel, message)
def irc_NICK(self, prefix, params):
nick = string.split(prefix,'!', 1)[0]
if nick == self.nickname:
self.nickChanged(params[0])
else:
self.userRenamed(nick, params[0])
def irc_KICK(self, prefix, params):
"""Kicked? Who? Not me, I hope.
"""
kicker = string.split(prefix,'!')[0]
channel = params[0]
kicked = params[1]
message = params[-1]
if string.lower(kicked) == string.lower(self.nickname):
# Yikes!
self.kickedFrom(channel, kicker, message)
else:
self.userKicked(kicked, channel, kicker, message)
def irc_TOPIC(self, prefix, params):
"""Someone in the channel set the topic.
"""
user = string.split(prefix, '!')[0]
channel = params[0]
newtopic = params[1]
self.topicUpdated(user, channel, newtopic)
def irc_RPL_TOPIC(self, prefix, params):
"""I just joined the channel, and the server is telling me the current topic.
"""
user = string.split(prefix, '!')[0]
channel = params[1]
newtopic = params[2]
self.topicUpdated(user, channel, newtopic)
def irc_RPL_NOTOPIC(self, prefix, params):
user = string.split(prefix, '!')[0]
channel = params[1]
newtopic = ""
self.topicUpdated(user, channel, newtopic)
def irc_RPL_MOTDSTART(self, prefix, params):
if params[-1].startswith("- "):
params[-1] = params[-1][2:]
self.motd = [params[-1]]
def irc_RPL_MOTD(self, prefix, params):
if params[-1].startswith("- "):
params[-1] = params[-1][2:]
self.motd.append(params[-1])
def irc_RPL_ENDOFMOTD(self, prefix, params):
self.receivedMOTD(self.motd)
def irc_RPL_CREATED(self, prefix, params):
self.created(params[1])
def irc_RPL_YOURHOST(self, prefix, params):
self.yourHost(params[1])
def irc_RPL_MYINFO(self, prefix, params):
info = params[1].split(None, 3)
while len(info) < 4:
info.append(None)
self.myInfo(*info)
def irc_RPL_BOUNCE(self, prefix, params):
# 005 is doubly assigned. Piece of crap dirty trash protocol.
if params[-1] == "are available on this server":
self.isupport(params[1:-1])
else:
self.bounce(params[1])
def irc_RPL_LUSERCLIENT(self, prefix, params):
self.luserClient(params[1])
def irc_RPL_LUSEROP(self, prefix, params):
try:
self.luserOp(int(params[1]))
except ValueError:
pass
def irc_RPL_LUSERCHANNELS(self, prefix, params):
try:
self.luserChannels(int(params[1]))
except ValueError:
pass
def irc_RPL_LUSERME(self, prefix, params):
self.luserMe(params[1])
def irc_unknown(self, prefix, command, params):
pass
### Receiving a CTCP query from another party
### It is safe to leave these alone.
def ctcpQuery(self, user, channel, messages):
"""Dispatch method for any CTCP queries received.
"""
for m in messages:
method = getattr(self, "ctcpQuery_%s" % m[0], None)
if method:
method(user, channel, m[1])
else:
self.ctcpUnknownQuery(user, channel, m[0], m[1])
def ctcpQuery_ACTION(self, user, channel, data):
self.action(user, channel, data)
def ctcpQuery_PING(self, user, channel, data):
nick = string.split(user,"!")[0]
self.ctcpMakeReply(nick, [("PING", data)])
def ctcpQuery_FINGER(self, user, channel, data):
if data is not None:
self.quirkyMessage("Why did %s send '%s' with a FINGER query?"
% (user, data))
if not self.fingerReply:
return
if callable(self.fingerReply):
reply = self.fingerReply()
else:
reply = str(self.fingerReply)
nick = string.split(user,"!")[0]
self.ctcpMakeReply(nick, [('FINGER', reply)])
def ctcpQuery_VERSION(self, user, channel, data):
if data is not None:
self.quirkyMessage("Why did %s send '%s' with a VERSION query?"
% (user, data))
if self.versionName:
nick = string.split(user,"!")[0]
self.ctcpMakeReply(nick, [('VERSION', '%s:%s:%s' %
(self.versionName,
self.versionNum,
self.versionEnv))])
def ctcpQuery_SOURCE(self, user, channel, data):
if data is not None:
self.quirkyMessage("Why did %s send '%s' with a SOURCE query?"
% (user, data))
if self.sourceURL:
nick = string.split(user,"!")[0]
# The CTCP document (Zeuge, Rollo, Mesander 1994) says that SOURCE
# replies should be responded to with the location of an anonymous
# FTP server in host:directory:file format. I'm taking the liberty
# of bringing it into the 21st century by sending a URL instead.
self.ctcpMakeReply(nick, [('SOURCE', self.sourceURL),
('SOURCE', None)])
def ctcpQuery_USERINFO(self, user, channel, data):
if data is not None:
self.quirkyMessage("Why did %s send '%s' with a USERINFO query?"
% (user, data))
if self.userinfo:
nick = string.split(user,"!")[0]
self.ctcpMakeReply(nick, [('USERINFO', self.userinfo)])
def ctcpQuery_CLIENTINFO(self, user, channel, data):
"""A master index of what CTCP tags this client knows.
If no arguments are provided, respond with a list of known tags.
If an argument is provided, provide human-readable help on
the usage of that tag.
"""
nick = string.split(user,"!")[0]
if not data:
# XXX: prefixedMethodNames gets methods from my *class*,
# but it's entirely possible that this *instance* has more
# methods.
names = reflect.prefixedMethodNames(self.__class__,
'ctcpQuery_')
self.ctcpMakeReply(nick, [('CLIENTINFO',
string.join(names, ' '))])
else:
args = string.split(data)
method = getattr(self, 'ctcpQuery_%s' % (args[0],), None)
if not method:
self.ctcpMakeReply(nick, [('ERRMSG',
"CLIENTINFO %s :"
"Unknown query '%s'"
% (data, args[0]))])
return
doc = getattr(method, '__doc__', '')
self.ctcpMakeReply(nick, [('CLIENTINFO', doc)])
def ctcpQuery_ERRMSG(self, user, channel, data):
# Yeah, this seems strange, but that's what the spec says to do
# when faced with an ERRMSG query (not a reply).
nick = string.split(user,"!")[0]
self.ctcpMakeReply(nick, [('ERRMSG',
"%s :No error has occoured." % data)])
def ctcpQuery_TIME(self, user, channel, data):
if data is not None:
self.quirkyMessage("Why did %s send '%s' with a TIME query?"
% (user, data))
nick = string.split(user,"!")[0]
self.ctcpMakeReply(nick,
[('TIME', ':%s' %
time.asctime(time.localtime(time.time())))])
def ctcpQuery_DCC(self, user, channel, data):
"""Initiate a Direct Client Connection
"""
if not data: return
dcctype = data.split(None, 1)[0].upper()
handler = getattr(self, "dcc_" + dcctype, None)
if handler:
if self.dcc_sessions is None:
self.dcc_sessions = []
data = data[len(dcctype)+1:]
handler(user, channel, data)
else:
nick = string.split(user,"!")[0]
self.ctcpMakeReply(nick, [('ERRMSG',
"DCC %s :Unknown DCC type '%s'"
% (data, dcctype))])
self.quirkyMessage("%s offered unknown DCC type %s"
% (user, dcctype))
def dcc_SEND(self, user, channel, data):
# Use splitQuoted for those who send files with spaces in the names.
data = text.splitQuoted(data)
if len(data) < 3:
raise IRCBadMessage, "malformed DCC SEND request: %r" % (data,)
(filename, address, port) = data[:3]
address = dccParseAddress(address)
try:
port = int(port)
except ValueError:
raise IRCBadMessage, "Indecipherable port %r" % (port,)
size = -1
if len(data) >= 4:
try:
size = int(data[3])
except ValueError:
pass
# XXX Should we bother passing this data?
self.dccDoSend(user, address, port, filename, size, data)
def dcc_ACCEPT(self, user, channel, data):
data = text.splitQuoted(data)
if len(data) < 3:
raise IRCBadMessage, "malformed DCC SEND ACCEPT request: %r" % (data,)
(filename, port, resumePos) = data[:3]
try:
port = int(port)
resumePos = int(resumePos)
except ValueError:
return
self.dccDoAcceptResume(user, filename, port, resumePos)
def dcc_RESUME(self, user, channel, data):
data = text.splitQuoted(data)
if len(data) < 3:
raise IRCBadMessage, "malformed DCC SEND RESUME request: %r" % (data,)
(filename, port, resumePos) = data[:3]
try:
port = int(port)
resumePos = int(resumePos)
except ValueError:
return
self.dccDoResume(user, filename, port, resumePos)
def dcc_CHAT(self, user, channel, data):
data = text.splitQuoted(data)
if len(data) < 3:
raise IRCBadMessage, "malformed DCC CHAT request: %r" % (data,)
(filename, address, port) = data[:3]
address = dccParseAddress(address)
try:
port = int(port)
except ValueError:
raise IRCBadMessage, "Indecipherable port %r" % (port,)
self.dccDoChat(user, channel, address, port, data)
### The dccDo methods are the slightly higher-level siblings of
### common dcc_ methods; the arguments have been parsed for them.
def dccDoSend(self, user, address, port, fileName, size, data):
"""Called when I receive a DCC SEND offer from a client.
By default, I do nothing here."""
## filename = path.basename(arg)
## protocol = DccFileReceive(filename, size,
## (user,channel,data),self.dcc_destdir)
## reactor.clientTCP(address, port, protocol)
## self.dcc_sessions.append(protocol)
pass
def dccDoResume(self, user, file, port, resumePos):
"""Called when a client is trying to resume an offered file
via DCC send. It should be either replied to with a DCC
ACCEPT or ignored (default)."""
pass
def dccDoAcceptResume(self, user, file, port, resumePos):
"""Called when a client has verified and accepted a DCC resume
request made by us. By default it will do nothing."""
pass
def dccDoChat(self, user, channel, address, port, data):
pass
#factory = DccChatFactory(self, queryData=(user, channel, data))
#reactor.connectTCP(address, port, factory)
#self.dcc_sessions.append(factory)
#def ctcpQuery_SED(self, user, data):
# """Simple Encryption Doodoo
#
# Feel free to implement this, but no specification is available.
# """
# raise NotImplementedError
def ctcpUnknownQuery(self, user, channel, tag, data):
nick = string.split(user,"!")[0]
self.ctcpMakeReply(nick, [('ERRMSG',
"%s %s: Unknown query '%s'"
% (tag, data, tag))])
log.msg("Unknown CTCP query from %s: %s %s\n"
% (user, tag, data))
def ctcpMakeReply(self, user, messages):
"""Send one or more X{extended messages} as a CTCP reply.
@type messages: a list of extended messages. An extended
message is a (tag, data) tuple, where 'data' may be C{None}.
"""
self.notice(user, ctcpStringify(messages))
### client CTCP query commands
def ctcpMakeQuery(self, user, messages):
"""Send one or more X{extended messages} as a CTCP query.
@type messages: a list of extended messages. An extended
message is a (tag, data) tuple, where 'data' may be C{None}.
"""
self.msg(user, ctcpStringify(messages))
### Receiving a response to a CTCP query (presumably to one we made)
### You may want to add methods here, or override UnknownReply.
def ctcpReply(self, user, channel, messages):
"""Dispatch method for any CTCP replies received.
"""
for m in messages:
method = getattr(self, "ctcpReply_%s" % m[0], None)
if method:
method(user, channel, m[1])
else:
self.ctcpUnknownReply(user, channel, m[0], m[1])
def ctcpReply_PING(self, user, channel, data):
nick = user.split('!', 1)[0]
if (not self._pings) or (not self._pings.has_key((nick, data))):
raise IRCBadMessage,\
"Bogus PING response from %s: %s" % (user, data)
t0 = self._pings[(nick, data)]
self.pong(user, time.time() - t0)
def ctcpUnknownReply(self, user, channel, tag, data):
"""Called when a fitting ctcpReply_ method is not found.
XXX: If the client makes arbitrary CTCP queries,
this method should probably show the responses to
them instead of treating them as anomolies.
"""
log.msg("Unknown CTCP reply from %s: %s %s\n"
% (user, tag, data))
### Error handlers
### You may override these with something more appropriate to your UI.
def badMessage(self, line, excType, excValue, tb):
"""When I get a message that's so broken I can't use it.
"""
log.msg(line)
log.msg(string.join(traceback.format_exception(excType,
excValue,
tb),''))
def quirkyMessage(self, s):
"""This is called when I receive a message which is peculiar,
but not wholly indecipherable.
"""
log.msg(s + '\n')
### Protocool methods
def connectionMade(self):
self._queue = []
if self.performLogin:
self.register(self.nickname)
def dataReceived(self, data):
basic.LineReceiver.dataReceived(self, data.replace('\r', ''))
def lineReceived(self, line):
line = lowDequote(line)
try:
prefix, command, params = parsemsg(line)
if numeric_to_symbolic.has_key(command):
command = numeric_to_symbolic[command]
self.handleCommand(command, prefix, params)
except IRCBadMessage:
self.badMessage(line, *sys.exc_info())
def handleCommand(self, command, prefix, params):
"""Determine the function to call for the given command and call
it with the given arguments.
"""
method = getattr(self, "irc_%s" % command, None)
try:
if method is not None:
method(prefix, params)
else:
self.irc_unknown(prefix, command, params)
except:
log.deferr()
def __getstate__(self):
dct = self.__dict__.copy()
dct['dcc_sessions'] = None
dct['_pings'] = None
return dct
def dccParseAddress(address):
if '.' in address:
pass
else:
try:
address = long(address)
except ValueError:
raise IRCBadMessage,\
"Indecipherable address %r" % (address,)
else:
address = (
(address >> 24) & 0xFF,
(address >> 16) & 0xFF,
(address >> 8) & 0xFF,
address & 0xFF,
)
address = '.'.join(map(str,address))
return address
class DccFileReceiveBasic(protocol.Protocol, styles.Ephemeral):
"""Bare protocol to receive a Direct Client Connection SEND stream.
This does enough to keep the other guy talking, but you'll want to
extend my dataReceived method to *do* something with the data I get.
"""
bytesReceived = 0
def __init__(self, resumeOffset=0):
self.bytesReceived = resumeOffset
self.resume = (resumeOffset != 0)
def dataReceived(self, data):
"""Called when data is received.
Warning: This just acknowledges to the remote host that the
data has been received; it doesn't *do* anything with the
data, so you'll want to override this.
"""
self.bytesReceived = self.bytesReceived + len(data)
self.transport.write(struct.pack('!i', self.bytesReceived))
class DccSendProtocol(protocol.Protocol, styles.Ephemeral):
"""Protocol for an outgoing Direct Client Connection SEND.
"""
blocksize = 1024
file = None
bytesSent = 0
completed = 0
connected = 0
def __init__(self, file):
if type(file) is types.StringType:
self.file = open(file, 'r')
def connectionMade(self):
self.connected = 1
self.sendBlock()
def dataReceived(self, data):
# XXX: Do we need to check to see if len(data) != fmtsize?
bytesShesGot = struct.unpack("!I", data)
if bytesShesGot < self.bytesSent:
# Wait for her.
# XXX? Add some checks to see if we've stalled out?
return
elif bytesShesGot > self.bytesSent:
# self.transport.log("DCC SEND %s: She says she has %d bytes "
# "but I've only sent %d. I'm stopping "
# "this screwy transfer."
# % (self.file,
# bytesShesGot, self.bytesSent))
self.transport.loseConnection()
return
self.sendBlock()
def sendBlock(self):
block = self.file.read(self.blocksize)
if block:
self.transport.write(block)
self.bytesSent = self.bytesSent + len(block)
else:
# Nothing more to send, transfer complete.
self.transport.loseConnection()
self.completed = 1
def connectionLost(self, reason):
self.connected = 0
if hasattr(self.file, "close"):
self.file.close()
class DccSendFactory(protocol.Factory):
protocol = DccSendProtocol
def __init__(self, file):
self.file = file
def buildProtocol(self, connection):
p = self.protocol(self.file)
p.factory = self
return p
def fileSize(file):
"""I'll try my damndest to determine the size of this file object.
"""
size = None
if hasattr(file, "fileno"):
fileno = file.fileno()
try:
stat_ = os.fstat(fileno)
size = stat_[stat.ST_SIZE]
except:
pass
else:
return size
if hasattr(file, "name") and path.exists(file.name):
try:
size = path.getsize(file.name)
except:
pass
else:
return size
if hasattr(file, "seek") and hasattr(file, "tell"):
try:
try:
file.seek(0, 2)
size = file.tell()
finally:
file.seek(0, 0)
except:
pass
else:
return size
return size
class DccChat(basic.LineReceiver, styles.Ephemeral):
"""Direct Client Connection protocol type CHAT.
DCC CHAT is really just your run o' the mill basic.LineReceiver
protocol. This class only varies from that slightly, accepting
either LF or CR LF for a line delimeter for incoming messages
while always using CR LF for outgoing.
The lineReceived method implemented here uses the DCC connection's
'client' attribute (provided upon construction) to deliver incoming
lines from the DCC chat via IRCClient's normal privmsg interface.
That's something of a spoof, which you may well want to override.
"""
queryData = None
delimiter = CR + NL
client = None
remoteParty = None
buffer = ""
def __init__(self, client, queryData=None):
"""Initialize a new DCC CHAT session.
queryData is a 3-tuple of
(fromUser, targetUserOrChannel, data)
as received by the CTCP query.
(To be honest, fromUser is the only thing that's currently
used here. targetUserOrChannel is potentially useful, while
the 'data' argument is soley for informational purposes.)
"""
self.client = client
if queryData:
self.queryData = queryData
self.remoteParty = self.queryData[0]
def dataReceived(self, data):
self.buffer = self.buffer + data
lines = string.split(self.buffer, LF)
# Put the (possibly empty) element after the last LF back in the
# buffer
self.buffer = lines.pop()
for line in lines:
if line[-1] == CR:
line = line[:-1]
self.lineReceived(line)
def lineReceived(self, line):
log.msg("DCC CHAT<%s> %s" % (self.remoteParty, line))
self.client.privmsg(self.remoteParty,
self.client.nickname, line)
class DccChatFactory(protocol.ClientFactory):
protocol = DccChat
noisy = 0
def __init__(self, client, queryData):
self.client = client
self.queryData = queryData
def buildProtocol(self, addr):
p = self.protocol(client=self.client, queryData=self.queryData)
p.factory = self
def clientConnectionFailed(self, unused_connector, unused_reason):
self.client.dcc_sessions.remove(self)
def clientConnectionLost(self, unused_connector, unused_reason):
self.client.dcc_sessions.remove(self)
def dccDescribe(data):
"""Given the data chunk from a DCC query, return a descriptive string.
"""
orig_data = data
data = string.split(data)
if len(data) < 4:
return orig_data
(dcctype, arg, address, port) = data[:4]
if '.' in address:
pass
else:
try:
address = long(address)
except ValueError:
pass
else:
address = (
(address >> 24) & 0xFF,
(address >> 16) & 0xFF,
(address >> 8) & 0xFF,
address & 0xFF,
)
# The mapping to 'int' is to get rid of those accursed
# "L"s which python 1.5.2 puts on the end of longs.
address = string.join(map(str,map(int,address)), ".")
if dcctype == 'SEND':
filename = arg
size_txt = ''
if len(data) >= 5:
try:
size = int(data[4])
size_txt = ' of size %d bytes' % (size,)
except ValueError:
pass
dcc_text = ("SEND for file '%s'%s at host %s, port %s"
% (filename, size_txt, address, port))
elif dcctype == 'CHAT':
dcc_text = ("CHAT for host %s, port %s"
% (address, port))
else:
dcc_text = orig_data
return dcc_text
class DccFileReceive(DccFileReceiveBasic):
"""Higher-level coverage for getting a file from DCC SEND.
I allow you to change the file's name and destination directory.
I won't overwrite an existing file unless I've been told it's okay
to do so. If passed the resumeOffset keyword argument I will attempt to
resume the file from that amount of bytes.
XXX: I need to let the client know when I am finished.
XXX: I need to decide how to keep a progress indicator updated.
XXX: Client needs a way to tell me \"Do not finish until I say so.\"
XXX: I need to make sure the client understands if the file cannot be written.
"""
filename = 'dcc'
fileSize = -1
destDir = '.'
overwrite = 0
fromUser = None
queryData = None
def __init__(self, filename, fileSize=-1, queryData=None,
destDir='.', resumeOffset=0):
DccFileReceiveBasic.__init__(self, resumeOffset=resumeOffset)
self.filename = filename
self.destDir = destDir
self.fileSize = fileSize
if queryData:
self.queryData = queryData
self.fromUser = self.queryData[0]
def set_directory(self, directory):
"""Set the directory where the downloaded file will be placed.
May raise OSError if the supplied directory path is not suitable.
"""
if not path.exists(directory):
raise OSError(errno.ENOENT, "You see no directory there.",
directory)
if not path.isdir(directory):
raise OSError(errno.ENOTDIR, "You cannot put a file into "
"something which is not a directory.",
directory)
if not os.access(directory, os.X_OK | os.W_OK):
raise OSError(errno.EACCES,
"This directory is too hard to write in to.",
directory)
self.destDir = directory
def set_filename(self, filename):
"""Change the name of the file being transferred.
This replaces the file name provided by the sender.
"""
self.filename = filename
def set_overwrite(self, boolean):
"""May I overwrite existing files?
"""
self.overwrite = boolean
# Protocol-level methods.
def connectionMade(self):
dst = path.abspath(path.join(self.destDir,self.filename))
exists = path.exists(dst)
if self.resume and exists:
# I have been told I want to resume, and a file already
# exists - Here we go
self.file = open(dst, 'ab')
log.msg("Attempting to resume %s - starting from %d bytes" %
(self.file, self.file.tell()))
elif self.overwrite or not exists:
self.file = open(dst, 'wb')
else:
raise OSError(errno.EEXIST,
"There's a file in the way. "
"Perhaps that's why you cannot open it.",
dst)
def dataReceived(self, data):
self.file.write(data)
DccFileReceiveBasic.dataReceived(self, data)
# XXX: update a progress indicator here?
def connectionLost(self, reason):
"""When the connection is lost, I close the file.
"""
self.connected = 0
logmsg = ("%s closed." % (self,))
if self.fileSize > 0:
logmsg = ("%s %d/%d bytes received"
% (logmsg, self.bytesReceived, self.fileSize))
if self.bytesReceived == self.fileSize:
pass # Hooray!
elif self.bytesReceived < self.fileSize:
logmsg = ("%s (Warning: %d bytes short)"
% (logmsg, self.fileSize - self.bytesReceived))
else:
logmsg = ("%s (file larger than expected)"
% (logmsg,))
else:
logmsg = ("%s %d bytes received"
% (logmsg, self.bytesReceived))
if hasattr(self, 'file'):
logmsg = "%s and written to %s.\n" % (logmsg, self.file.name)
if hasattr(self.file, 'close'): self.file.close()
# self.transport.log(logmsg)
def __str__(self):
if not self.connected:
return "<Unconnected DccFileReceive object at %x>" % (id(self),)
from_ = self.transport.getPeer()
if self.fromUser:
from_ = "%s (%s)" % (self.fromUser, from_)
s = ("DCC transfer of '%s' from %s" % (self.filename, from_))
return s
def __repr__(self):
s = ("<%s at %x: GET %s>"
% (self.__class__, id(self), self.filename))
return s
# CTCP constants and helper functions
X_DELIM = chr(001)
def ctcpExtract(message):
"""Extract CTCP data from a string.
Returns a dictionary with two items:
- C{'extended'}: a list of CTCP (tag, data) tuples
- C{'normal'}: a list of strings which were not inside a CTCP delimeter
"""
extended_messages = []
normal_messages = []
retval = {'extended': extended_messages,
'normal': normal_messages }
messages = string.split(message, X_DELIM)
odd = 0
# X1 extended data X2 nomal data X3 extended data X4 normal...
while messages:
if odd:
extended_messages.append(messages.pop(0))
else:
normal_messages.append(messages.pop(0))
odd = not odd
extended_messages[:] = filter(None, extended_messages)
normal_messages[:] = filter(None, normal_messages)
extended_messages[:] = map(ctcpDequote, extended_messages)
for i in xrange(len(extended_messages)):
m = string.split(extended_messages[i], SPC, 1)
tag = m[0]
if len(m) > 1:
data = m[1]
else:
data = None
extended_messages[i] = (tag, data)
return retval
# CTCP escaping
M_QUOTE= chr(020)
mQuoteTable = {
NUL: M_QUOTE + '0',
NL: M_QUOTE + 'n',
CR: M_QUOTE + 'r',
M_QUOTE: M_QUOTE + M_QUOTE
}
mDequoteTable = {}
for k, v in mQuoteTable.items():
mDequoteTable[v[-1]] = k
del k, v
mEscape_re = re.compile('%s.' % (re.escape(M_QUOTE),), re.DOTALL)
def lowQuote(s):
for c in (M_QUOTE, NUL, NL, CR):
s = string.replace(s, c, mQuoteTable[c])
return s
def lowDequote(s):
def sub(matchobj, mDequoteTable=mDequoteTable):
s = matchobj.group()[1]
try:
s = mDequoteTable[s]
except KeyError:
s = s
return s
return mEscape_re.sub(sub, s)
X_QUOTE = '\\'
xQuoteTable = {
X_DELIM: X_QUOTE + 'a',
X_QUOTE: X_QUOTE + X_QUOTE
}
xDequoteTable = {}
for k, v in xQuoteTable.items():
xDequoteTable[v[-1]] = k
xEscape_re = re.compile('%s.' % (re.escape(X_QUOTE),), re.DOTALL)
def ctcpQuote(s):
for c in (X_QUOTE, X_DELIM):
s = string.replace(s, c, xQuoteTable[c])
return s
def ctcpDequote(s):
def sub(matchobj, xDequoteTable=xDequoteTable):
s = matchobj.group()[1]
try:
s = xDequoteTable[s]
except KeyError:
s = s
return s
return xEscape_re.sub(sub, s)
def ctcpStringify(messages):
"""
@type messages: a list of extended messages. An extended
message is a (tag, data) tuple, where 'data' may be C{None}, a
string, or a list of strings to be joined with whitespace.
@returns: String
"""
coded_messages = []
for (tag, data) in messages:
if data:
if not isinstance(data, types.StringType):
try:
# data as list-of-strings
data = " ".join(map(str, data))
except TypeError:
# No? Then use it's %s representation.
pass
m = "%s %s" % (tag, data)
else:
m = str(tag)
m = ctcpQuote(m)
m = "%s%s%s" % (X_DELIM, m, X_DELIM)
coded_messages.append(m)
line = string.join(coded_messages, '')
return line
# Constants (from RFC 2812)
RPL_WELCOME = '001'
RPL_YOURHOST = '002'
RPL_CREATED = '003'
RPL_MYINFO = '004'
RPL_BOUNCE = '005'
RPL_USERHOST = '302'
RPL_ISON = '303'
RPL_AWAY = '301'
RPL_UNAWAY = '305'
RPL_NOWAWAY = '306'
RPL_WHOISUSER = '311'
RPL_WHOISSERVER = '312'
RPL_WHOISOPERATOR = '313'
RPL_WHOISIDLE = '317'
RPL_ENDOFWHOIS = '318'
RPL_WHOISCHANNELS = '319'
RPL_WHOWASUSER = '314'
RPL_ENDOFWHOWAS = '369'
RPL_LISTSTART = '321'
RPL_LIST = '322'
RPL_LISTEND = '323'
RPL_UNIQOPIS = '325'
RPL_CHANNELMODEIS = '324'
RPL_NOTOPIC = '331'
RPL_TOPIC = '332'
RPL_INVITING = '341'
RPL_SUMMONING = '342'
RPL_INVITELIST = '346'
RPL_ENDOFINVITELIST = '347'
RPL_EXCEPTLIST = '348'
RPL_ENDOFEXCEPTLIST = '349'
RPL_VERSION = '351'
RPL_WHOREPLY = '352'
RPL_ENDOFWHO = '315'
RPL_NAMREPLY = '353'
RPL_ENDOFNAMES = '366'
RPL_LINKS = '364'
RPL_ENDOFLINKS = '365'
RPL_BANLIST = '367'
RPL_ENDOFBANLIST = '368'
RPL_INFO = '371'
RPL_ENDOFINFO = '374'
RPL_MOTDSTART = '375'
RPL_MOTD = '372'
RPL_ENDOFMOTD = '376'
RPL_YOUREOPER = '381'
RPL_REHASHING = '382'
RPL_YOURESERVICE = '383'
RPL_TIME = '391'
RPL_USERSSTART = '392'
RPL_USERS = '393'
RPL_ENDOFUSERS = '394'
RPL_NOUSERS = '395'
RPL_TRACELINK = '200'
RPL_TRACECONNECTING = '201'
RPL_TRACEHANDSHAKE = '202'
RPL_TRACEUNKNOWN = '203'
RPL_TRACEOPERATOR = '204'
RPL_TRACEUSER = '205'
RPL_TRACESERVER = '206'
RPL_TRACESERVICE = '207'
RPL_TRACENEWTYPE = '208'
RPL_TRACECLASS = '209'
RPL_TRACERECONNECT = '210'
RPL_TRACELOG = '261'
RPL_TRACEEND = '262'
RPL_STATSLINKINFO = '211'
RPL_STATSCOMMANDS = '212'
RPL_ENDOFSTATS = '219'
RPL_STATSUPTIME = '242'
RPL_STATSOLINE = '243'
RPL_UMODEIS = '221'
RPL_SERVLIST = '234'
RPL_SERVLISTEND = '235'
RPL_LUSERCLIENT = '251'
RPL_LUSEROP = '252'
RPL_LUSERUNKNOWN = '253'
RPL_LUSERCHANNELS = '254'
RPL_LUSERME = '255'
RPL_ADMINME = '256'
RPL_ADMINLOC = '257'
RPL_ADMINLOC = '258'
RPL_ADMINEMAIL = '259'
RPL_TRYAGAIN = '263'
ERR_NOSUCHNICK = '401'
ERR_NOSUCHSERVER = '402'
ERR_NOSUCHCHANNEL = '403'
ERR_CANNOTSENDTOCHAN = '404'
ERR_TOOMANYCHANNELS = '405'
ERR_WASNOSUCHNICK = '406'
ERR_TOOMANYTARGETS = '407'
ERR_NOSUCHSERVICE = '408'
ERR_NOORIGIN = '409'
ERR_NORECIPIENT = '411'
ERR_NOTEXTTOSEND = '412'
ERR_NOTOPLEVEL = '413'
ERR_WILDTOPLEVEL = '414'
ERR_BADMASK = '415'
ERR_UNKNOWNCOMMAND = '421'
ERR_NOMOTD = '422'
ERR_NOADMININFO = '423'
ERR_FILEERROR = '424'
ERR_NONICKNAMEGIVEN = '431'
ERR_ERRONEUSNICKNAME = '432'
ERR_NICKNAMEINUSE = '433'
ERR_NICKCOLLISION = '436'
ERR_UNAVAILRESOURCE = '437'
ERR_USERNOTINCHANNEL = '441'
ERR_NOTONCHANNEL = '442'
ERR_USERONCHANNEL = '443'
ERR_NOLOGIN = '444'
ERR_SUMMONDISABLED = '445'
ERR_USERSDISABLED = '446'
ERR_NOTREGISTERED = '451'
ERR_NEEDMOREPARAMS = '461'
ERR_ALREADYREGISTRED = '462'
ERR_NOPERMFORHOST = '463'
ERR_PASSWDMISMATCH = '464'
ERR_YOUREBANNEDCREEP = '465'
ERR_YOUWILLBEBANNED = '466'
ERR_KEYSET = '467'
ERR_CHANNELISFULL = '471'
ERR_UNKNOWNMODE = '472'
ERR_INVITEONLYCHAN = '473'
ERR_BANNEDFROMCHAN = '474'
ERR_BADCHANNELKEY = '475'
ERR_BADCHANMASK = '476'
ERR_NOCHANMODES = '477'
ERR_BANLISTFULL = '478'
ERR_NOPRIVILEGES = '481'
ERR_CHANOPRIVSNEEDED = '482'
ERR_CANTKILLSERVER = '483'
ERR_RESTRICTED = '484'
ERR_UNIQOPPRIVSNEEDED = '485'
ERR_NOOPERHOST = '491'
ERR_NOSERVICEHOST = '492'
ERR_UMODEUNKNOWNFLAG = '501'
ERR_USERSDONTMATCH = '502'
# And hey, as long as the strings are already intern'd...
symbolic_to_numeric = {
"RPL_WELCOME": '001',
"RPL_YOURHOST": '002',
"RPL_CREATED": '003',
"RPL_MYINFO": '004',
"RPL_BOUNCE": '005',
"RPL_USERHOST": '302',
"RPL_ISON": '303',
"RPL_AWAY": '301',
"RPL_UNAWAY": '305',
"RPL_NOWAWAY": '306',
"RPL_WHOISUSER": '311',
"RPL_WHOISSERVER": '312',
"RPL_WHOISOPERATOR": '313',
"RPL_WHOISIDLE": '317',
"RPL_ENDOFWHOIS": '318',
"RPL_WHOISCHANNELS": '319',
"RPL_WHOWASUSER": '314',
"RPL_ENDOFWHOWAS": '369',
"RPL_LISTSTART": '321',
"RPL_LIST": '322',
"RPL_LISTEND": '323',
"RPL_UNIQOPIS": '325',
"RPL_CHANNELMODEIS": '324',
"RPL_NOTOPIC": '331',
"RPL_TOPIC": '332',
"RPL_INVITING": '341',
"RPL_SUMMONING": '342',
"RPL_INVITELIST": '346',
"RPL_ENDOFINVITELIST": '347',
"RPL_EXCEPTLIST": '348',
"RPL_ENDOFEXCEPTLIST": '349',
"RPL_VERSION": '351',
"RPL_WHOREPLY": '352',
"RPL_ENDOFWHO": '315',
"RPL_NAMREPLY": '353',
"RPL_ENDOFNAMES": '366',
"RPL_LINKS": '364',
"RPL_ENDOFLINKS": '365',
"RPL_BANLIST": '367',
"RPL_ENDOFBANLIST": '368',
"RPL_INFO": '371',
"RPL_ENDOFINFO": '374',
"RPL_MOTDSTART": '375',
"RPL_MOTD": '372',
"RPL_ENDOFMOTD": '376',
"RPL_YOUREOPER": '381',
"RPL_REHASHING": '382',
"RPL_YOURESERVICE": '383',
"RPL_TIME": '391',
"RPL_USERSSTART": '392',
"RPL_USERS": '393',
"RPL_ENDOFUSERS": '394',
"RPL_NOUSERS": '395',
"RPL_TRACELINK": '200',
"RPL_TRACECONNECTING": '201',
"RPL_TRACEHANDSHAKE": '202',
"RPL_TRACEUNKNOWN": '203',
"RPL_TRACEOPERATOR": '204',
"RPL_TRACEUSER": '205',
"RPL_TRACESERVER": '206',
"RPL_TRACESERVICE": '207',
"RPL_TRACENEWTYPE": '208',
"RPL_TRACECLASS": '209',
"RPL_TRACERECONNECT": '210',
"RPL_TRACELOG": '261',
"RPL_TRACEEND": '262',
"RPL_STATSLINKINFO": '211',
"RPL_STATSCOMMANDS": '212',
"RPL_ENDOFSTATS": '219',
"RPL_STATSUPTIME": '242',
"RPL_STATSOLINE": '243',
"RPL_UMODEIS": '221',
"RPL_SERVLIST": '234',
"RPL_SERVLISTEND": '235',
"RPL_LUSERCLIENT": '251',
"RPL_LUSEROP": '252',
"RPL_LUSERUNKNOWN": '253',
"RPL_LUSERCHANNELS": '254',
"RPL_LUSERME": '255',
"RPL_ADMINME": '256',
"RPL_ADMINLOC": '257',
"RPL_ADMINLOC": '258',
"RPL_ADMINEMAIL": '259',
"RPL_TRYAGAIN": '263',
"ERR_NOSUCHNICK": '401',
"ERR_NOSUCHSERVER": '402',
"ERR_NOSUCHCHANNEL": '403',
"ERR_CANNOTSENDTOCHAN": '404',
"ERR_TOOMANYCHANNELS": '405',
"ERR_WASNOSUCHNICK": '406',
"ERR_TOOMANYTARGETS": '407',
"ERR_NOSUCHSERVICE": '408',
"ERR_NOORIGIN": '409',
"ERR_NORECIPIENT": '411',
"ERR_NOTEXTTOSEND": '412',
"ERR_NOTOPLEVEL": '413',
"ERR_WILDTOPLEVEL": '414',
"ERR_BADMASK": '415',
"ERR_UNKNOWNCOMMAND": '421',
"ERR_NOMOTD": '422',
"ERR_NOADMININFO": '423',
"ERR_FILEERROR": '424',
"ERR_NONICKNAMEGIVEN": '431',
"ERR_ERRONEUSNICKNAME": '432',
"ERR_NICKNAMEINUSE": '433',
"ERR_NICKCOLLISION": '436',
"ERR_UNAVAILRESOURCE": '437',
"ERR_USERNOTINCHANNEL": '441',
"ERR_NOTONCHANNEL": '442',
"ERR_USERONCHANNEL": '443',
"ERR_NOLOGIN": '444',
"ERR_SUMMONDISABLED": '445',
"ERR_USERSDISABLED": '446',
"ERR_NOTREGISTERED": '451',
"ERR_NEEDMOREPARAMS": '461',
"ERR_ALREADYREGISTRED": '462',
"ERR_NOPERMFORHOST": '463',
"ERR_PASSWDMISMATCH": '464',
"ERR_YOUREBANNEDCREEP": '465',
"ERR_YOUWILLBEBANNED": '466',
"ERR_KEYSET": '467',
"ERR_CHANNELISFULL": '471',
"ERR_UNKNOWNMODE": '472',
"ERR_INVITEONLYCHAN": '473',
"ERR_BANNEDFROMCHAN": '474',
"ERR_BADCHANNELKEY": '475',
"ERR_BADCHANMASK": '476',
"ERR_NOCHANMODES": '477',
"ERR_BANLISTFULL": '478',
"ERR_NOPRIVILEGES": '481',
"ERR_CHANOPRIVSNEEDED": '482',
"ERR_CANTKILLSERVER": '483',
"ERR_RESTRICTED": '484',
"ERR_UNIQOPPRIVSNEEDED": '485',
"ERR_NOOPERHOST": '491',
"ERR_NOSERVICEHOST": '492',
"ERR_UMODEUNKNOWNFLAG": '501',
"ERR_USERSDONTMATCH": '502',
}
numeric_to_symbolic = {}
for k, v in symbolic_to_numeric.items():
numeric_to_symbolic[v] = k | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/protocols/irc.py | irc.py |
from zope.interface import directlyProvides, implements
from twisted.internet import defer
from twisted.internet.error import ConnectionLost
from twisted.python import failure
from twisted.words.protocols.jabber import error, ijabber
from twisted.words.xish import domish, xmlstream
from twisted.words.xish.xmlstream import STREAM_CONNECTED_EVENT
from twisted.words.xish.xmlstream import STREAM_START_EVENT
from twisted.words.xish.xmlstream import STREAM_END_EVENT
from twisted.words.xish.xmlstream import STREAM_ERROR_EVENT
try:
from twisted.internet import ssl
except ImportError:
ssl = None
if ssl and not ssl.supported:
ssl = None
STREAM_AUTHD_EVENT = intern("//event/stream/authd")
INIT_FAILED_EVENT = intern("//event/xmpp/initfailed")
NS_STREAMS = 'http://etherx.jabber.org/streams'
NS_XMPP_TLS = 'urn:ietf:params:xml:ns:xmpp-tls'
Reset = object()
def hashPassword(sid, password):
"""
Create a SHA1-digest string of a session identifier and password.
"""
import sha
return sha.new("%s%s" % (sid, password)).hexdigest()
class Authenticator:
"""
Base class for business logic of initializing an XmlStream
Subclass this object to enable an XmlStream to initialize and authenticate
to different types of stream hosts (such as clients, components, etc.).
Rules:
1. The Authenticator MUST dispatch a L{STREAM_AUTHD_EVENT} when the
stream has been completely initialized.
2. The Authenticator SHOULD reset all state information when
L{associateWithStream} is called.
3. The Authenticator SHOULD override L{streamStarted}, and start
initialization there.
@type xmlstream: L{XmlStream}
@ivar xmlstream: The XmlStream that needs authentication
@note: the term authenticator is historical. Authenticators perform
all steps required to prepare the stream for the exchange
of XML stanzas.
"""
def __init__(self):
self.xmlstream = None
def connectionMade(self):
"""
Called by the XmlStream when the underlying socket connection is
in place.
This allows the Authenticator to send an initial root element, if it's
connecting, or wait for an inbound root from the peer if it's accepting
the connection.
Subclasses can use self.xmlstream.send() to send any initial data to
the peer.
"""
def streamStarted(self):
"""
Called by the XmlStream when the stream has started.
A stream is considered to have started when the root element has been
received and, if applicable, the feature set has been received.
"""
def associateWithStream(self, xmlstream):
"""
Called by the XmlStreamFactory when a connection has been made
to the requested peer, and an XmlStream object has been
instantiated.
The default implementation just saves a handle to the new
XmlStream.
@type xmlstream: L{XmlStream}
@param xmlstream: The XmlStream that will be passing events to this
Authenticator.
"""
self.xmlstream = xmlstream
class ConnectAuthenticator(Authenticator):
"""
Authenticator for initiating entities.
"""
namespace = None
def __init__(self, otherHost):
self.otherHost = otherHost
def connectionMade(self):
self.xmlstream.namespace = self.namespace
self.xmlstream.otherHost = self.otherHost
self.xmlstream.sendHeader()
def initializeStream(self):
"""
Perform stream initialization procedures.
An L{XmlStream} holds a list of initializer objects in its
C{initializers} attribute. This method calls these initializers in
order and dispatches the C{STREAM_AUTHD_EVENT} event when the list has
been successfully processed. Otherwise it dispatches the
C{INIT_FAILED_EVENT} event with the failure.
Initializers may return the special L{Reset} object to halt the
initialization processing. It signals that the current initializer was
successfully processed, but that the XML Stream has been reset. An
example is the TLSInitiatingInitializer.
"""
def remove_first(result):
self.xmlstream.initializers.pop(0)
return result
def do_next(result):
"""
Take the first initializer and process it.
On success, the initializer is removed from the list and
then next initializer will be tried.
"""
if result is Reset:
return None
try:
init = self.xmlstream.initializers[0]
except IndexError:
self.xmlstream.dispatch(self.xmlstream, STREAM_AUTHD_EVENT)
return None
else:
d = defer.maybeDeferred(init.initialize)
d.addCallback(remove_first)
d.addCallback(do_next)
return d
d = defer.succeed(None)
d.addCallback(do_next)
d.addErrback(self.xmlstream.dispatch, INIT_FAILED_EVENT)
def streamStarted(self):
self.initializeStream()
class FeatureNotAdvertized(Exception):
"""
Exception indicating a stream feature was not advertized, while required by
the initiating entity.
"""
class BaseFeatureInitiatingInitializer(object):
"""
Base class for initializers with a stream feature.
This assumes the associated XmlStream represents the initiating entity
of the connection.
@cvar feature: tuple of (uri, name) of the stream feature root element.
@type feature: tuple of (L{str}, L{str})
@ivar required: whether the stream feature is required to be advertized
by the receiving entity.
@type required: L{bool}
"""
implements(ijabber.IInitiatingInitializer)
feature = None
required = False
def __init__(self, xs):
self.xmlstream = xs
def initialize(self):
"""
Initiate the initialization.
Checks if the receiving entity advertizes the stream feature. If it
does, the initialization is started. If it is not advertized, and the
C{required} instance variable is L{True}, it raises
L{FeatureNotAdvertized}. Otherwise, the initialization silently
succeeds.
"""
if self.feature in self.xmlstream.features:
return self.start()
elif self.required:
raise FeatureNotAdvertized
else:
return None
def start(self):
"""
Start the actual initialization.
May return a deferred for asynchronous initialization.
"""
class TLSError(Exception):
"""
TLS base exception.
"""
class TLSFailed(TLSError):
"""
Exception indicating failed TLS negotiation
"""
class TLSRequired(TLSError):
"""
Exception indicating required TLS negotiation.
This exception is raised when the receiving entity requires TLS
negotiation and the initiating does not desire to negotiate TLS.
"""
class TLSNotSupported(TLSError):
"""
Exception indicating missing TLS support.
This exception is raised when the initiating entity wants and requires to
negotiate TLS when the OpenSSL library is not available.
"""
class TLSInitiatingInitializer(BaseFeatureInitiatingInitializer):
"""
TLS stream initializer for the initiating entity.
It is strongly required to include this initializer in the list of
initializers for an XMPP stream. By default it will try to negotiate TLS.
An XMPP server may indicate that TLS is required. If TLS is not desired,
set the C{wanted} attribute to False instead of removing it from the list
of initializers, so a proper exception L{TLSRequired} can be raised.
@cvar wanted: indicates if TLS negotiation is wanted.
@type wanted: L{bool}
"""
feature = (NS_XMPP_TLS, 'starttls')
wanted = True
_deferred = None
def onProceed(self, obj):
"""
Proceed with TLS negotiation and reset the XML stream.
"""
self.xmlstream.removeObserver('/failure', self.onFailure)
ctx = ssl.CertificateOptions()
self.xmlstream.transport.startTLS(ctx)
self.xmlstream.reset()
self.xmlstream.sendHeader()
self._deferred.callback(Reset)
def onFailure(self, obj):
self.xmlstream.removeObserver('/proceed', self.onProceed)
self._deferred.errback(TLSFailed())
def start(self):
"""
Start TLS negotiation.
This checks if the receiving entity requires TLS, the SSL library is
available and uses the C{required} and C{wanted} instance variables to
determine what to do in the various different cases.
For example, if the SSL library is not available, and wanted and
required by the user, it raises an exception. However if it is not
required by both parties, initialization silently succeeds, moving
on to the next step.
"""
if self.wanted:
if ssl is None:
if self.required:
return defer.fail(TLSNotSupported())
else:
return defer.succeed(None)
else:
pass
elif self.xmlstream.features[self.feature].required:
return defer.fail(TLSRequired())
else:
return defer.succeed(None)
self._deferred = defer.Deferred()
self.xmlstream.addOnetimeObserver("/proceed", self.onProceed)
self.xmlstream.addOnetimeObserver("/failure", self.onFailure)
self.xmlstream.send(domish.Element((NS_XMPP_TLS, "starttls")))
return self._deferred
class XmlStream(xmlstream.XmlStream):
"""
XMPP XML Stream protocol handler.
@ivar version: XML stream version as a tuple (major, minor). Initially,
this is set to the minimally supported version. Upon
receiving the stream header of the peer, it is set to the
minimum of that value and the version on the received
header.
@type version: (L{int}, L{int})
@ivar namespace: default namespace URI for stream
@type namespace: L{str}
@ivar thisHost: hostname of this entity
@ivar otherHost: hostname of the peer entity
@ivar sid: session identifier
@type sid: L{str}
@ivar initiating: True if this is the initiating stream
@type initiating: L{bool}
@ivar features: map of (uri, name) to stream features element received from
the receiving entity.
@type features: L{dict} of (L{str}, L{str}) to L{domish.Element}.
@ivar prefixes: map of URI to prefixes that are to appear on stream
header.
@type prefixes: L{dict} of L{str} to L{str}
@ivar initializers: list of stream initializer objects
@type initializers: L{list} of objects that provide L{IInitializer}
@ivar authenticator: associated authenticator that uses C{initializers} to
initialize the XML stream.
"""
version = (1, 0)
namespace = 'invalid'
thisHost = None
otherHost = None
sid = None
initiating = True
prefixes = {NS_STREAMS: 'stream'}
_headerSent = False # True if the stream header has been sent
def __init__(self, authenticator):
xmlstream.XmlStream.__init__(self)
self.authenticator = authenticator
self.initializers = []
self.features = {}
# Reset the authenticator
authenticator.associateWithStream(self)
def _callLater(self, *args, **kwargs):
from twisted.internet import reactor
return reactor.callLater(*args, **kwargs)
def reset(self):
"""
Reset XML Stream.
Resets the XML Parser for incoming data. This is to be used after
successfully negotiating a new layer, e.g. TLS and SASL. Note that
registered event observers will continue to be in place.
"""
self._headerSent = False
self._initializeStream()
def onStreamError(self, errelem):
"""
Called when a stream:error element has been received.
Dispatches a L{STREAM_ERROR_EVENT} event with the error element to
allow for cleanup actions and drops the connection.
@param errelem: The received error element.
@type errelem: L{domish.Element}
"""
self.dispatch(failure.Failure(error.exceptionFromStreamError(errelem)),
STREAM_ERROR_EVENT)
self.transport.loseConnection()
def onFeatures(self, features):
"""
Called when a stream:features element has been received.
Stores the received features in the C{features} attribute, checks the
need for initiating TLS and notifies the authenticator of the start of
the stream.
@param features: The received features element.
@type features: L{domish.Element}
"""
self.features = {}
for feature in features.elements():
self.features[(feature.uri, feature.name)] = feature
self.authenticator.streamStarted()
def sendHeader(self):
"""
Send stream header.
"""
rootElem = domish.Element((NS_STREAMS, 'stream'), self.namespace)
if self.initiating and self.otherHost:
rootElem['to'] = self.otherHost
elif not self.initiating:
if self.thisHost:
rootElem['from'] = self.thisHost
if self.sid:
rootElem['id'] = self.sid
if self.version >= (1, 0):
rootElem['version'] = "%d.%d" % (self.version[0], self.version[1])
self.rootElem = rootElem
self.send(rootElem.toXml(prefixes=self.prefixes, closeElement=0))
self._headerSent = True
def sendFooter(self):
"""
Send stream footer.
"""
self.send('</stream:stream>')
def sendStreamError(self, streamError):
"""
Send stream level error.
If we are the receiving entity, and haven't sent the header yet,
we sent one first.
If the given C{failure} is a L{error.StreamError}, it is rendered
to its XML representation, otherwise a generic C{internal-error}
stream error is generated.
After sending the stream error, the stream is closed and the transport
connection dropped.
"""
if not self._headerSent and not self.initiating:
self.sendHeader()
if self._headerSent:
self.send(streamError.getElement())
self.sendFooter()
self.transport.loseConnection()
def send(self, obj):
"""
Send data over the stream.
This overrides L{xmlstream.Xmlstream.send} to use the default namespace
of the stream header when serializing L{domish.IElement}s. It is
assumed that if you pass an object that provides L{domish.IElement},
it represents a direct child of the stream's root element.
"""
if domish.IElement.providedBy(obj):
obj = obj.toXml(prefixes=self.prefixes,
defaultUri=self.namespace,
prefixesInScope=self.prefixes.values())
xmlstream.XmlStream.send(self, obj)
def connectionMade(self):
"""
Called when a connection is made.
Notifies the authenticator when a connection has been made.
"""
xmlstream.XmlStream.connectionMade(self)
self.authenticator.connectionMade()
def onDocumentStart(self, rootelem):
"""
Called when the stream header has been received.
Extracts the header's C{id} and C{version} attributes from the root
element. The C{id} attribute is stored in our C{sid} attribute and the
C{version} attribute is parsed and the minimum of the version we sent
and the parsed C{version} attribute is stored as a tuple (major, minor)
in this class' C{version} attribute. If no C{version} attribute was
present, we assume version 0.0.
If appropriate (we are the initiating stream and the minimum of our and
the other party's version is at least 1.0), a one-time observer is
registered for getting the stream features. The registered function is
C{onFeatures}.
Ultimately, the authenticator's C{streamStarted} method will be called.
@param rootelem: The root element.
@type rootelem: L{domish.Element}
"""
xmlstream.XmlStream.onDocumentStart(self, rootelem)
# Extract stream identifier
if rootelem.hasAttribute("id"):
self.sid = rootelem["id"]
# Extract stream version and take minimum with the version sent
if rootelem.hasAttribute("version"):
version = rootelem["version"].split(".")
try:
version = (int(version[0]), int(version[1]))
except IndexError, ValueError:
version = (0, 0)
else:
version = (0, 0)
self.version = min(self.version, version)
# Setup observer for stream errors
self.addOnetimeObserver("/error[@xmlns='%s']" % NS_STREAMS,
self.onStreamError)
# Setup observer for stream features, if applicable
if self.initiating and self.version >= (1, 0):
self.addOnetimeObserver('/features[@xmlns="%s"]' % NS_STREAMS,
self.onFeatures)
else:
self.authenticator.streamStarted()
class XmlStreamFactory(xmlstream.XmlStreamFactory):
def __init__(self, authenticator):
xmlstream.XmlStreamFactory.__init__(self)
self.authenticator = authenticator
def buildProtocol(self, _):
self.resetDelay()
# Create the stream and register all the bootstrap observers
xs = XmlStream(self.authenticator)
xs.factory = self
for event, fn in self.bootstraps: xs.addObserver(event, fn)
return xs
class TimeoutError(Exception):
"""
Exception raised when no IQ response has been received before the
configured timeout.
"""
def upgradeWithIQResponseTracker(xs):
"""
Enhances an XmlStream for iq response tracking.
This makes an L{XmlStream} object provide L{IIQResponseTracker}. When a
response is an error iq stanza, the deferred has its errback invoked with a
failure that holds a L{StanzaException<error.StanzaException>} that is
easier to examine.
"""
def callback(iq):
"""
Handle iq response by firing associated deferred.
"""
if getattr(iq, 'handled', False):
return
try:
d = xs.iqDeferreds[iq["id"]]
except KeyError:
pass
else:
del xs.iqDeferreds[iq["id"]]
iq.handled = True
if iq['type'] == 'error':
d.errback(error.exceptionFromStanza(iq))
else:
d.callback(iq)
def disconnected(_):
"""
Make sure deferreds do not linger on after disconnect.
This errbacks all deferreds of iq's for which no response has been
received with a L{ConnectionLost} failure. Otherwise, the deferreds
will never be fired.
"""
iqDeferreds = xs.iqDeferreds
xs.iqDeferreds = {}
for d in iqDeferreds.itervalues():
d.errback(ConnectionLost())
xs.iqDeferreds = {}
xs.iqDefaultTimeout = getattr(xs, 'iqDefaultTimeout', None)
xs.addObserver(xmlstream.STREAM_END_EVENT, disconnected)
xs.addObserver('/iq[@type="result"]', callback)
xs.addObserver('/iq[@type="error"]', callback)
directlyProvides(xs, ijabber.IIQResponseTracker)
class IQ(domish.Element):
"""
Wrapper for an iq stanza.
Iq stanzas are used for communications with a request-response behaviour.
Each iq request is associated with an XML stream and has its own unique id
to be able to track the response.
@ivar timeout: if set, a timeout period after which the deferred returned
by C{send} will have its errback called with a
L{TimeoutError} failure.
@type timeout: C{float}
"""
timeout = None
def __init__(self, xmlstream, type = "set"):
"""
@type xmlstream: L{xmlstream.XmlStream}
@param xmlstream: XmlStream to use for transmission of this IQ
@type type: L{str}
@param type: IQ type identifier ('get' or 'set')
"""
domish.Element.__init__(self, (None, "iq"))
self.addUniqueId()
self["type"] = type
self._xmlstream = xmlstream
def send(self, to=None):
"""
Send out this iq.
Returns a deferred that is fired when an iq response with the same id
is received. Result responses will be passed to the deferred callback.
Error responses will be transformed into a
L{StanzaError<error.StanzaError>} and result in the errback of the
deferred being invoked.
@rtype: L{defer.Deferred}
"""
if to is not None:
self["to"] = to
if not ijabber.IIQResponseTracker.providedBy(self._xmlstream):
upgradeWithIQResponseTracker(self._xmlstream)
d = defer.Deferred()
self._xmlstream.iqDeferreds[self['id']] = d
timeout = self.timeout or self._xmlstream.iqDefaultTimeout
if timeout is not None:
def onTimeout():
del self._xmlstream.iqDeferreds[self['id']]
d.errback(TimeoutError("IQ timed out"))
call = self._xmlstream._callLater(timeout, onTimeout)
def cancelTimeout(result):
if call.active():
call.cancel()
return result
d.addBoth(cancelTimeout)
self._xmlstream.send(self)
return d | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/protocols/jabber/xmlstream.py | xmlstream.py |
import base64
from twisted.internet import defer
from twisted.words.protocols.jabber import sasl_mechanisms, xmlstream
from twisted.words.xish import domish
NS_XMPP_SASL = 'urn:ietf:params:xml:ns:xmpp-sasl'
def get_mechanisms(xs):
"""
Parse the SASL feature to extract the available mechanism names.
"""
mechanisms = []
for element in xs.features[(NS_XMPP_SASL, 'mechanisms')].elements():
if element.name == 'mechanism':
mechanisms.append(str(element))
return mechanisms
class SASLError(Exception):
"""
SASL base exception.
"""
class SASLNoAcceptableMechanism(SASLError):
"""
The server did not present an acceptable SASL mechanism.
"""
class SASLAuthError(SASLError):
"""
SASL Authentication failed.
"""
def __init__(self, condition=None):
self.condition = condition
def __str__(self):
return "SASLAuthError with condition %r" % self.condition
class SASLInitiatingInitializer(xmlstream.BaseFeatureInitiatingInitializer):
"""
Stream initializer that performs SASL authentication.
The supported mechanisms by this initializer are C{DIGEST-MD5} and C{PLAIN}
which are attemped in that order.
"""
feature = (NS_XMPP_SASL, 'mechanisms')
_deferred = None
def start(self):
"""
Start SASL authentication exchange.
Used the authenticator's C{jid} and C{password} attribute for the
authentication credentials. If no supported SASL mechanisms are
advertized by the receiving party, a failing deferred is returned with
a L{SASLNoAcceptableMechanism} exception.
"""
jid = self.xmlstream.authenticator.jid
password = self.xmlstream.authenticator.password
mechanisms = get_mechanisms(self.xmlstream)
if 'DIGEST-MD5' in mechanisms:
self.mechanism = sasl_mechanisms.DigestMD5('xmpp', jid.host, None,
jid.user, password)
elif 'PLAIN' in mechanisms:
self.mechanism = sasl_mechanisms.Plain(None, jid.user, password)
else:
return defer.fail(SASLNoAcceptableMechanism)
self._deferred = defer.Deferred()
self.xmlstream.addObserver('/challenge', self.onChallenge)
self.xmlstream.addOnetimeObserver('/success', self.onSuccess)
self.xmlstream.addOnetimeObserver('/failure', self.onFailure)
self.sendAuth(self.mechanism.getInitialResponse())
return self._deferred
def sendAuth(self, data=None):
"""
Initiate authentication protocol exchange.
If an initial client response is given in C{data}, it will be
sent along.
@param data: initial client response.
@type data: L{str} or L{None}.
"""
auth = domish.Element((NS_XMPP_SASL, 'auth'))
auth['mechanism'] = self.mechanism.name
if data is not None:
auth.addContent(base64.b64encode(data) or '=')
self.xmlstream.send(auth)
def sendResponse(self, data=''):
"""
Send response to a challenge.
@param data: client response.
@type data: L{str}.
"""
response = domish.Element((NS_XMPP_SASL, 'response'))
if data:
response.addContent(base64.b64encode(data))
self.xmlstream.send(response)
def onChallenge(self, element):
"""
Parse challenge and send response from the mechanism.
@param element: the challenge protocol element.
@type element: L{domish.Element}.
"""
challenge = base64.b64decode(str(element))
self.sendResponse(self.mechanism.getResponse(challenge))
def onSuccess(self, success):
"""
Clean up observers, reset the XML stream and send a new header.
@param success: the success protocol element. For now unused, but
could hold additional data.
@type success: L{domish.Element}
"""
self.xmlstream.removeObserver('/challenge', self.onChallenge)
self.xmlstream.removeObserver('/failure', self.onFailure)
self.xmlstream.reset()
self.xmlstream.sendHeader()
self._deferred.callback(xmlstream.Reset)
def onFailure(self, failure):
"""
Clean up observers, parse the failure and errback the deferred.
@param failure: the failure protocol element. Holds details on
the error condition.
@type failure: L{domish.Element}
"""
self.xmlstream.removeObserver('/challenge', self.onChallenge)
self.xmlstream.removeObserver('/success', self.onSuccess)
try:
condition = failure.firstChildElement().name
except AttributeError:
condition = None
self._deferred.errback(SASLAuthError(condition)) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/protocols/jabber/sasl.py | sasl.py |
from zope.interface import implements
from twisted.application import service
from twisted.internet import defer
from twisted.words.xish import domish
from twisted.words.protocols.jabber import ijabber, jstrports, xmlstream
def componentFactory(componentid, password):
"""
XML stream factory for external server-side components.
@param componentid: JID of the component.
@type componentid: L{unicode}
@param password: password used to authenticate to the server.
@type password: L{str}
"""
a = ConnectComponentAuthenticator(componentid, password)
return xmlstream.XmlStreamFactory(a)
class ComponentInitiatingInitializer(object):
"""
External server-side component authentication initializer for the
initiating entity.
@ivar xmlstream: XML stream between server and component.
@type xmlstream: L{xmlstream.XmlStream}
"""
def __init__(self, xs):
self.xmlstream = xs
self._deferred = None
def initialize(self):
xs = self.xmlstream
hs = domish.Element((self.xmlstream.namespace, "handshake"))
hs.addContent(xmlstream.hashPassword(xs.sid,
xs.authenticator.password))
# Setup observer to watch for handshake result
xs.addOnetimeObserver("/handshake", self._cbHandshake)
xs.send(hs)
self._deferred = defer.Deferred()
return self._deferred
def _cbHandshake(self, _):
# we have successfully shaken hands and can now consider this
# entity to represent the component JID.
self.xmlstream.thisHost = self.xmlstream.otherHost
self._deferred.callback(None)
class ConnectComponentAuthenticator(xmlstream.ConnectAuthenticator):
"""
Authenticator to permit an XmlStream to authenticate against a Jabber
server as an external component (where the Authenticator is initiating the
stream).
"""
namespace = 'jabber:component:accept'
def __init__(self, componentjid, password):
"""
@type componentjid: L{str}
@param componentjid: Jabber ID that this component wishes to bind to.
@type password: L{str}
@param password: Password/secret this component uses to authenticate.
"""
# Note that we are sending 'to' our desired component JID.
xmlstream.ConnectAuthenticator.__init__(self, componentjid)
self.password = password
def associateWithStream(self, xs):
xs.version = (0, 0)
xmlstream.ConnectAuthenticator.associateWithStream(self, xs)
xs.initializers = [ComponentInitiatingInitializer(xs)]
class ListenComponentAuthenticator(xmlstream.Authenticator):
"""
Placeholder for listening components.
"""
class Service(service.Service):
"""
External server-side component service.
"""
implements(ijabber.IService)
def componentConnected(self, xs):
pass
def componentDisconnected(self):
pass
def transportConnected(self, xs):
pass
def send(self, obj):
"""
Send data over service parent's XML stream.
@note: L{ServiceManager} maintains a queue for data sent using this
method when there is no current established XML stream. This data is
then sent as soon as a new stream has been established and initialized.
Subsequently, L{componentConnected} will be called again. If this
queueing is not desired, use C{send} on the XmlStream object (passed to
L{componentConnected}) directly.
@param obj: data to be sent over the XML stream. This is usually an
object providing L{domish.IElement}, or serialized XML. See
L{xmlstream.XmlStream} for details.
"""
self.parent.send(obj)
class ServiceManager(service.MultiService):
"""
Business logic representing a managed component connection to a Jabber
router.
This service maintains a single connection to a Jabber router and provides
facilities for packet routing and transmission. Business logic modules are
services implementing L{ijabber.IService} (like subclasses of L{Service}), and
added as sub-service.
"""
def __init__(self, jid, password):
service.MultiService.__init__(self)
# Setup defaults
self.jabberId = jid
self.xmlstream = None
# Internal buffer of packets
self._packetQueue = []
# Setup the xmlstream factory
self._xsFactory = componentFactory(self.jabberId, password)
# Register some lambda functions to keep the self.xmlstream var up to
# date
self._xsFactory.addBootstrap(xmlstream.STREAM_CONNECTED_EVENT,
self._connected)
self._xsFactory.addBootstrap(xmlstream.STREAM_AUTHD_EVENT, self._authd)
self._xsFactory.addBootstrap(xmlstream.STREAM_END_EVENT,
self._disconnected)
# Map addBootstrap and removeBootstrap to the underlying factory -- is
# this right? I have no clue...but it'll work for now, until i can
# think about it more.
self.addBootstrap = self._xsFactory.addBootstrap
self.removeBootstrap = self._xsFactory.removeBootstrap
def getFactory(self):
return self._xsFactory
def _connected(self, xs):
self.xmlstream = xs
for c in self:
if ijabber.IService.providedBy(c):
c.transportConnected(xs)
def _authd(self, xs):
# Flush all pending packets
for p in self._packetQueue:
self.xmlstream.send(p)
self._packetQueue = []
# Notify all child services which implement the IService interface
for c in self:
if ijabber.IService.providedBy(c):
c.componentConnected(xs)
def _disconnected(self, _):
self.xmlstream = None
# Notify all child services which implement
# the IService interface
for c in self:
if ijabber.IService.providedBy(c):
c.componentDisconnected()
def send(self, obj):
"""
Send data over the XML stream.
When there is no established XML stream, the data is queued and sent
out when a new XML stream has been established and initialized.
@param obj: data to be sent over the XML stream. This is usually an
object providing L{domish.IElement}, or serialized XML. See
L{xmlstream.XmlStream} for details.
"""
if self.xmlstream != None:
self.xmlstream.send(obj)
else:
self._packetQueue.append(obj)
def buildServiceManager(jid, password, strport):
"""
Constructs a pre-built L{ServiceManager}, using the specified strport
string.
"""
svc = ServiceManager(jid, password)
client_svc = jstrports.client(strport, svc.getFactory())
client_svc.setServiceParent(svc)
return svc | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/protocols/jabber/component.py | component.py |
import md5, binascii, random, time, os
from zope.interface import Interface, Attribute, implements
class ISASLMechanism(Interface):
name = Attribute("""Common name for the SASL Mechanism.""")
def getInitialResponse():
"""
Get the initial client response, if defined for this mechanism.
@return: initial client response string.
@rtype: L{str}.
"""
def getResponse(challenge):
"""
Get the response to a server challenge.
@param challenge: server challenge.
@type challenge: L{str}.
@return: client response.
@rtype: L{str}.
"""
class Plain(object):
"""
Implements the PLAIN SASL authentication mechanism.
The PLAIN SASL authentication mechanism is defined in RFC 2595.
"""
implements(ISASLMechanism)
name = 'PLAIN'
def __init__(self, authzid, authcid, password):
self.authzid = authzid or ''
self.authcid = authcid or ''
self.password = password or ''
def getInitialResponse(self):
return "%s\x00%s\x00%s" % (self.authzid.encode('utf-8'),
self.authcid.encode('utf-8'),
self.password.encode('utf-8'))
class DigestMD5(object):
"""
Implements the DIGEST-MD5 SASL authentication mechanism.
The DIGEST-MD5 SASL authentication mechanism is defined in RFC 2831.
"""
implements(ISASLMechanism)
name = 'DIGEST-MD5'
def __init__(self, serv_type, host, serv_name, username, password):
self.username = username
self.password = password
self.defaultRealm = host
self.digest_uri = '%s/%s' % (serv_type, host)
if serv_name is not None:
self.digest_uri += '/%s' % serv_name
def getInitialResponse(self):
return None
def getResponse(self, challenge):
directives = self._parse(challenge)
# Compat for implementations that do not send this along with
# a succesful authentication.
if directives.has_key('rspauth'):
return ''
try:
realm = directives['realm']
except KeyError:
realm = self.defaultRealm
return self._gen_response(directives['charset'],
realm,
directives['nonce'])
def _parse(self, challenge):
"""
Parses the server challenge.
Splits the challenge into a dictionary of directives with values.
@return: challenge directives and their values.
@rtype: L{dict} of L{str} to L{str}.
"""
directive_list = challenge.split(',')
directives = {}
for directive in directive_list:
name, value = directive.split('=')
value = value.replace("'","")
value = value.replace('"','')
directives[name] = value
return directives
def _unparse(self, directives):
"""
Create message string from directives.
@param directives: dictionary of directives (names to their values).
For certain directives, extra quotes are added, as
needed.
@type directives: L{dict} of L{str} to L{str}
@return: message string.
@rtype: L{str}.
"""
directive_list = []
for name, value in directives.iteritems():
if name in ('username', 'realm', 'cnonce',
'nonce', 'digest-uri', 'authzid'):
directive = '%s="%s"' % (name, value)
else:
directive = '%s=%s' % (name, value)
directive_list.append(directive)
return ','.join(directive_list)
def _gen_response(self, charset, realm, nonce):
"""
Generate response-value.
Creates a response to a challenge according to section 2.1.2.1 of
RFC 2831 using the L{charset}, L{realm} and L{nonce} directives
from the challenge.
"""
def H(s):
return md5.new(s).digest()
def HEX(n):
return binascii.b2a_hex(n)
def KD(k, s):
return H('%s:%s' % (k, s))
try:
username = self.username.encode(charset)
password = self.password.encode(charset)
except UnicodeError:
# TODO - add error checking
raise
nc = '%08x' % 1 # TODO: support subsequent auth.
cnonce = self._gen_nonce()
qop = 'auth'
# TODO - add support for authzid
a1 = "%s:%s:%s" % (H("%s:%s:%s" % (username, realm, password)),
nonce,
cnonce)
a2 = "AUTHENTICATE:%s" % self.digest_uri
response = HEX( KD ( HEX(H(a1)),
"%s:%s:%s:%s:%s" % (nonce, nc,
cnonce, "auth", HEX(H(a2)))))
directives = {'username': username,
'realm' : realm,
'nonce' : nonce,
'cnonce' : cnonce,
'nc' : nc,
'qop' : qop,
'digest-uri': self.digest_uri,
'response': response,
'charset': charset}
return self._unparse(directives)
def _gen_nonce(self):
return md5.new("%s:%s:%s" % (str(random.random()) , str(time.gmtime()),str(os.getpid()))).hexdigest() | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/protocols/jabber/sasl_mechanisms.py | sasl_mechanisms.py |
from twisted.internet import defer
from twisted.words.xish import domish, xpath, utility
from twisted.words.protocols.jabber import xmlstream, sasl, error
from twisted.words.protocols.jabber.jid import JID
NS_XMPP_STREAMS = 'urn:ietf:params:xml:ns:xmpp-streams'
NS_XMPP_BIND = 'urn:ietf:params:xml:ns:xmpp-bind'
NS_XMPP_SESSION = 'urn:ietf:params:xml:ns:xmpp-session'
NS_IQ_AUTH_FEATURE = 'http://jabber.org/features/iq-auth'
DigestAuthQry = xpath.internQuery("/iq/query/digest")
PlaintextAuthQry = xpath.internQuery("/iq/query/password")
def basicClientFactory(jid, secret):
a = BasicAuthenticator(jid, secret)
return xmlstream.XmlStreamFactory(a)
class IQ(domish.Element):
"""
Wrapper for a Info/Query packet.
This provides the necessary functionality to send IQs and get notified when
a result comes back. It's a subclass from L{domish.Element}, so you can use
the standard DOM manipulation calls to add data to the outbound request.
@type callbacks: L{utility.CallbackList}
@cvar callbacks: Callback list to be notified when response comes back
"""
def __init__(self, xmlstream, type = "set"):
"""
@type xmlstream: L{xmlstream.XmlStream}
@param xmlstream: XmlStream to use for transmission of this IQ
@type type: L{str}
@param type: IQ type identifier ('get' or 'set')
"""
domish.Element.__init__(self, ("jabber:client", "iq"))
self.addUniqueId()
self["type"] = type
self._xmlstream = xmlstream
self.callbacks = utility.CallbackList()
def addCallback(self, fn, *args, **kwargs):
"""
Register a callback for notification when the IQ result is available.
"""
self.callbacks.addCallback(True, fn, *args, **kwargs)
def send(self, to = None):
"""
Call this method to send this IQ request via the associated XmlStream.
@param to: Jabber ID of the entity to send the request to
@type to: L{str}
@returns: Callback list for this IQ. Any callbacks added to this list
will be fired when the result comes back.
"""
if to != None:
self["to"] = to
self._xmlstream.addOnetimeObserver("/iq[@id='%s']" % self["id"], \
self._resultEvent)
self._xmlstream.send(self)
def _resultEvent(self, iq):
self.callbacks.callback(iq)
self.callbacks = None
class IQAuthInitializer(object):
"""
Non-SASL Authentication initializer for the initiating entity.
This protocol is defined in
U{JEP-0078<http://www.jabber.org/jeps/jep-0078.html>} and mainly serves for
compatibility with pre-XMPP-1.0 server implementations.
"""
INVALID_USER_EVENT = "//event/client/basicauth/invaliduser"
AUTH_FAILED_EVENT = "//event/client/basicauth/authfailed"
def __init__(self, xs):
self.xmlstream = xs
def initialize(self):
# Send request for auth fields
iq = xmlstream.IQ(self.xmlstream, "get")
iq.addElement(("jabber:iq:auth", "query"))
jid = self.xmlstream.authenticator.jid
iq.query.addElement("username", content = jid.user)
d = iq.send()
d.addCallbacks(self._cbAuthQuery, self._ebAuthQuery)
return d
def _cbAuthQuery(self, iq):
jid = self.xmlstream.authenticator.jid
password = self.xmlstream.authenticator.password
# Construct auth request
reply = xmlstream.IQ(self.xmlstream, "set")
reply.addElement(("jabber:iq:auth", "query"))
reply.query.addElement("username", content = jid.user)
reply.query.addElement("resource", content = jid.resource)
# Prefer digest over plaintext
if DigestAuthQry.matches(iq):
digest = xmlstream.hashPassword(self.xmlstream.sid, password)
reply.query.addElement("digest", content = digest)
else:
reply.query.addElement("password", content = password)
d = reply.send()
d.addCallbacks(self._cbAuth, self._ebAuth)
return d
def _ebAuthQuery(self, failure):
failure.trap(error.StanzaError)
e = failure.value
if e.condition == 'not-authorized':
self.xmlstream.dispatch(e.stanza, self.INVALID_USER_EVENT)
else:
self.xmlstream.dispatch(e.stanza, self.AUTH_FAILED_EVENT)
return failure
def _cbAuth(self, iq):
pass
def _ebAuth(self, failure):
failure.trap(error.StanzaError)
self.xmlstream.dispatch(failure.value.stanza, self.AUTH_FAILED_EVENT)
return failure
class BasicAuthenticator(xmlstream.ConnectAuthenticator):
"""
Authenticates an XmlStream against a Jabber server as a Client.
This only implements non-SASL authentication, per
U{JEP-0078<http://www.jabber.org/jeps/jep-0078.html>}. Additionally, this
authenticator provides the ability to perform inline registration, per
U{JEP-0077<http://www.jabber.org/jeps/jep-0077.html>}.
Under normal circumstances, the BasicAuthenticator generates the
L{xmlstream.STREAM_AUTHD_EVENT} once the stream has authenticated. However,
it can also generate other events, such as:
- L{INVALID_USER_EVENT} : Authentication failed, due to invalid username
- L{AUTH_FAILED_EVENT} : Authentication failed, due to invalid password
- L{REGISTER_FAILED_EVENT} : Registration failed
If authentication fails for any reason, you can attempt to register by
calling the L{registerAccount} method. If the registration succeeds, a
L{xmlstream.STREAM_AUTHD_EVENT} will be fired. Otherwise, one of the above
errors will be generated (again).
"""
namespace = "jabber:client"
INVALID_USER_EVENT = IQAuthInitializer.INVALID_USER_EVENT
AUTH_FAILED_EVENT = IQAuthInitializer.AUTH_FAILED_EVENT
REGISTER_FAILED_EVENT = "//event/client/basicauth/registerfailed"
def __init__(self, jid, password):
xmlstream.ConnectAuthenticator.__init__(self, jid.host)
self.jid = jid
self.password = password
def associateWithStream(self, xs):
xs.version = (0, 0)
xmlstream.ConnectAuthenticator.associateWithStream(self, xs)
inits = [ (xmlstream.TLSInitiatingInitializer, False),
(IQAuthInitializer, True),
]
for initClass, required in inits:
init = initClass(xs)
init.required = required
xs.initializers.append(init)
# TODO: move registration into an Initializer?
def registerAccount(self, username = None, password = None):
if username:
self.jid.user = username
if password:
self.password = password
iq = IQ(self.xmlstream, "set")
iq.addElement(("jabber:iq:register", "query"))
iq.query.addElement("username", content = self.jid.user)
iq.query.addElement("password", content = self.password)
iq.addCallback(self._registerResultEvent)
iq.send()
def _registerResultEvent(self, iq):
if iq["type"] == "result":
# Registration succeeded -- go ahead and auth
self.streamStarted()
else:
# Registration failed
self.xmlstream.dispatch(iq, self.REGISTER_FAILED_EVENT)
class CheckVersionInitializer(object):
"""
Initializer that checks if the minimum common stream version number is 1.0.
"""
def __init__(self, xs):
self.xmlstream = xs
def initialize(self):
if self.xmlstream.version < (1, 0):
raise error.StreamError('unsupported-version')
class BindInitializer(xmlstream.BaseFeatureInitiatingInitializer):
"""
Initializer that implements Resource Binding for the initiating entity.
This protocol is documented in U{RFC 3920, section
7<http://www.xmpp.org/specs/rfc3920.html#bind>}.
"""
feature = (NS_XMPP_BIND, 'bind')
def start(self):
iq = xmlstream.IQ(self.xmlstream, 'set')
bind = iq.addElement((NS_XMPP_BIND, 'bind'))
resource = self.xmlstream.authenticator.jid.resource
if resource:
bind.addElement('resource', content=resource)
d = iq.send()
d.addCallback(self.onBind)
return d
def onBind(self, iq):
if iq.bind:
self.xmlstream.authenticator.jid = JID(unicode(iq.bind.jid))
class SessionInitializer(xmlstream.BaseFeatureInitiatingInitializer):
"""
Initializer that implements session establishment for the initiating
entity.
This protocol is defined in U{RFC 3921, section
3<http://www.xmpp.org/specs/rfc3921.html#session>}.
"""
feature = (NS_XMPP_SESSION, 'session')
def start(self):
iq = xmlstream.IQ(self.xmlstream, 'set')
session = iq.addElement((NS_XMPP_SESSION, 'session'))
return iq.send()
def XMPPClientFactory(jid, password):
"""
Client factory for XMPP 1.0 (only).
This returns a L{xmlstream.XmlStreamFactory} with an L{XMPPAuthenticator}
object to perform the stream initialization steps (such as authentication}.
@see: The notes at L{XMPPAuthenticator} describe how the L{jid} and
L{password} parameters are to be used.
@param jid: Jabber ID to connect with.
@type jid: L{jid.JID}
@param password: password to authenticate with.
@type password: L{unicode}
@return: XML stream factory.
@rtype: L{xmlstream.XmlStreamFactory}
"""
a = XMPPAuthenticator(jid, password)
return xmlstream.XmlStreamFactory(a)
class XMPPAuthenticator(xmlstream.ConnectAuthenticator):
"""
Initializes an XmlStream connecting to an XMPP server as a Client.
This authenticator performs the initialization steps needed to start
exchanging XML stanzas with an XMPP server as an XMPP client. It checks if
the server advertises XML stream version 1.0, negotiates TLS (when
available), performs SASL authentication, binds a resource and establishes
a session.
Upon successful stream initialization, the L{xmlstream.STREAM_AUTHD_EVENT}
event will be dispatched through the XML stream object. Otherwise, the
L{xmlstream.INIT_FAILED_EVENT} event will be dispatched with a failure
object.
After inspection of the failure, initialization can then be restarted by
calling L{initializeStream}. For example, in case of authentication
failure, a user may be given the opportunity to input the correct password.
By setting the L{password} instance variable and restarting initialization,
the stream authentication step is then retried, and subsequent steps are
performed if succesful.
@ivar jid: Jabber ID to authenticate with. This may contain a resource
part, as a suggestion to the server for resource binding. A
server may override this, though. If the resource part is left
off, the server will generate a unique resource identifier.
The server will always return the full Jabber ID in the
resource binding step, and this is stored in this instance
variable.
@type jid: L{jid.JID}
@ivar password: password to be used during SASL authentication.
@type password: L{unicode}
"""
namespace = 'jabber:client'
def __init__(self, jid, password):
xmlstream.ConnectAuthenticator.__init__(self, jid.host)
self.jid = jid
self.password = password
def associateWithStream(self, xs):
"""
Register with the XML stream.
Populates stream's list of initializers, along with their
requiredness. This list is used by
L{ConnectAuthenticator.initializeStream} to perform the initalization
steps.
"""
xmlstream.ConnectAuthenticator.associateWithStream(self, xs)
xs.initializers = [CheckVersionInitializer(xs)]
inits = [ (xmlstream.TLSInitiatingInitializer, False),
(sasl.SASLInitiatingInitializer, True),
(BindInitializer, False),
(SessionInitializer, False),
]
for initClass, required in inits:
init = initClass(xs)
init.required = required
xs.initializers.append(init) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/protocols/jabber/client.py | client.py |
import sys, warnings
from zope.interface import Interface, implements
if sys.version_info < (2,3,2):
import re
class IDNA:
dots = re.compile(u"[\u002E\u3002\uFF0E\uFF61]")
def nameprep(self, label):
return label.lower()
idna = IDNA()
crippled = True
warnings.warn("Accented and non-Western Jabber IDs will not be properly "
"case-folded with this version of Python, resulting in "
"incorrect protocol-level behavior. It is strongly "
"recommended you upgrade to Python 2.3.2 or newer if you "
"intend to use Twisted's Jabber support.")
else:
import stringprep
import unicodedata
from encodings import idna
crippled = False
del sys, warnings
class ILookupTable(Interface):
""" Interface for character lookup classes. """
def lookup(c):
""" Return whether character is in this table. """
class IMappingTable(Interface):
""" Interface for character mapping classes. """
def map(c):
""" Return mapping for character. """
class LookupTableFromFunction:
implements(ILookupTable)
def __init__(self, in_table_function):
self.lookup = in_table_function
class LookupTable:
implements(ILookupTable)
def __init__(self, table):
self._table = table
def lookup(self, c):
return c in self._table
class MappingTableFromFunction:
implements(IMappingTable)
def __init__(self, map_table_function):
self.map = map_table_function
class EmptyMappingTable:
implements(IMappingTable)
def __init__(self, in_table_function):
self._in_table_function = in_table_function
def map(self, c):
if self._in_table_function(c):
return None
else:
return c
class Profile:
def __init__(self, mappings=[], normalize=True, prohibiteds=[],
check_unassigneds=True, check_bidi=True):
self.mappings = mappings
self.normalize = normalize
self.prohibiteds = prohibiteds
self.do_check_unassigneds = check_unassigneds
self.do_check_bidi = check_bidi
def prepare(self, string):
result = self.map(string)
if self.normalize:
result = unicodedata.normalize("NFKC", result)
self.check_prohibiteds(result)
if self.do_check_unassigneds:
self.check_unassigneds(result)
if self.do_check_bidi:
self.check_bidirectionals(result)
return result
def map(self, string):
result = []
for c in string:
result_c = c
for mapping in self.mappings:
result_c = mapping.map(c)
if result_c != c:
break
if result_c is not None:
result.append(result_c)
return u"".join(result)
def check_prohibiteds(self, string):
for c in string:
for table in self.prohibiteds:
if table.lookup(c):
raise UnicodeError, "Invalid character %s" % repr(c)
def check_unassigneds(self, string):
for c in string:
if stringprep.in_table_a1(c):
raise UnicodeError, "Unassigned code point %s" % repr(c)
def check_bidirectionals(self, string):
found_LCat = False
found_RandALCat = False
for c in string:
if stringprep.in_table_d1(c):
found_RandALCat = True
if stringprep.in_table_d2(c):
found_LCat = True
if found_LCat and found_RandALCat:
raise UnicodeError, "Violation of BIDI Requirement 2"
if found_RandALCat and not (stringprep.in_table_d1(string[0]) and
stringprep.in_table_d1(string[-1])):
raise UnicodeError, "Violation of BIDI Requirement 3"
class NamePrep:
""" Implements preparation of internationalized domain names.
This class implements preparing internationalized domain names using the
rules defined in RFC 3491, section 4 (Conversion operations).
We do not perform step 4 since we deal with unicode representations of
domain names and do not convert from or to ASCII representations using
punycode encoding. When such a conversion is needed, the L{idna} standard
library provides the C{ToUnicode()} and C{ToASCII()} functions. Note that
L{idna} itself assumes UseSTD3ASCIIRules to be false.
The following steps are performed by C{prepare()}:
- Split the domain name in labels at the dots (RFC 3490, 3.1)
- Apply nameprep proper on each label (RFC 3491)
- Enforce the restrictions on ASCII characters in host names by
assuming STD3ASCIIRules to be true. (STD 3)
- Rejoin the labels using the label separator U+002E (full stop).
"""
# Prohibited characters.
prohibiteds = [unichr(n) for n in range(0x00, 0x2c + 1) +
range(0x2e, 0x2f + 1) +
range(0x3a, 0x40 + 1) +
range(0x5b, 0x60 + 1) +
range(0x7b, 0x7f + 1) ]
def prepare(self, string):
result = []
labels = idna.dots.split(string)
if labels and len(labels[-1]) == 0:
trailing_dot = '.'
del labels[-1]
else:
trailing_dot = ''
for label in labels:
result.append(self.nameprep(label))
return ".".join(result) + trailing_dot
def check_prohibiteds(self, string):
for c in string:
if c in self.prohibiteds:
raise UnicodeError, "Invalid character %s" % repr(c)
def nameprep(self, label):
label = idna.nameprep(label)
self.check_prohibiteds(label)
if label[0] == '-':
raise UnicodeError, "Invalid leading hyphen-minus"
if label[-1] == '-':
raise UnicodeError, "Invalid trailing hyphen-minus"
return label
if crippled:
case_map = MappingTableFromFunction(lambda c: c.lower())
nodeprep = Profile(mappings=[case_map],
normalize=False,
prohibiteds=[LookupTable([u' ', u'"', u'&', u"'", u'/',
u':', u'<', u'>', u'@'])],
check_unassigneds=False,
check_bidi=False)
resourceprep = Profile(normalize=False,
check_unassigneds=False,
check_bidi=False)
else:
C_11 = LookupTableFromFunction(stringprep.in_table_c11)
C_12 = LookupTableFromFunction(stringprep.in_table_c12)
C_21 = LookupTableFromFunction(stringprep.in_table_c21)
C_22 = LookupTableFromFunction(stringprep.in_table_c22)
C_3 = LookupTableFromFunction(stringprep.in_table_c3)
C_4 = LookupTableFromFunction(stringprep.in_table_c4)
C_5 = LookupTableFromFunction(stringprep.in_table_c5)
C_6 = LookupTableFromFunction(stringprep.in_table_c6)
C_7 = LookupTableFromFunction(stringprep.in_table_c7)
C_8 = LookupTableFromFunction(stringprep.in_table_c8)
C_9 = LookupTableFromFunction(stringprep.in_table_c9)
B_1 = EmptyMappingTable(stringprep.in_table_b1)
B_2 = MappingTableFromFunction(stringprep.map_table_b2)
nodeprep = Profile(mappings=[B_1, B_2],
prohibiteds=[C_11, C_12, C_21, C_22,
C_3, C_4, C_5, C_6, C_7, C_8, C_9,
LookupTable([u'"', u'&', u"'", u'/',
u':', u'<', u'>', u'@'])])
resourceprep = Profile(mappings=[B_1,],
prohibiteds=[C_12, C_21, C_22,
C_3, C_4, C_5, C_6, C_7, C_8, C_9])
nameprep = NamePrep() | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/protocols/jabber/xmpp_stringprep.py | xmpp_stringprep.py |
from twisted.words.xish import domish
NS_XML = "http://www.w3.org/XML/1998/namespace"
NS_XMPP_STANZAS = "urn:ietf:params:xml:ns:xmpp-stanzas"
STANZA_CONDITIONS = {
'bad-request': {'code': '400', 'type': 'modify'},
'conflict': {'code': '409', 'type': 'cancel'},
'feature-not-implemented': {'code': '501', 'type': 'cancel'},
'forbidden': {'code': '403', 'type': 'auth'},
'gone': {'code': '302', 'type': 'modify'},
'internal-server-error': {'code': '500', 'type': 'wait'},
'item-not-found': {'code': '404', 'type': 'cancel'},
'jid-malformed': {'code': '400', 'type': 'modify'},
'not-acceptable': {'code': '406', 'type': 'modify'},
'not-allowed': {'code': '405', 'type': 'cancel'},
'not-authorized': {'code': '401', 'type': 'auth'},
'payment-required': {'code': '402', 'type': 'auth'},
'recipient-unavailable': {'code': '404', 'type': 'wait'},
'redirect': {'code': '302', 'type': 'modify'},
'registration-required': {'code': '407', 'type': 'auth'},
'remote-server-not-found': {'code': '404', 'type': 'cancel'},
'remove-server-timeout': {'code': '504', 'type': 'wait'},
'resource-constraint': {'code': '500', 'type': 'wait'},
'service-unavailable': {'code': '503', 'type': 'cancel'},
'subscription-required': {'code': '407', 'type': 'auth'},
'undefined-condition': {'code': '500', 'type': None},
'unexpected-request': {'code': '400', 'type': 'wait'},
}
CODES_TO_CONDITIONS = {
'302': ('gone', 'modify'),
'400': ('bad-request', 'modify'),
'401': ('not-authorized', 'auth'),
'402': ('payment-required', 'auth'),
'403': ('forbidden', 'auth'),
'404': ('item-not-found', 'cancel'),
'405': ('not-allowed', 'cancel'),
'406': ('not-acceptable', 'modify'),
'407': ('registration-required', 'auth'),
'408': ('remote-server-timeout', 'wait'),
'409': ('conflict', 'cancel'),
'500': ('internal-server-error', 'wait'),
'501': ('feature-not-implemented', 'cancel'),
'502': ('service-unavailable', 'wait'),
'503': ('service-unavailable', 'cancel'),
'504': ('remote-server-timeout', 'wait'),
'510': ('service-unavailable', 'cancel'),
}
class Error(Exception):
"""
Generic XMPP error exception.
"""
def __init__(self, condition, text=None, textLang=None, appCondition=None):
Exception.__init__(self)
self.condition = condition
self.text = text
self.textLang = textLang
self.appCondition = appCondition
def __str__(self):
message = "%s with condition %r" % (self.__class__.__name__,
self.condition)
if self.text:
message += ': ' + self.text
return message
def getElement(self):
"""
Get XML representation from self.
The method creates an L{domish} representation of the
error data contained in this exception.
@rtype: L{domish.Element}
"""
error = domish.Element((None, 'error'))
error.addElement((NS_XMPP_STANZAS, self.condition))
if self.text:
text = error.addElement((NS_XMPP_STANZAS, 'text'),
content=self.text)
if self.textLang:
text[(NS_XML, 'lang')] = self.textLang
if self.appCondition:
error.addChild(self.appCondition)
return error
class StreamError(Error):
"""
Stream Error exception.
"""
def getElement(self):
"""
Get XML representation from self.
Overrides the base L{Error.getElement} to make sure the returned
element is in the XML Stream namespace.
@rtype: L{domish.Element}
"""
from twisted.words.protocols.jabber.xmlstream import NS_STREAMS
error = Error.getElement(self)
error.uri = NS_STREAMS
return error
class StanzaError(Error):
"""
Stanza Error exception.
"""
def __init__(self, condition, type=None, text=None, textLang=None,
appCondition=None):
Error.__init__(self, condition, text, textLang, appCondition)
if type is None:
try:
type = STANZA_CONDITIONS[condition]['type']
except KeyError:
pass
self.type = type
try:
self.code = STANZA_CONDITIONS[condition]['code']
except KeyError:
self.code = None
self.children = []
self.iq = None
def getElement(self):
"""
Get XML representation from self.
Overrides the base L{Error.getElement} to make sure the returned
element has a C{type} attribute and optionally a legacy C{code}
attribute.
@rtype: L{domish.Element}
"""
error = Error.getElement(self)
error['type'] = self.type
if self.code:
error['code'] = self.code
return error
def toResponse(self, stanza):
"""
Construct error response stanza.
The C{stanza} is transformed into an error response stanza by
swapping the C{to} and C{from} addresses and inserting an error
element.
@param stanza: the stanza to respond to
@type stanza: L{domish.Element}
"""
if stanza.getAttribute('to'):
stanza.swapAttributeValues('to', 'from')
stanza['type'] = 'error'
stanza.addChild(self.getElement())
return stanza
def _getText(element):
for child in element.children:
if isinstance(child, basestring):
return unicode(child)
return None
def _parseError(error):
"""
Parses an error element.
@param error: the error element to be parsed
@type error: L{domish.Element}
@return: dictionary with extracted error information. If present, keys
C{condition}, C{text}, C{textLang} have a string value,
and C{appCondition} has an L{domish.Element} value.
@rtype: L{dict}
"""
condition = None
text = None
textLang = None
appCondition = None
for element in error.elements():
if element.uri == NS_XMPP_STANZAS:
if element.name == 'text':
text = _getText(element)
textLang = element.getAttribute((NS_XML, 'lang'))
else:
condition = element.name
else:
appCondition = element
return {
'condition': condition,
'text': text,
'textLang': textLang,
'appCondition': appCondition,
}
def exceptionFromStreamError(element):
"""
Build an exception object from a stream error.
@param element: the stream error
@type element: L{domish.Element}
@return: the generated exception object
@rtype: L{StreamError}
"""
error = _parseError(element)
exception = StreamError(error['condition'],
error['text'],
error['textLang'],
error['appCondition'])
return exception
def exceptionFromStanza(stanza):
"""
Build an exception object from an error stanza.
@param stanza: the error stanza
@type stanza: L{domish.Element}
@return: the generated exception object
@rtype: L{StanzaError}
"""
children = []
condition = text = textLang = appCondition = type = code = None
for element in stanza.elements():
if element.name == 'error' and element.uri == stanza.uri:
code = element.getAttribute('code')
type = element.getAttribute('type')
error = _parseError(element)
condition = error['condition']
text = error['text']
textLang = error['textLang']
appCondition = error['appCondition']
if not condition and code:
condition, type = CODES_TO_CONDITIONS[code]
text = _getText(stanza.error)
else:
children.append(element)
if condition is None:
# TODO: raise exception instead?
return StanzaError(None)
exception = StanzaError(condition, type, text, textLang, appCondition)
exception.children = children
exception.stanza = stanza
return exception | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/protocols/jabber/error.py | error.py |
from twisted.internet import reactor, protocol, defer
from twisted.words.xish import domish, utility
from twisted.words.protocols.jabber.xmpp_stringprep import nodeprep, resourceprep, nameprep
import string
class InvalidFormat(Exception):
pass
def parse(jidstring):
user = None
server = None
resource = None
# Search for delimiters
user_sep = jidstring.find("@")
res_sep = jidstring.find("/")
if user_sep == -1:
if res_sep == -1:
# host
server = jidstring
else:
# host/resource
server = jidstring[0:res_sep]
resource = jidstring[res_sep + 1:] or None
else:
if res_sep == -1:
# user@host
user = jidstring[0:user_sep] or None
server = jidstring[user_sep + 1:]
else:
if user_sep < res_sep:
# user@host/resource
user = jidstring[0:user_sep] or None
server = jidstring[user_sep + 1:user_sep + (res_sep - user_sep)]
resource = jidstring[res_sep + 1:] or None
else:
# server/resource (with an @ in resource)
server = jidstring[0:res_sep]
resource = jidstring[res_sep + 1:] or None
return prep(user, server, resource)
def prep(user, server, resource):
""" Perform stringprep on all JID fragments """
if user:
try:
user = nodeprep.prepare(unicode(user))
except UnicodeError:
raise InvalidFormat, "Invalid character in username"
else:
user = None
if not server:
raise InvalidFormat, "Server address required."
else:
try:
server = nameprep.prepare(unicode(server))
except UnicodeError:
raise InvalidFormat, "Invalid character in hostname"
if resource:
try:
resource = resourceprep.prepare(unicode(resource))
except UnicodeError:
raise InvalidFormat, "Invalid character in resource"
else:
resource = None
return (user, server, resource)
__internJIDs = {}
def internJID(str):
""" Return interned JID.
Assumes C{str} is stringprep'd.
"""
if str in __internJIDs:
return __internJIDs[str]
else:
j = JID(str)
__internJIDs[str] = j
return j
class JID:
""" Represents a stringprep'd Jabber ID.
Note that it is assumed that the attributes C{host}, C{user} and
C{resource}, when set individually, have been properly stringprep'd.
"""
def __init__(self, str = None, tuple = None):
assert (str or tuple)
if str:
user, host, res = parse(str)
else:
user, host, res = prep(*tuple)
self.host = host
self.user = user
self.resource = res
def userhost(self):
if self.user:
return "%s@%s" % (self.user, self.host)
else:
return self.host
def userhostJID(self):
if self.resource:
if "_uhjid" not in self.__dict__:
self._uhjid = internJID(self.userhost())
return self._uhjid
else:
return self
def full(self):
if self.user:
if self.resource:
return "%s@%s/%s" % (self.user, self.host, self.resource)
else:
return "%s@%s" % (self.user, self.host)
else:
if self.resource:
return "%s/%s" % (self.host, self.resource)
else:
return self.host
def __eq__(self, other):
return (self.user == other.user and
self.host == other.host and
self.resource == other.resource)
def __ne__(self, other):
return not (self.user == other.user and
self.host == other.host and
self.resource == other.resource) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/protocols/jabber/jid.py | jid.py |
from zope.interface import Attribute, Interface
class IInitializer(Interface):
"""
Interface for XML stream initializers.
Initializers perform a step in getting the XML stream ready to be
used for the exchange of XML stanzas.
"""
class IInitiatingInitializer(IInitializer):
"""
Interface for XML stream initializers for the initiating entity.
"""
xmlstream = Attribute("""The associated XML stream""")
def initialize():
"""
Initiate the initialization step.
May return a deferred when the initialization is done asynchronously.
"""
class IIQResponseTracker(Interface):
"""
IQ response tracker interface.
The XMPP stanza C{iq} has a request-response nature that fits
naturally with deferreds. You send out a request and when the response
comes back a deferred is fired.
The L{IQ} class implements a C{send} method that returns a deferred. This
deferred is put in a dictionary that is kept in an L{XmlStream} object,
keyed by the request stanzas C{id} attribute.
An object providing this interface (usually an instance of L{XmlStream}),
keeps the said dictionary and sets observers on the iq stanzas of type
C{result} and C{error} and lets the callback fire the associated deferred.
"""
iqDeferreds = Attribute("Dictionary of deferreds waiting for an iq "
"response")
class IService(Interface):
"""
External server-side component service interface.
Services that provide this interface can be added to L{ServiceManager} to
implement (part of) the functionality of the server-side component.
"""
def componentConnected(xs):
"""
Parent component has established a connection.
At this point, authentication was succesful, and XML stanzas
can be exchanged over the XML stream L{xs}. This method can be used
to setup observers for incoming stanzas.
@param xs: XML Stream that represents the established connection.
@type xs: L{xmlstream.XmlStream}
"""
def componentDisconnected():
"""
Parent component has lost the connection to the Jabber server.
Subsequent use of C{self.parent.send} will result in data being
queued until a new connection has been established.
"""
def transportConnected(xs):
"""
Parent component has established a connection over the underlying
transport.
At this point, no traffic has been exchanged over the XML stream. This
method can be used to change properties of the XML Stream (in L{xs}),
the service manager or it's authenticator prior to stream
initialization (including authentication).
""" | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/protocols/jabber/ijabber.py | ijabber.py |
from twisted.internet import protocol
from twisted.words.xish import domish, utility
STREAM_CONNECTED_EVENT = intern("//event/stream/connected")
STREAM_START_EVENT = intern("//event/stream/start")
STREAM_END_EVENT = intern("//event/stream/end")
STREAM_ERROR_EVENT = intern("//event/stream/error")
class XmlStream(protocol.Protocol, utility.EventDispatcher):
""" Generic Streaming XML protocol handler.
This protocol handler will parse incoming data as XML and dispatch events
accordingly. Incoming stanzas can be handled by registering observers using
XPath-like expressions that are matched against each stanza. See
L{utility.EventDispatcher} for details.
"""
def __init__(self):
utility.EventDispatcher.__init__(self)
self.stream = None
self.rawDataOutFn = None
self.rawDataInFn = None
def _initializeStream(self):
""" Sets up XML Parser. """
self.stream = domish.elementStream()
self.stream.DocumentStartEvent = self.onDocumentStart
self.stream.ElementEvent = self.onElement
self.stream.DocumentEndEvent = self.onDocumentEnd
### --------------------------------------------------------------
###
### Protocol events
###
### --------------------------------------------------------------
def connectionMade(self):
""" Called when a connection is made.
Sets up the XML parser and dispatches the L{STREAM_CONNECTED_EVENT}
event indicating the connection has been established.
"""
self._initializeStream()
self.dispatch(self, STREAM_CONNECTED_EVENT)
def dataReceived(self, data):
""" Called whenever data is received.
Passes the data to the XML parser. This can result in calls to the
DOM handlers. If a parse error occurs, the L{STREAM_ERROR_EVENT} event
is called to allow for cleanup actions, followed by dropping the
connection.
"""
try:
if self.rawDataInFn: self.rawDataInFn(data)
self.stream.parse(data)
except domish.ParserError:
self.dispatch(self, STREAM_ERROR_EVENT)
self.transport.loseConnection()
def connectionLost(self, reason):
""" Called when the connection is shut down.
Dispatches the L{STREAM_END_EVENT}.
"""
self.dispatch(self, STREAM_END_EVENT)
self.stream = None
### --------------------------------------------------------------
###
### DOM events
###
### --------------------------------------------------------------
def onDocumentStart(self, rootelem):
""" Called whenever the start tag of a root element has been received.
Dispatches the L{STREAM_START_EVENT}.
"""
self.dispatch(self, STREAM_START_EVENT)
def onElement(self, element):
""" Called whenever a direct child element of the root element has
been received.
Dispatches the received element.
"""
self.dispatch(element)
def onDocumentEnd(self):
""" Called whenever the end tag of the root element has been received.
Closes the connection. This causes C{connectionLost} being called.
"""
self.transport.loseConnection()
def setDispatchFn(self, fn):
""" Set another function to handle elements. """
self.stream.ElementEvent = fn
def resetDispatchFn(self):
""" Set the default function (C{onElement}) to handle elements. """
self.stream.ElementEvent = self.onElement
def send(self, obj):
""" Send data over the stream.
Sends the given C{obj} over the connection. C{obj} may be instances of
L{domish.Element}, L{unicode} and L{str}. The first two will be
properly serialized and/or encoded. L{str} objects must be in UTF-8
encoding.
Note: because it is easy to make mistakes in maintaining a properly
encoded L{str} object, it is advised to use L{unicode} objects
everywhere when dealing with XML Streams.
@param obj: Object to be sent over the stream.
@type obj: L{domish.Element}, L{domish} or L{str}
"""
if domish.IElement.providedBy(obj):
obj = obj.toXml()
if isinstance(obj, unicode):
obj = obj.encode('utf-8')
if self.rawDataOutFn:
self.rawDataOutFn(obj)
self.transport.write(obj)
class XmlStreamFactory(protocol.ReconnectingClientFactory):
""" Factory for XmlStream protocol objects as a reconnection client.
This factory generates XmlStream objects when a connection has been
established. To make sure certain event observers are set up before
incoming data is processed, you can set up bootstrap event observers using
C{addBootstrap}.
"""
def __init__(self):
self.bootstraps = []
def buildProtocol(self, addr):
""" Create an instance of XmlStream.
The returned instance will have bootstrap event observers registered
and will proceed to handle input on an incoming connection.
"""
self.resetDelay()
xs = XmlStream()
xs.factory = self
for event, fn in self.bootstraps: xs.addObserver(event, fn)
return xs
def addBootstrap(self, event, fn):
""" Add a bootstrap event handler. """
self.bootstraps.append((event, fn))
def removeBootstrap(self, event, fn):
""" Remove a bootstrap event handler. """
self.bootstraps.remove((event, fn)) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/xish/xmlstream.py | xmlstream.py |
try:
import cStringIO as StringIO
except ImportError:
import StringIO
def _isStr(s):
""" Internal method to determine if an object is a string """
return isinstance(s, type('')) or isinstance(s, type(u''))
class LiteralValue(str):
def value(self, elem):
return self
class IndexValue:
def __init__(self, index):
self.index = int(index) - 1
def value(self, elem):
return elem.children[self.index]
class AttribValue:
def __init__(self, attribname):
self.attribname = attribname
if self.attribname == "xmlns":
self.value = self.value_ns
def value_ns(self, elem):
return elem.uri
def value(self, elem):
if self.attribname in elem.attributes:
return elem.attributes[self.attribname]
else:
return None
class CompareValue:
def __init__(self, lhs, op, rhs):
self.lhs = lhs
self.rhs = rhs
if op == "=":
self.value = self._compareEqual
else:
self.value = self._compareNotEqual
def _compareEqual(self, elem):
return self.lhs.value(elem) == self.rhs.value(elem)
def _compareNotEqual(self, elem):
return self.lhs.value(elem) != self.rhs.value(elem)
def Function(fname):
""" Internal method which selects the function object """
klassname = "_%s_Function" % fname
c = globals()[klassname]()
return c
class _not_Function:
def __init__(self):
self.baseValue = None
def setParams(self, baseValue):
self.baseValue = baseValue
def value(self, elem):
return not self.baseValue.value(elem)
class _text_Function:
def setParams(self):
pass
def value(self, elem):
return str(elem)
class _Location:
def __init__(self):
self.predicates = []
self.elementName = None
self.childLocation = None
def matchesPredicates(self, elem):
if self.elementName != None and self.elementName != elem.name:
return 0
for p in self.predicates:
if not p.value(elem):
return 0
return 1
def matches(self, elem):
if not self.matchesPredicates(elem):
return 0
if self.childLocation != None:
for c in elem.elements():
if self.childLocation.matches(c):
return 1
else:
return 1
return 0
def queryForString(self, elem, resultbuf):
if not self.matchesPredicates(elem):
return
if self.childLocation != None:
for c in elem.elements():
self.childLocation.queryForString(c, resultbuf)
else:
resultbuf.write(str(elem))
def queryForNodes(self, elem, resultlist):
if not self.matchesPredicates(elem):
return
if self.childLocation != None:
for c in elem.elements():
self.childLocation.queryForNodes(c, resultlist)
else:
resultlist.append(elem)
def queryForStringList(self, elem, resultlist):
if not self.matchesPredicates(elem):
return
if self.childLocation != None:
for c in elem.elements():
self.childLocation.queryForStringList(c, resultlist)
else:
for c in elem.children:
if _isStr(c): resultlist.append(c)
class _AnyLocation:
def __init__(self):
self.predicates = []
self.elementName = None
self.childLocation = None
def matchesPredicates(self, elem):
for p in self.predicates:
if not p.value(elem):
return 0
return 1
def listParents(self, elem, parentlist):
if elem.parent != None:
self.listParents(elem.parent, parentlist)
parentlist.append(elem.name)
def isRootMatch(self, elem):
if (self.elementName == None or self.elementName == elem.name) and \
self.matchesPredicates(elem):
if self.childLocation != None:
for c in elem.elements():
if self.childLocation.matches(c):
return True
else:
return True
return False
def findFirstRootMatch(self, elem):
if (self.elementName == None or self.elementName == elem.name) and \
self.matchesPredicates(elem):
# Thus far, the name matches and the predicates match,
# now check into the children and find the first one
# that matches the rest of the structure
# the rest of the structure
if self.childLocation != None:
for c in elem.elements():
if self.childLocation.matches(c):
return c
return None
else:
# No children locations; this is a match!
return elem
else:
# Ok, predicates or name didn't match, so we need to start
# down each child and treat it as the root and try
# again
for c in elem.elements():
if self.matches(c):
return c
# No children matched...
return None
def matches(self, elem):
if self.isRootMatch(elem):
return True
else:
# Ok, initial element isn't an exact match, walk
# down each child and treat it as the root and try
# again
for c in elem.elements():
if self.matches(c):
return True
# No children matched...
return False
def queryForString(self, elem, resultbuf):
raise "UnsupportedOperation"
def queryForNodes(self, elem, resultlist):
# First check to see if _this_ element is a root
if self.isRootMatch(elem):
resultlist.append(elem)
# Now check each child
for c in elem.elements():
self.queryForNodes(c, resultlist)
def queryForStringList(self, elem, resultlist):
if self.isRootMatch(elem):
for c in elem.children:
if _isStr(c): resultlist.append(c)
for c in elem.elements():
self.queryForStringList(c, resultlist)
class XPathQuery:
def __init__(self, queryStr):
self.queryStr = queryStr
from twisted.words.xish.xpathparser import parse
self.baseLocation = parse('XPATH', queryStr)
def __hash__(self):
return self.queryStr.__hash__()
def matches(self, elem):
return self.baseLocation.matches(elem)
def queryForString(self, elem):
result = StringIO.StringIO()
self.baseLocation.queryForString(elem, result)
return result.getvalue()
def queryForNodes(self, elem):
result = []
self.baseLocation.queryForNodes(elem, result)
if len(result) == 0:
return None
else:
return result
def queryForStringList(self, elem):
result = []
self.baseLocation.queryForStringList(elem, result)
if len(result) == 0:
return None
else:
return result
__internedQueries = {}
def internQuery(queryString):
if queryString not in __internedQueries:
__internedQueries[queryString] = XPathQuery(queryString)
return __internedQueries[queryString]
def matches(xpathstr, elem):
return internQuery(xpathstr).matches(elem)
def queryForStringList(xpathstr, elem):
return internQuery(xpathstr).queryForStringList(elem)
def queryForString(xpathstr, elem):
return internQuery(xpathstr).queryForString(elem)
def queryForNodes(xpathstr, elem):
return internQuery(xpathstr).queryForNodes(elem)
# Convenience main to generate new xpathparser.py
if __name__ == "__main__":
from twisted.python import yapps2
yapps2.generate('xpathparser.g') | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/xish/xpath.py | xpath.py |
from __future__ import generators
import types
from zope.interface import implements, Interface, Attribute
def _splitPrefix(name):
""" Internal method for splitting a prefixed Element name into its
respective parts """
ntok = name.split(":", 1)
if len(ntok) == 2:
return ntok
else:
return (None, ntok[0])
# Global map of prefixes that always get injected
# into the serializers prefix map (note, that doesn't
# mean they're always _USED_)
G_PREFIXES = { "http://www.w3.org/XML/1998/namespace":"xml" }
class _ListSerializer:
""" Internal class which serializes an Element tree into a buffer """
def __init__(self, prefixes=None, prefixesInScope=None):
self.writelist = []
self.prefixes = prefixes or {}
self.prefixes.update(G_PREFIXES)
self.prefixStack = [G_PREFIXES.values()] + (prefixesInScope or [])
self.prefixCounter = 0
def getValue(self):
return u"".join(self.writelist)
def getPrefix(self, uri):
if not self.prefixes.has_key(uri):
self.prefixes[uri] = "xn%d" % (self.prefixCounter)
self.prefixCounter = self.prefixCounter + 1
return self.prefixes[uri]
def prefixInScope(self, prefix):
stack = self.prefixStack
for i in range(-1, (len(self.prefixStack)+1) * -1, -1):
if prefix in stack[i]:
return True
return False
def serialize(self, elem, closeElement=1, defaultUri=''):
# Optimization shortcuts
write = self.writelist.append
# Shortcut, check to see if elem is actually a chunk o' serialized XML
if isinstance(elem, SerializedXML):
write(elem)
return
# Shortcut, check to see if elem is actually a string (aka Cdata)
if isinstance(elem, types.StringTypes):
write(escapeToXml(elem))
return
# Further optimizations
parent = elem.parent
name = elem.name
uri = elem.uri
defaultUri, currentDefaultUri = elem.defaultUri, defaultUri
for p, u in elem.localPrefixes.iteritems():
self.prefixes[u] = p
self.prefixStack.append(elem.localPrefixes.keys())
# Inherit the default namespace
if defaultUri is None:
defaultUri = currentDefaultUri
if uri is None:
uri = defaultUri
prefix = None
if uri != defaultUri or uri in self.prefixes:
prefix = self.getPrefix(uri)
inScope = self.prefixInScope(prefix)
# Create the starttag
if not prefix:
write("<%s" % (name))
else:
write("<%s:%s" % (prefix, name))
if not inScope:
write(" xmlns:%s='%s'" % (prefix, uri))
self.prefixStack[-1].append(prefix)
inScope = True
if defaultUri != currentDefaultUri and \
(uri != defaultUri or not prefix or not inScope):
write(" xmlns='%s'" % (defaultUri))
for p, u in elem.localPrefixes.iteritems():
write(" xmlns:%s='%s'" % (p, u))
# Serialize attributes
for k,v in elem.attributes.items():
# If the attribute name is a tuple, it's a qualified attribute
if isinstance(k, types.TupleType):
attr_uri, attr_name = k
attr_prefix = self.getPrefix(attr_uri)
if not self.prefixInScope(attr_prefix):
write(" xmlns:%s='%s'" % (attr_prefix, attr_uri))
self.prefixStack[-1].append(attr_prefix)
write(" %s:%s='%s'" % (attr_prefix, attr_name,
escapeToXml(v, 1)))
else:
write((" %s='%s'" % ( k, escapeToXml(v, 1))))
# Shortcut out if this is only going to return
# the element (i.e. no children)
if closeElement == 0:
write(">")
return
# Serialize children
if len(elem.children) > 0:
write(">")
for c in elem.children:
self.serialize(c, defaultUri=defaultUri)
# Add closing tag
if not prefix:
write("</%s>" % (name))
else:
write("</%s:%s>" % (prefix, name))
else:
write("/>")
self.prefixStack.pop()
SerializerClass = _ListSerializer
def escapeToXml(text, isattrib = 0):
""" Escape text to proper XML form, per section 2.3 in the XML specification.
@type text: L{str}
@param text: Text to escape
@type isattrib: L{bool}
@param isattrib: Triggers escaping of characters necessary for use as
attribute values
"""
text = text.replace("&", "&")
text = text.replace("<", "<")
text = text.replace(">", ">")
if isattrib == 1:
text = text.replace("'", "'")
text = text.replace("\"", """)
return text
def unescapeFromXml(text):
text = text.replace("<", "<")
text = text.replace(">", ">")
text = text.replace("'", "'")
text = text.replace(""", "\"")
text = text.replace("&", "&")
return text
def generateOnlyInterface(list, int):
""" Filters items in a list by class
"""
for n in list:
if int.providedBy(n):
yield n
def generateElementsQNamed(list, name, uri):
""" Filters Element items in a list with matching name and URI. """
for n in list:
if IElement.providedBy(n) and n.name == name and n.uri == uri:
yield n
def generateElementsNamed(list, name):
""" Filters Element items in a list with matching name, regardless of URI.
"""
for n in list:
if IElement.providedBy(n) and n.name == name:
yield n
class SerializedXML(unicode):
""" Marker class for pre-serialized XML in the DOM. """
pass
class Namespace:
""" Convenience object for tracking namespace declarations. """
def __init__(self, uri):
self._uri = uri
def __getattr__(self, n):
return (self._uri, n)
def __getitem__(self, n):
return (self._uri, n)
class IElement(Interface):
""" Interface to XML element nodes.
See L{Element} for a detailed example of its general use.
@warning: this Interface is not yet complete!
"""
uri = Attribute(""" Element's namespace URI """)
name = Attribute(""" Element's local name """)
defaultUri = Attribute(""" Default namespace URI of child elements """)
attributes = Attribute(""" Dictionary of element attributes """)
children = Attribute(""" List of child nodes """)
parent = Attribute(""" Reference to element's parent element """)
localPrefixes = Attribute(""" Dictionary of local prefixes """)
def toXml(prefixes=None, closeElement=1, defaultUri='',
prefixesInScope=None):
""" Serializes object to a (partial) XML document
@param prefixes: dictionary that maps namespace URIs to suggested
prefix names.
@type prefixes: L{dict}
@param closeElement: flag that determines whether to include the
closing tag of the element in the serialized
string. A value of C{0} only generates the
element's start tag. A value of C{1} yields a
complete serialization.
@type closeElement: L{int}
@param defaultUri: Initial default namespace URI. This is most useful
for partial rendering, where the logical parent
element (of which the starttag was already
serialized) declares a default namespace that should
be inherited.
@type defaultUri: L{str}
@param prefixesInScope: list of prefixes that are assumed to be
declared by ancestors.
@type prefixesInScope: L{list}
@return: (partial) serialized XML
@rtype: L{unicode}
"""
def addElement(name, defaultUri = None, content = None):
""" Create an element and add as child.
The new element is added to this element as a child, and will have
this element as its parent.
@param name: element name. This can be either a L{unicode} object that
contains the local name, or a tuple of (uri, local_name)
for a fully qualified name. In the former case,
the namespace URI is inherited from this element.
@type name: L{unicode} or L{tuple} of (L{unicode}, L{unicode})
@param defaultUri: default namespace URI for child elements. If
C{None}, this is inherited from this element.
@type defaultUri: L{unicode}
@param content: text contained by the new element.
@type content: L{unicode}
@return: the created element
@rtype: object providing L{IElement}
"""
def addChild(node):
""" Adds a node as child of this element.
The C{node} will be added to the list of childs of this element, and
will have this element set as its parent when C{node} provides
L{IElement}.
@param node: the child node.
@type node: L{unicode} or object implementing L{IElement}
"""
class Element(object):
""" Represents an XML element node.
An Element contains a series of attributes (name/value pairs), content
(character data), and other child Element objects. When building a document
with markup (such as HTML or XML), use this object as the starting point.
Element objects fully support XML Namespaces. The fully qualified name of
the XML Element it represents is stored in the C{uri} and C{name}
attributes, where C{uri} holds the namespace URI. There is also a default
namespace, for child elements. This is stored in the C{defaultUri}
attribute. Note that C{''} means the empty namespace.
Serialization of Elements through C{toXml()} will use these attributes
for generating proper serialized XML. When both C{uri} and C{defaultUri}
are not None in the Element and all of its descendents, serialization
proceeds as expected:
>>> from twisted.words.xish import domish
>>> root = domish.Element(('myns', 'root'))
>>> root.addElement('child', content='test')
<twisted.words.xish.domish.Element object at 0x83002ac>
>>> root.toXml()
u"<root xmlns='myns'><child>test</child></root>"
For partial serialization, needed for streaming XML, a special value for
namespace URIs can be used: C{None}.
Using C{None} as the value for C{uri} means: this element is in whatever
namespace inherited by the closest logical ancestor when the complete XML
document has been serialized. The serialized start tag will have a
non-prefixed name, and no xmlns declaration will be generated.
Similarly, C{None} for C{defaultUri} means: the default namespace for my
child elements is inherited from the logical ancestors of this element,
when the complete XML document has been serialized.
To illustrate, an example from a Jabber stream. Assume the start tag of the
root element of the stream has already been serialized, along with several
complete child elements, and sent off, looking like this:
<stream:stream xmlns:stream='http://etherx.jabber.org/streams'
xmlns='jabber:client' to='example.com'>
...
Now suppose we want to send a complete element represented by an
object C{message} created like:
>>> message = domish.Element((None, 'message'))
>>> message['to'] = '[email protected]'
>>> message.addElement('body', content='Hi!')
<twisted.words.xish.domish.Element object at 0x8276e8c>
>>> message.toXml()
u"<message to='[email protected]'><body>Hi!</body></message>"
As, you can see, this XML snippet has no xmlns declaration. When sent
off, it inherits the C{jabber:client} namespace from the root element.
Note that this renders the same as using C{''} instead of C{None}:
>>> presence = domish.Element(('', 'presence'))
>>> presence.toXml()
u"<presence/>"
However, if this object has a parent defined, the difference becomes
clear:
>>> child = message.addElement(('http://example.com/', 'envelope'))
>>> child.addChild(presence)
<twisted.words.xish.domish.Element object at 0x8276fac>
>>> message.toXml()
u"<message to='[email protected]'><body>Hi!</body><envelope xmlns='http://example.com/'><presence xmlns=''/></envelope></message>"
As, you can see, the <presence/> element is now in the empty namespace, not
in the default namespace of the parent or the streams'.
@type uri: L{unicode} or None
@ivar uri: URI of this Element's name
@type name: L{unicode}
@ivar name: Name of this Element
@type defaultUri: L{unicode} or None
@ivar defaultUri: URI this Element exists within
@type children: L{list}
@ivar children: List of child Elements and content
@type parent: L{Element}
@ivar parent: Reference to the parent Element, if any.
@type attributes: L{dict}
@ivar attributes: Dictionary of attributes associated with this Element.
@type localPrefixes: L{dict}
@ivar localPrefixes: Dictionary of namespace declarations on this
element. The key is the prefix to bind the
namespace uri to.
"""
implements(IElement)
_idCounter = 0
def __init__(self, qname, defaultUri=None, attribs=None,
localPrefixes=None):
"""
@param qname: Tuple of (uri, name)
@param defaultUri: The default URI of the element; defaults to the URI
specified in L{qname}
@param attribs: Dictionary of attributes
@param localPrefixes: Dictionary of namespace declarations on this
element. The key is the prefix to bind the
namespace uri to.
"""
self.localPrefixes = localPrefixes or {}
self.uri, self.name = qname
if defaultUri is None and \
self.uri not in self.localPrefixes.itervalues():
self.defaultUri = self.uri
else:
self.defaultUri = defaultUri
self.attributes = attribs or {}
self.children = []
self.parent = None
def __getattr__(self, key):
# Check child list for first Element with a name matching the key
for n in self.children:
if IElement.providedBy(n) and n.name == key:
return n
# Tweak the behaviour so that it's more friendly about not
# finding elements -- we need to document this somewhere :)
if key.startswith('_'):
raise AttributeError(key)
else:
return None
def __getitem__(self, key):
return self.attributes[self._dqa(key)]
def __delitem__(self, key):
del self.attributes[self._dqa(key)];
def __setitem__(self, key, value):
self.attributes[self._dqa(key)] = value
def __str__(self):
""" Retrieve the first CData (content) node
"""
for n in self.children:
if isinstance(n, types.StringTypes): return n
return ""
def _dqa(self, attr):
""" Dequalify an attribute key as needed """
if isinstance(attr, types.TupleType) and not attr[0]:
return attr[1]
else:
return attr
def getAttribute(self, attribname, default = None):
""" Retrieve the value of attribname, if it exists """
return self.attributes.get(attribname, default)
def hasAttribute(self, attrib):
""" Determine if the specified attribute exists """
return self.attributes.has_key(self._dqa(attrib))
def compareAttribute(self, attrib, value):
""" Safely compare the value of an attribute against a provided value.
C{None}-safe.
"""
return self.attributes.get(self._dqa(attrib), None) == value
def swapAttributeValues(self, left, right):
""" Swap the values of two attribute. """
d = self.attributes
l = d[left]
d[left] = d[right]
d[right] = l
def addChild(self, node):
""" Add a child to this Element. """
if IElement.providedBy(node):
node.parent = self
self.children.append(node)
return self.children[-1]
def addContent(self, text):
""" Add some text data to this Element. """
c = self.children
if len(c) > 0 and isinstance(c[-1], types.StringTypes):
c[-1] = c[-1] + text
else:
c.append(text)
return c[-1]
def addElement(self, name, defaultUri = None, content = None):
result = None
if isinstance(name, type(())):
if defaultUri is None:
defaultUri = name[0]
self.children.append(Element(name, defaultUri))
else:
if defaultUri is None:
defaultUri = self.defaultUri
self.children.append(Element((defaultUri, name), defaultUri))
result = self.children[-1]
result.parent = self
if content:
result.children.append(content)
return result
def addRawXml(self, rawxmlstring):
""" Add a pre-serialized chunk o' XML as a child of this Element. """
self.children.append(SerializedXML(rawxmlstring))
def addUniqueId(self):
""" Add a unique (across a given Python session) id attribute to this
Element.
"""
self.attributes["id"] = "H_%d" % Element._idCounter
Element._idCounter = Element._idCounter + 1
def elements(self):
""" Iterate across all children of this Element that are Elements. """
return generateOnlyInterface(self.children, IElement)
def toXml(self, prefixes=None, closeElement=1, defaultUri='',
prefixesInScope=None):
""" Serialize this Element and all children to a string. """
s = SerializerClass(prefixes=prefixes, prefixesInScope=prefixesInScope)
s.serialize(self, closeElement=closeElement, defaultUri=defaultUri)
return s.getValue()
def firstChildElement(self):
for c in self.children:
if IElement.providedBy(c):
return c
return None
class ParserError(Exception):
""" Exception thrown when a parsing error occurs """
pass
def elementStream():
""" Preferred method to construct an ElementStream
Uses Expat-based stream if available, and falls back to Sux if necessary.
"""
try:
es = ExpatElementStream()
return es
except ImportError:
if SuxElementStream is None:
raise Exception("No parsers available :(")
es = SuxElementStream()
return es
try:
from twisted.web import sux
except:
SuxElementStream = None
else:
class SuxElementStream(sux.XMLParser):
def __init__(self):
self.connectionMade()
self.DocumentStartEvent = None
self.ElementEvent = None
self.DocumentEndEvent = None
self.currElem = None
self.rootElem = None
self.documentStarted = False
self.defaultNsStack = []
self.prefixStack = []
def parse(self, buffer):
try:
self.dataReceived(buffer)
except sux.ParseError, e:
raise ParserError, str(e)
def findUri(self, prefix):
# Walk prefix stack backwards, looking for the uri
# matching the specified prefix
stack = self.prefixStack
for i in range(-1, (len(self.prefixStack)+1) * -1, -1):
if prefix in stack[i]:
return stack[i][prefix]
return None
def gotTagStart(self, name, attributes):
defaultUri = None
localPrefixes = {}
attribs = {}
uri = None
# Pass 1 - Identify namespace decls
for k, v in attributes.items():
if k.startswith("xmlns"):
x, p = _splitPrefix(k)
if (x is None): # I.e. default declaration
defaultUri = v
else:
localPrefixes[p] = v
del attributes[k]
# Push namespace decls onto prefix stack
self.prefixStack.append(localPrefixes)
# Determine default namespace for this element; if there
# is one
if defaultUri is None:
if len(self.defaultNsStack) > 0:
defaultUri = self.defaultNsStack[-1]
else:
defaultUri = ''
# Fix up name
prefix, name = _splitPrefix(name)
if prefix is None: # This element is in the default namespace
uri = defaultUri
else:
# Find the URI for the prefix
uri = self.findUri(prefix)
# Pass 2 - Fix up and escape attributes
for k, v in attributes.items():
p, n = _splitPrefix(k)
if p is None:
attribs[n] = v
else:
attribs[(self.findUri(p)), n] = unescapeFromXml(v)
# Construct the actual Element object
e = Element((uri, name), defaultUri, attribs, localPrefixes)
# Save current default namespace
self.defaultNsStack.append(defaultUri)
# Document already started
if self.documentStarted:
# Starting a new packet
if self.currElem is None:
self.currElem = e
# Adding to existing element
else:
self.currElem = self.currElem.addChild(e)
# New document
else:
self.rootElem = e
self.documentStarted = True
self.DocumentStartEvent(e)
def gotText(self, data):
if self.currElem != None:
self.currElem.addContent(data)
def gotCData(self, data):
if self.currElem != None:
self.currElem.addContent(data)
def gotComment(self, data):
# Ignore comments for the moment
pass
entities = { "amp" : "&",
"lt" : "<",
"gt" : ">",
"apos": "'",
"quot": "\"" }
def gotEntityReference(self, entityRef):
# If this is an entity we know about, add it as content
# to the current element
if entityRef in SuxElementStream.entities:
self.currElem.addContent(SuxElementStream.entities[entityRef])
def gotTagEnd(self, name):
# Ensure the document hasn't already ended
if self.rootElem is None:
# XXX: Write more legible explanation
raise ParserError, "Element closed after end of document."
# Fix up name
prefix, name = _splitPrefix(name)
if prefix is None:
uri = self.defaultNsStack[-1]
else:
uri = self.findUri(prefix)
# End of document
if self.currElem is None:
# Ensure element name and uri matches
if self.rootElem.name != name or self.rootElem.uri != uri:
raise ParserError, "Mismatched root elements"
self.DocumentEndEvent()
self.rootElem = None
# Other elements
else:
# Ensure the tag being closed matches the name of the current
# element
if self.currElem.name != name or self.currElem.uri != uri:
# XXX: Write more legible explanation
raise ParserError, "Malformed element close"
# Pop prefix and default NS stack
self.prefixStack.pop()
self.defaultNsStack.pop()
# Check for parent null parent of current elem;
# that's the top of the stack
if self.currElem.parent is None:
self.currElem.parent = self.rootElem
self.ElementEvent(self.currElem)
self.currElem = None
# Anything else is just some element wrapping up
else:
self.currElem = self.currElem.parent
class ExpatElementStream:
def __init__(self):
import pyexpat
self.DocumentStartEvent = None
self.ElementEvent = None
self.DocumentEndEvent = None
self.error = pyexpat.error
self.parser = pyexpat.ParserCreate("UTF-8", " ")
self.parser.StartElementHandler = self._onStartElement
self.parser.EndElementHandler = self._onEndElement
self.parser.CharacterDataHandler = self._onCdata
self.parser.StartNamespaceDeclHandler = self._onStartNamespace
self.parser.EndNamespaceDeclHandler = self._onEndNamespace
self.currElem = None
self.defaultNsStack = ['']
self.documentStarted = 0
self.localPrefixes = {}
def parse(self, buffer):
try:
self.parser.Parse(buffer)
except self.error, e:
raise ParserError, str(e)
def _onStartElement(self, name, attrs):
# Generate a qname tuple from the provided name
qname = name.split(" ")
if len(qname) == 1:
qname = ('', name)
# Process attributes
for k, v in attrs.items():
if k.find(" ") != -1:
aqname = k.split(" ")
attrs[(aqname[0], aqname[1])] = v
del attrs[k]
# Construct the new element
e = Element(qname, self.defaultNsStack[-1], attrs, self.localPrefixes)
self.localPrefixes = {}
# Document already started
if self.documentStarted == 1:
if self.currElem != None:
self.currElem.children.append(e)
e.parent = self.currElem
self.currElem = e
# New document
else:
self.documentStarted = 1
self.DocumentStartEvent(e)
def _onEndElement(self, _):
# Check for null current elem; end of doc
if self.currElem is None:
self.DocumentEndEvent()
# Check for parent that is None; that's
# the top of the stack
elif self.currElem.parent is None:
self.ElementEvent(self.currElem)
self.currElem = None
# Anything else is just some element in the current
# packet wrapping up
else:
self.currElem = self.currElem.parent
def _onCdata(self, data):
if self.currElem != None:
self.currElem.addContent(data)
def _onStartNamespace(self, prefix, uri):
# If this is the default namespace, put
# it on the stack
if prefix is None:
self.defaultNsStack.append(uri)
else:
self.localPrefixes[prefix] = uri
def _onEndNamespace(self, prefix):
# Remove last element on the stack
if prefix is None:
self.defaultNsStack.pop()
## class FileParser(ElementStream):
## def __init__(self):
## ElementStream.__init__(self)
## self.DocumentStartEvent = self.docStart
## self.ElementEvent = self.elem
## self.DocumentEndEvent = self.docEnd
## self.done = 0
## def docStart(self, elem):
## self.document = elem
## def elem(self, elem):
## self.document.addChild(elem)
## def docEnd(self):
## self.done = 1
## def parse(self, filename):
## for l in open(filename).readlines():
## self.parser.Parse(l)
## assert self.done == 1
## return self.document
## def parseFile(filename):
## return FileParser().parse(filename) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/xish/domish.py | domish.py |
def _isStr(s):
""" Internal method to determine if an object is a string """
return isinstance(s, type('')) or isinstance(s, type(u''))
class _MethodWrapper(object):
""" Internal class for tracking method calls """
def __init__(self, method, *args, **kwargs):
self.method = method
self.args = args
self.kwargs = kwargs
def __call__(self, *args, **kwargs):
nargs = self.args + args
nkwargs = self.kwargs.copy()
nkwargs.update(kwargs)
self.method(*nargs, **nkwargs)
class CallbackList:
def __init__(self):
self.callbacks = {}
def addCallback(self, onetime, method, *args, **kwargs):
if not method in self.callbacks:
self.callbacks[method] = (_MethodWrapper(method, *args, **kwargs), onetime)
def removeCallback(self, method):
if method in self.callbacks:
del self.callbacks[method]
def callback(self, *args, **kwargs):
for key, (methodwrapper, onetime) in self.callbacks.items():
methodwrapper(*args, **kwargs)
if onetime:
del self.callbacks[key]
from twisted.words.xish import xpath, domish
class EventDispatcher:
""" Event dispatching service.
The C{EventDispatcher} allows observers to be registered for certain events
that are dispatched. There are two types of events: XPath events and Named
events.
Every dispatch is triggered by calling L{dispatch} with a data object and,
for named events, the name of the event.
When an XPath type event is dispatched, the associated object is assumed
to be a L{domish.Element} object, which is matched against all registered
XPath queries. For every match, the respective observer will be called with
the data object.
A named event will simply call each registered observer for that particular
event name, with the data object. Unlike XPath type events, the data object
is not restricted to L{domish.Element}, but can be anything.
When registering observers, the event that is to be observed is specified
using an L{xpath.XPathQuery} object or a string. In the latter case, the
string can also contain the string representation of an XPath expression.
To distinguish these from named events, each named event should start with
a special prefix that is stored in C{self.prefix}. It defaults to
C{//event/}.
Observers registered using L{addObserver} are persistent: after the
observer has been triggered by a dispatch, it remains registered for a
possible next dispatch. If instead L{addOnetimeObserver} was used to
observe an event, the observer is removed from the list of observers after
the first observed event.
Obsevers can also prioritized, by providing an optional C{priority}
parameter to the L{addObserver} and L{addOnetimeObserver} methods. Higher
priority observers are then called before lower priority observers.
Finally, observers can be unregistered by using L{removeObserver}.
"""
def __init__(self, eventprefix = "//event/"):
self.prefix = eventprefix
self._eventObservers = {}
self._xpathObservers = {}
self._orderedEventObserverKeys = []
self._orderedXpathObserverKeys = []
self._dispatchDepth = 0 # Flag indicating levels of dispatching in progress
self._updateQueue = [] # Queued updates for observer ops
def _isEvent(self, event):
return _isStr(event) and self.prefix == event[0:len(self.prefix)]
def addOnetimeObserver(self, event, observerfn, priority=0, *args, **kwargs):
""" Register a one-time observer for an event.
Like L{addObserver}, but is only triggered at most once. See there
for a description of the parameters.
"""
self._addObserver(True, event, observerfn, priority, *args, **kwargs)
def addObserver(self, event, observerfn, priority=0, *args, **kwargs):
""" Register an observer for an event.
Each observer will be registered with a certain priority. Higher
priority observers get called before lower priority observers.
@param event: Name or XPath query for the event to be monitored.
@type event: L{str} or L{xpath.XPathQuery}.
@param observerfn: Function to be called when the specified event
has been triggered. This function takes
one parameter: the data object that triggered
the event. When specified, the C{*args} and
C{**kwargs} parameters to addObserver are being used
as additional parameters to the registered observer
function.
@param priority: (Optional) priority of this observer in relation to
other observer that match the same event. Defaults to
C{0}.
@type priority: L{int}
"""
self._addObserver(False, event, observerfn, priority, *args, **kwargs)
def _addObserver(self, onetime, event, observerfn, priority, *args, **kwargs):
# If this is happening in the middle of the dispatch, queue
# it up for processing after the dispatch completes
if self._dispatchDepth > 0:
self._updateQueue.append(lambda:self.addObserver(event, observerfn, priority, *args, **kwargs))
return
observers = None
if _isStr(event):
if self.prefix == event[0:len(self.prefix)]:
# Treat as event
observers = self._eventObservers
else:
# Treat as xpath
event = xpath.internQuery(event)
observers = self._xpathObservers
else:
# Treat as xpath
observers = self._xpathObservers
key = (priority, event)
if not key in observers:
cbl = CallbackList()
cbl.addCallback(onetime, observerfn, *args, **kwargs)
observers[key] = cbl
else:
observers[key].addCallback(onetime, observerfn, *args, **kwargs)
# Update the priority ordered list of xpath keys --
# This really oughta be rethought for efficiency
self._orderedEventObserverKeys = self._eventObservers.keys()
self._orderedEventObserverKeys.sort()
self._orderedEventObserverKeys.reverse()
self._orderedXpathObserverKeys = self._xpathObservers.keys()
self._orderedXpathObserverKeys.sort()
self._orderedXpathObserverKeys.reverse()
def removeObserver(self, event, observerfn):
""" Remove function as observer for an event.
The observer function is removed for all priority levels for the
specified event.
@param event: Event for which the observer function was registered.
@type event: L{str} or L{xpath.XPathQuery}
@param observerfn: Observer function to be unregistered.
"""
# If this is happening in the middle of the dispatch, queue
# it up for processing after the dispatch completes
if self._dispatchDepth > 0:
self._updateQueue.append(lambda:self.removeObserver(event, observerfn))
return
observers = None
if _isStr(event):
if self.prefix == event[0:len(self.prefix)]:
observers = self._eventObservers
else:
event = xpath.internQuery(event)
observers = self._xpathObservers
else:
observers = self._xpathObservers
for priority, query in observers:
if event == query:
observers[(priority, query)].removeCallback(observerfn)
# Update the priority ordered list of xpath keys --
# This really oughta be rethought for efficiency
self._orderedEventObserverKeys = self._eventObservers.keys()
self._orderedEventObserverKeys.sort()
self._orderedEventObserverKeys.reverse()
self._orderedXpathObserverKeys = self._xpathObservers.keys()
self._orderedXpathObserverKeys.sort()
self._orderedXpathObserverKeys.reverse()
def dispatch(self, object, event = None):
""" Dispatch an event.
When C{event} is C{None}, an XPath type event is triggered, and
C{object} is assumed to be an instance of {domish.Element}. Otherwise,
C{event} holds the name of the named event being triggered. In the
latter case, C{object} can be anything.
@param object: The object to be dispatched.
@param event: Optional event name.
@type event: L{str}
"""
foundTarget = False
# Aiyiyi! If this dispatch occurs within a dispatch
# we need to preserve the original dispatching flag
# and not mess up the updateQueue
self._dispatchDepth = self._dispatchDepth + 1
if event != None:
for priority, query in self._orderedEventObserverKeys:
if event == query:
self._eventObservers[(priority, event)].callback(object)
foundTarget = True
else:
for priority, query in self._orderedXpathObserverKeys:
callbacklist = self._xpathObservers[(priority, query)]
if query.matches(object):
callbacklist.callback(object)
foundTarget = True
self._dispatchDepth = self._dispatchDepth -1
# If this is a dispatch within a dispatch, don't
# do anything with the updateQueue -- it needs to
# wait until we've back all the way out of the stack
if self._dispatchDepth == 0:
# Deal with pending update operations
for f in self._updateQueue:
f()
self._updateQueue = []
return foundTarget | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/words/xish/utility.py | utility.py |
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
"""Utility classes for spread."""
from twisted.internet import defer
from twisted.python.failure import Failure
from zope.interface import implements
class LocalMethod:
def __init__(self, local, name):
self.local = local
self.name = name
def __call__(self, *args, **kw):
return self.local.callRemote(self.name, *args, **kw)
class LocalAsRemote:
"""
A class useful for emulating the effects of remote behavior locally.
"""
reportAllTracebacks = 1
def callRemote(self, name, *args, **kw):
"""Call a specially-designated local method.
self.callRemote('x') will first try to invoke a method named
sync_x and return its result (which should probably be a
Deferred). Second, it will look for a method called async_x,
which will be called and then have its result (or Failure)
automatically wrapped in a Deferred.
"""
if hasattr(self, 'sync_'+name):
return getattr(self, 'sync_'+name)(*args, **kw)
try:
method = getattr(self, "async_" + name)
return defer.succeed(method(*args, **kw))
except:
f = Failure()
if self.reportAllTracebacks:
f.printTraceback()
return defer.fail(f)
def remoteMethod(self, name):
return LocalMethod(self, name)
class LocalAsyncForwarder:
"""A class useful for forwarding a locally-defined interface.
"""
def __init__(self, forwarded, interfaceClass, failWhenNotImplemented=0):
assert interfaceClass.providedBy(forwarded)
self.forwarded = forwarded
self.interfaceClass = interfaceClass
self.failWhenNotImplemented = failWhenNotImplemented
def _callMethod(self, method, *args, **kw):
return getattr(self.forwarded, method)(*args, **kw)
def callRemote(self, method, *args, **kw):
if self.interfaceClass.queryDescriptionFor(method):
result = defer.maybeDeferred(self._callMethod, method, *args, **kw)
return result
elif self.failWhenNotImplemented:
return defer.fail(
Failure(NotImplementedError,
"No Such Method in Interface: %s" % method))
else:
return defer.succeed(None)
class Pager:
"""I am an object which pages out information.
"""
def __init__(self, collector, callback=None, *args, **kw):
"""
Create a pager with a Reference to a remote collector and
an optional callable to invoke upon completion.
"""
if callable(callback):
self.callback = callback
self.callbackArgs = args
self.callbackKeyword = kw
else:
self.callback = None
self._stillPaging = 1
self.collector = collector
collector.broker.registerPageProducer(self)
def stillPaging(self):
"""(internal) Method called by Broker.
"""
if not self._stillPaging:
self.collector.callRemote("endedPaging")
if self.callback is not None:
self.callback(*self.callbackArgs, **self.callbackKeyword)
return self._stillPaging
def sendNextPage(self):
"""(internal) Method called by Broker.
"""
self.collector.callRemote("gotPage", self.nextPage())
def nextPage(self):
"""Override this to return an object to be sent to my collector.
"""
raise NotImplementedError()
def stopPaging(self):
"""Call this when you're done paging.
"""
self._stillPaging = 0
class StringPager(Pager):
"""A simple pager that splits a string into chunks.
"""
def __init__(self, collector, st, chunkSize=8192, callback=None, *args, **kw):
self.string = st
self.pointer = 0
self.chunkSize = chunkSize
Pager.__init__(self, collector, callback, *args, **kw)
def nextPage(self):
val = self.string[self.pointer:self.pointer+self.chunkSize]
self.pointer += self.chunkSize
if self.pointer >= len(self.string):
self.stopPaging()
return val
from twisted.protocols import basic
from twisted.internet import interfaces
class FilePager(Pager):
"""Reads a file in chunks and sends the chunks as they come.
"""
implements(interfaces.IConsumer)
def __init__(self, collector, fd, callback=None, *args, **kw):
self.chunks = []
self.pointer = 0
self.startProducing(fd)
Pager.__init__(self, collector, callback, *args, **kw)
def startProducing(self, fd):
self.deferred = basic.FileSender().beginFileTransfer(fd, self)
self.deferred.addBoth(lambda x : self.stopPaging())
def registerProducer(self, producer, streaming):
self.producer = producer
if not streaming:
self.producer.resumeProducing()
def unregisterProducer(self):
self.producer = None
def write(self, chunk):
self.chunks.append(chunk)
def sendNextPage(self):
if self.pointer >= len(self.chunks):
return
val = self.chunks[self.pointer]
self.pointer += 1
self.producer.resumeProducing()
self.collector.callRemote("gotPage", val)
### Utility paging stuff.
from twisted.spread import pb
class CallbackPageCollector(pb.Referenceable):
"""I receive pages from the peer. You may instantiate a Pager with a
remote reference to me. I will call the callback with a list of pages
once they are all received."""
def __init__(self, callback):
self.pages = []
self.callback = callback
def remote_gotPage(self, page):
self.pages.append(page)
def remote_endedPaging(self):
self.callback(self.pages)
def getAllPages(referenceable, methodName, *args, **kw):
"""A utility method that will call a remote method which expects a
PageCollector as the first argument."""
d = defer.Deferred()
referenceable.callRemote(methodName, CallbackPageCollector(d.callback), *args, **kw)
return d | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/spread/util.py | util.py |
__version__ = "$Revision: 1.37 $"[11:-2]
from twisted.internet import protocol
from twisted.persisted import styles
from twisted.python import log
import copy, cStringIO, struct
class BananaError(Exception):
pass
def int2b128(integer, stream):
if integer == 0:
stream(chr(0))
return
assert integer > 0, "can only encode positive integers"
while integer:
stream(chr(integer & 0x7f))
integer = integer >> 7
def b1282int(st):
oneHundredAndTwentyEight = 128l
i = 0
place = 0
for char in st:
num = ord(char)
i = i + (num * (oneHundredAndTwentyEight ** place))
place = place + 1
if i <= 2147483647:
return int(i)
else:
return i
# delimiter characters.
LIST = chr(0x80)
INT = chr(0x81)
STRING = chr(0x82)
NEG = chr(0x83)
FLOAT = chr(0x84)
# "optional" -- these might be refused by a low-level implementation.
LONGINT = chr(0x85)
LONGNEG = chr(0x86)
# really optional; this is is part of the 'pb' vocabulary
VOCAB = chr(0x87)
HIGH_BIT_SET = chr(0x80)
def setPrefixLimit(limit):
"""
Set the limit on the prefix length for all Banana connections
established after this call.
The prefix length limit determines how many bytes of prefix a banana
decoder will allow before rejecting a potential object as too large.
@type limit: C{int}
@param limit: The number of bytes of prefix for banana to allow when
decoding.
"""
global _PREFIX_LIMIT
_PREFIX_LIMIT = limit
setPrefixLimit(64)
SIZE_LIMIT = 640 * 1024 # 640k is all you'll ever need :-)
class Banana(protocol.Protocol, styles.Ephemeral):
knownDialects = ["pb", "none"]
prefixLimit = None
sizeLimit = SIZE_LIMIT
def setPrefixLimit(self, limit):
"""
Set the prefix limit for decoding done by this protocol instance.
@see L{setPrefixLimit}
"""
self.prefixLimit = limit
self._smallestLongInt = -2 ** (limit * 7) + 1
self._smallestInt = -2 ** 31
self._largestInt = 2 ** 31 - 1
self._largestLongInt = 2 ** (limit * 7) - 1
def connectionReady(self):
"""Surrogate for connectionMade
Called after protocol negotiation.
"""
def _selectDialect(self, dialect):
self.currentDialect = dialect
self.connectionReady()
def callExpressionReceived(self, obj):
if self.currentDialect:
self.expressionReceived(obj)
else:
# this is the first message we've received
if self.isClient:
# if I'm a client I have to respond
for serverVer in obj:
if serverVer in self.knownDialects:
self.sendEncoded(serverVer)
self._selectDialect(serverVer)
break
else:
# I can't speak any of those dialects.
log.msg('error losing')
self.transport.loseConnection()
else:
if obj in self.knownDialects:
self._selectDialect(obj)
else:
# the client just selected a protocol that I did not suggest.
log.msg('freaky losing')
self.transport.loseConnection()
def connectionMade(self):
self.setPrefixLimit(_PREFIX_LIMIT)
self.currentDialect = None
if not self.isClient:
self.sendEncoded(self.knownDialects)
def gotItem(self, item):
l = self.listStack
if l:
l[-1][1].append(item)
else:
self.callExpressionReceived(item)
buffer = ''
def dataReceived(self, chunk):
buffer = self.buffer + chunk
listStack = self.listStack
gotItem = self.gotItem
while buffer:
assert self.buffer != buffer, "This ain't right: %s %s" % (repr(self.buffer), repr(buffer))
self.buffer = buffer
pos = 0
for ch in buffer:
if ch >= HIGH_BIT_SET:
break
pos = pos + 1
else:
if pos > self.prefixLimit:
raise BananaError("Security precaution: more than %d bytes of prefix" % (self.prefixLimit,))
return
num = buffer[:pos]
typebyte = buffer[pos]
rest = buffer[pos+1:]
if len(num) > self.prefixLimit:
raise BananaError("Security precaution: longer than %d bytes worth of prefix" % (self.prefixLimit,))
if typebyte == LIST:
num = b1282int(num)
if num > SIZE_LIMIT:
raise BananaError("Security precaution: List too long.")
listStack.append((num, []))
buffer = rest
elif typebyte == STRING:
num = b1282int(num)
if num > SIZE_LIMIT:
raise BananaError("Security precaution: String too long.")
if len(rest) >= num:
buffer = rest[num:]
gotItem(rest[:num])
else:
return
elif typebyte == INT:
buffer = rest
num = b1282int(num)
gotItem(int(num))
elif typebyte == LONGINT:
buffer = rest
num = b1282int(num)
gotItem(long(num))
elif typebyte == LONGNEG:
buffer = rest
num = b1282int(num)
gotItem(-long(num))
elif typebyte == NEG:
buffer = rest
num = -b1282int(num)
gotItem(num)
elif typebyte == VOCAB:
buffer = rest
num = b1282int(num)
gotItem(self.incomingVocabulary[num])
elif typebyte == FLOAT:
if len(rest) >= 8:
buffer = rest[8:]
gotItem(struct.unpack("!d", rest[:8])[0])
else:
return
else:
raise NotImplementedError(("Invalid Type Byte %r" % (typebyte,)))
while listStack and (len(listStack[-1][1]) == listStack[-1][0]):
item = listStack.pop()[1]
gotItem(item)
self.buffer = ''
def expressionReceived(self, lst):
"""Called when an expression (list, string, or int) is received.
"""
raise NotImplementedError()
outgoingVocabulary = {
# Jelly Data Types
'None' : 1,
'class' : 2,
'dereference' : 3,
'reference' : 4,
'dictionary' : 5,
'function' : 6,
'instance' : 7,
'list' : 8,
'module' : 9,
'persistent' : 10,
'tuple' : 11,
'unpersistable' : 12,
# PB Data Types
'copy' : 13,
'cache' : 14,
'cached' : 15,
'remote' : 16,
'local' : 17,
'lcache' : 18,
# PB Protocol Messages
'version' : 19,
'login' : 20,
'password' : 21,
'challenge' : 22,
'logged_in' : 23,
'not_logged_in' : 24,
'cachemessage' : 25,
'message' : 26,
'answer' : 27,
'error' : 28,
'decref' : 29,
'decache' : 30,
'uncache' : 31,
}
incomingVocabulary = {}
for k, v in outgoingVocabulary.items():
incomingVocabulary[v] = k
def __init__(self, isClient=1):
self.listStack = []
self.outgoingSymbols = copy.copy(self.outgoingVocabulary)
self.outgoingSymbolCount = 0
self.isClient = isClient
def sendEncoded(self, obj):
io = cStringIO.StringIO()
self._encode(obj, io.write)
value = io.getvalue()
self.transport.write(value)
def _encode(self, obj, write):
if isinstance(obj, (list, tuple)):
if len(obj) > SIZE_LIMIT:
raise BananaError(
"list/tuple is too long to send (%d)" % (len(obj),))
int2b128(len(obj), write)
write(LIST)
for elem in obj:
self._encode(elem, write)
elif isinstance(obj, (int, long)):
if obj < self._smallestLongInt or obj > self._largestLongInt:
raise BananaError(
"int/long is too large to send (%d)" % (obj,))
if obj < self._smallestInt:
int2b128(-obj, write)
write(LONGNEG)
elif obj < 0:
int2b128(-obj, write)
write(NEG)
elif obj <= self._largestInt:
int2b128(obj, write)
write(INT)
else:
int2b128(obj, write)
write(LONGINT)
elif isinstance(obj, float):
write(FLOAT)
write(struct.pack("!d", obj))
elif isinstance(obj, str):
# TODO: an API for extending banana...
if self.currentDialect == "pb" and obj in self.outgoingSymbols:
symbolID = self.outgoingSymbols[obj]
int2b128(symbolID, write)
write(VOCAB)
else:
if len(obj) > SIZE_LIMIT:
raise BananaError(
"string is too long to send (%d)" % (len(obj),))
int2b128(len(obj), write)
write(STRING)
write(obj)
else:
raise BananaError("could not send object: %r" % (obj,))
# For use from the interactive interpreter
_i = Banana()
_i.connectionMade()
_i._selectDialect("none")
def encode(lst):
"""Encode a list s-expression."""
io = cStringIO.StringIO()
_i.transport = io
_i.sendEncoded(lst)
return io.getvalue()
def decode(st):
"""
Decode a banana-encoded string.
"""
l = []
_i.expressionReceived = l.append
try:
_i.dataReceived(st)
finally:
_i.buffer = ''
del _i.expressionReceived
return l[0] | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/spread/banana.py | banana.py |
__version__ = "$Revision: 1.157 $"[11:-2]
# System Imports
try:
import cStringIO as StringIO
except ImportError:
import StringIO
import md5
import random
import new
import types
# Twisted Imports
from twisted.python import log, failure
from twisted.internet import defer, protocol
from twisted.cred.portal import Portal
from twisted.cred.credentials import ICredentials, IUsernameHashedPassword
from twisted.persisted import styles
from twisted.python.components import registerAdapter
from zope.interface import implements, Interface
# Sibling Imports
from twisted.spread.interfaces import IJellyable, IUnjellyable
from twisted.spread.jelly import jelly, unjelly, globalSecurity
from twisted.spread import banana
from twisted.spread.flavors import Serializable
from twisted.spread.flavors import Referenceable, NoSuchMethod
from twisted.spread.flavors import Root, IPBRoot
from twisted.spread.flavors import ViewPoint
from twisted.spread.flavors import Viewable
from twisted.spread.flavors import Copyable
from twisted.spread.flavors import Jellyable
from twisted.spread.flavors import Cacheable
from twisted.spread.flavors import RemoteCopy
from twisted.spread.flavors import RemoteCache
from twisted.spread.flavors import RemoteCacheObserver
from twisted.spread.flavors import copyTags
from twisted.spread.flavors import setCopierForClass, setUnjellyableForClass
from twisted.spread.flavors import setFactoryForClass
from twisted.spread.flavors import setCopierForClassTree
MAX_BROKER_REFS = 1024
portno = 8787
class ProtocolError(Exception):
"""
This error is raised when an invalid protocol statement is received.
"""
class DeadReferenceError(ProtocolError):
"""
This error is raised when a method is called on a dead reference (one whose
broker has been disconnected).
"""
class Error(Exception):
"""
This error can be raised to generate known error conditions.
When a PB callable method (perspective_, remote_, view_) raises
this error, it indicates that a traceback should not be printed,
but instead, the string representation of the exception should be
sent.
"""
class RemoteMethod:
"""This is a translucent reference to a remote message.
"""
def __init__(self, obj, name):
"""Initialize with a L{RemoteReference} and the name of this message.
"""
self.obj = obj
self.name = name
def __cmp__(self, other):
return cmp((self.obj, self.name), other)
def __hash__(self):
return hash((self.obj, self.name))
def __call__(self, *args, **kw):
"""Asynchronously invoke a remote method.
"""
return self.obj.broker._sendMessage('',self.obj.perspective, self.obj.luid, self.name, args, kw)
def noOperation(*args, **kw):
"""Do nothing.
Neque porro quisquam est qui dolorem ipsum quia dolor sit amet,
consectetur, adipisci velit...
"""
class PBConnectionLost(Exception):
pass
def printTraceback(tb):
"""Print a traceback (string) to the standard log.
"""
log.msg('Perspective Broker Traceback:' )
log.msg(tb)
class IPerspective(Interface):
"""
per*spec*tive, n. : The relationship of aspects of a subject to each
other and to a whole: 'a perspective of history'; 'a need to view
the problem in the proper perspective'.
This is a Perspective Broker-specific wrapper for an avatar. That
is to say, a PB-published view on to the business logic for the
system's concept of a 'user'.
The concept of attached/detached is no longer implemented by the
framework. The realm is expected to implement such semantics if
needed.
"""
def perspectiveMessageReceived(broker, message, args, kwargs):
"""
This method is called when a network message is received.
@arg broker: The Perspective Broker.
@type message: str
@arg message: The name of the method called by the other end.
@type args: list in jelly format
@arg args: The arguments that were passed by the other end. It
is recommend that you use the `unserialize' method of the
broker to decode this.
@type kwargs: dict in jelly format
@arg kwargs: The keyword arguments that were passed by the
other end. It is recommended that you use the
`unserialize' method of the broker to decode this.
@rtype: A jelly list.
@return: It is recommended that you use the `serialize' method
of the broker on whatever object you need to return to
generate the return value.
"""
class Avatar:
"""A default IPerspective implementor.
This class is intended to be subclassed, and a realm should return
an instance of such a subclass when IPerspective is requested of
it.
A peer requesting a perspective will receive only a
L{RemoteReference} to a pb.Avatar. When a method is called on
that L{RemoteReference}, it will translate to a method on the
remote perspective named 'perspective_methodname'. (For more
information on invoking methods on other objects, see
L{flavors.ViewPoint}.)
"""
implements(IPerspective)
def perspectiveMessageReceived(self, broker, message, args, kw):
"""This method is called when a network message is received.
I will call::
| self.perspective_%(message)s(*broker.unserialize(args),
| **broker.unserialize(kw))
to handle the method; subclasses of Avatar are expected to
implement methods of this naming convention.
"""
args = broker.unserialize(args, self)
kw = broker.unserialize(kw, self)
method = getattr(self, "perspective_%s" % message)
try:
state = method(*args, **kw)
except TypeError:
log.msg("%s didn't accept %s and %s" % (method, args, kw))
raise
return broker.serialize(state, self, method, args, kw)
class AsReferenceable(Referenceable):
"""AsReferenceable: a reference directed towards another object.
"""
def __init__(self, object, messageType="remote"):
"""Initialize me with an object.
"""
self.remoteMessageReceived = getattr(object, messageType + "MessageReceived")
class RemoteReference(Serializable, styles.Ephemeral):
"""This is a translucent reference to a remote object.
I may be a reference to a L{flavors.ViewPoint}, a
L{flavors.Referenceable}, or an L{IPerspective} implementor (e.g.,
pb.Avatar). From the client's perspective, it is not possible to
tell which except by convention.
I am a \"translucent\" reference because although no additional
bookkeeping overhead is given to the application programmer for
manipulating a reference, return values are asynchronous.
See also L{twisted.internet.defer}.
@ivar broker: The broker I am obtained through.
@type broker: L{Broker}
"""
implements(IUnjellyable)
def __init__(self, perspective, broker, luid, doRefCount):
"""(internal) Initialize me with a broker and a locally-unique ID.
The ID is unique only to the particular Perspective Broker
instance.
"""
self.luid = luid
self.broker = broker
self.doRefCount = doRefCount
self.perspective = perspective
self.disconnectCallbacks = []
def notifyOnDisconnect(self, callback):
"""Register a callback to be called if our broker gets disconnected.
This callback will be called with one argument, this instance.
"""
assert callable(callback)
self.disconnectCallbacks.append(callback)
if len(self.disconnectCallbacks) == 1:
self.broker.notifyOnDisconnect(self._disconnected)
def dontNotifyOnDisconnect(self, callback):
"""Remove a callback that was registered with notifyOnDisconnect."""
self.disconnectCallbacks.remove(callback)
if not self.disconnectCallbacks:
self.broker.dontNotifyOnDisconnect(self._disconnected)
def _disconnected(self):
"""Called if we are disconnected and have callbacks registered."""
for callback in self.disconnectCallbacks:
callback(self)
self.disconnectCallbacks = None
def jellyFor(self, jellier):
"""If I am being sent back to where I came from, serialize as a local backreference.
"""
if jellier.invoker:
assert self.broker == jellier.invoker, "Can't send references to brokers other than their own."
return "local", self.luid
else:
return "unpersistable", "References cannot be serialized"
def unjellyFor(self, unjellier, unjellyList):
self.__init__(unjellier.invoker.unserializingPerspective, unjellier.invoker, unjellyList[1], 1)
return self
def callRemote(self, _name, *args, **kw):
"""Asynchronously invoke a remote method.
@type _name: C{string}
@param _name: the name of the remote method to invoke
@param args: arguments to serialize for the remote function
@param kw: keyword arguments to serialize for the remote function.
@rtype: L{twisted.internet.defer.Deferred}
@returns: a Deferred which will be fired when the result of
this remote call is received.
"""
# note that we use '_name' instead of 'name' so the user can call
# remote methods with 'name' as a keyword parameter, like this:
# ref.callRemote("getPeopleNamed", count=12, name="Bob")
return self.broker._sendMessage('',self.perspective, self.luid,
_name, args, kw)
def remoteMethod(self, key):
"""Get a L{RemoteMethod} for this key.
"""
return RemoteMethod(self, key)
def __cmp__(self,other):
"""Compare me [to another L{RemoteReference}].
"""
if isinstance(other, RemoteReference):
if other.broker == self.broker:
return cmp(self.luid, other.luid)
return cmp(self.broker, other)
def __hash__(self):
"""Hash me.
"""
return self.luid
def __del__(self):
"""Do distributed reference counting on finalization.
"""
if self.doRefCount:
self.broker.sendDecRef(self.luid)
setUnjellyableForClass("remote", RemoteReference)
class Local:
"""(internal) A reference to a local object.
"""
def __init__(self, object, perspective=None):
"""Initialize.
"""
self.object = object
self.perspective = perspective
self.refcount = 1
def __repr__(self):
return "<pb.Local %r ref:%s>" % (self.object, self.refcount)
def incref(self):
"""Increment and return my reference count.
"""
self.refcount = self.refcount + 1
return self.refcount
def decref(self):
"""Decrement and return my reference count.
"""
self.refcount = self.refcount - 1
return self.refcount
class _RemoteCacheDummy:
"""Ignore.
"""
##
# Failure
##
class CopyableFailure(failure.Failure, Copyable):
"""
A L{flavors.RemoteCopy} and L{flavors.Copyable} version of
L{twisted.python.failure.Failure} for serialization.
"""
unsafeTracebacks = 0
def getStateToCopy(self):
#state = self.__getstate__()
state = self.__dict__.copy()
state['tb'] = None
state['frames'] = []
state['stack'] = []
if isinstance(self.value, failure.Failure):
state['value'] = failure2Copyable(self.value, self.unsafeTracebacks)
else:
state['value'] = str(self.value) # Exception instance
state['type'] = str(self.type) # Exception class
if self.unsafeTracebacks:
io = StringIO.StringIO()
self.printTraceback(io)
state['traceback'] = io.getvalue()
else:
state['traceback'] = 'Traceback unavailable\n'
return state
class CopiedFailure(RemoteCopy, failure.Failure):
def printTraceback(self, file=None, elideFrameworkCode=0, detail='default'):
if file is None:
file = log.logfile
file.write("Traceback from remote host -- ")
file.write(self.traceback)
printBriefTraceback = printTraceback
printDetailedTraceback = printTraceback
setUnjellyableForClass(CopyableFailure, CopiedFailure)
def failure2Copyable(fail, unsafeTracebacks=0):
f = new.instance(CopyableFailure, fail.__dict__)
f.unsafeTracebacks = unsafeTracebacks
return f
class Broker(banana.Banana):
"""I am a broker for objects.
"""
version = 6
username = None
factory = None
def __init__(self, isClient=1, security=globalSecurity):
banana.Banana.__init__(self, isClient)
self.disconnected = 0
self.disconnects = []
self.failures = []
self.connects = []
self.localObjects = {}
self.security = security
self.pageProducers = []
self.currentRequestID = 0
self.currentLocalID = 0
# Some terms:
# PUID: process unique ID; return value of id() function. type "int".
# LUID: locally unique ID; an ID unique to an object mapped over this
# connection. type "int"
# GUID: (not used yet) globally unique ID; an ID for an object which
# may be on a redirected or meta server. Type as yet undecided.
# Dictionary mapping LUIDs to local objects.
# set above to allow root object to be assigned before connection is made
# self.localObjects = {}
# Dictionary mapping PUIDs to LUIDs.
self.luids = {}
# Dictionary mapping LUIDs to local (remotely cached) objects. Remotely
# cached means that they're objects which originate here, and were
# copied remotely.
self.remotelyCachedObjects = {}
# Dictionary mapping PUIDs to (cached) LUIDs
self.remotelyCachedLUIDs = {}
# Dictionary mapping (remote) LUIDs to (locally cached) objects.
self.locallyCachedObjects = {}
self.waitingForAnswers = {}
def resumeProducing(self):
"""Called when the consumer attached to me runs out of buffer.
"""
# Go backwards over the list so we can remove indexes from it as we go
for pageridx in xrange(len(self.pageProducers)-1, -1, -1):
pager = self.pageProducers[pageridx]
pager.sendNextPage()
if not pager.stillPaging():
del self.pageProducers[pageridx]
if not self.pageProducers:
self.transport.unregisterProducer()
# Streaming producer methods; not necessary to implement.
def pauseProducing(self):
pass
def stopProducing(self):
pass
def registerPageProducer(self, pager):
self.pageProducers.append(pager)
if len(self.pageProducers) == 1:
self.transport.registerProducer(self, 0)
def expressionReceived(self, sexp):
"""Evaluate an expression as it's received.
"""
if isinstance(sexp, types.ListType):
command = sexp[0]
methodName = "proto_%s" % command
method = getattr(self, methodName, None)
if method:
method(*sexp[1:])
else:
self.sendCall("didNotUnderstand", command)
else:
raise ProtocolError("Non-list expression received.")
def proto_version(self, vnum):
"""Protocol message: (version version-number)
Check to make sure that both ends of the protocol are speaking
the same version dialect.
"""
if vnum != self.version:
raise ProtocolError("Version Incompatibility: %s %s" % (self.version, vnum))
def sendCall(self, *exp):
"""Utility method to send an expression to the other side of the connection.
"""
self.sendEncoded(exp)
def proto_didNotUnderstand(self, command):
"""Respond to stock 'C{didNotUnderstand}' message.
Log the command that was not understood and continue. (Note:
this will probably be changed to close the connection or raise
an exception in the future.)
"""
log.msg("Didn't understand command: %r" % command)
def connectionReady(self):
"""Initialize. Called after Banana negotiation is done.
"""
self.sendCall("version", self.version)
for notifier in self.connects:
try:
notifier()
except:
log.deferr()
self.connects = None
if self.factory: # in tests we won't have factory
self.factory.clientConnectionMade(self)
def connectionFailed(self):
# XXX should never get called anymore? check!
for notifier in self.failures:
try:
notifier()
except:
log.deferr()
self.failures = None
waitingForAnswers = None
def connectionLost(self, reason):
"""The connection was lost.
"""
self.disconnected = 1
# nuke potential circular references.
self.luids = None
if self.waitingForAnswers:
for d in self.waitingForAnswers.values():
try:
d.errback(failure.Failure(PBConnectionLost(reason)))
except:
log.deferr()
# Assure all Cacheable.stoppedObserving are called
for lobj in self.remotelyCachedObjects.values():
cacheable = lobj.object
perspective = lobj.perspective
try:
cacheable.stoppedObserving(perspective, RemoteCacheObserver(self, cacheable, perspective))
except:
log.deferr()
# Loop on a copy to prevent notifiers to mixup
# the list by calling dontNotifyOnDisconnect
for notifier in self.disconnects[:]:
try:
notifier()
except:
log.deferr()
self.disconnects = None
self.waitingForAnswers = None
self.localSecurity = None
self.remoteSecurity = None
self.remotelyCachedObjects = None
self.remotelyCachedLUIDs = None
self.locallyCachedObjects = None
self.localObjects = None
def notifyOnDisconnect(self, notifier):
"""Call the given callback when the Broker disconnects."""
assert callable(notifier)
self.disconnects.append(notifier)
def notifyOnFail(self, notifier):
"""Call the given callback if the Broker fails to connect."""
assert callable(notifier)
self.failures.append(notifier)
def notifyOnConnect(self, notifier):
"""Call the given callback when the Broker connects."""
assert callable(notifier)
if self.connects is None:
try:
notifier()
except:
log.err()
else:
self.connects.append(notifier)
def dontNotifyOnDisconnect(self, notifier):
"""Remove a callback from list of disconnect callbacks."""
try:
self.disconnects.remove(notifier)
except ValueError:
pass
def localObjectForID(self, luid):
"""Get a local object for a locally unique ID.
I will return an object previously stored with
self.L{registerReference}, or C{None} if XXX:Unfinished thought:XXX
"""
lob = self.localObjects.get(luid)
if lob is None:
return
return lob.object
maxBrokerRefsViolations = 0
def registerReference(self, object):
"""Get an ID for a local object.
Store a persistent reference to a local object and map its id()
to a generated, session-unique ID and return that ID.
"""
assert object is not None
puid = object.processUniqueID()
luid = self.luids.get(puid)
if luid is None:
if len(self.localObjects) > MAX_BROKER_REFS:
self.maxBrokerRefsViolations = self.maxBrokerRefsViolations + 1
if self.maxBrokerRefsViolations > 3:
self.transport.loseConnection()
raise Error("Maximum PB reference count exceeded. "
"Goodbye.")
raise Error("Maximum PB reference count exceeded.")
luid = self.newLocalID()
self.localObjects[luid] = Local(object)
self.luids[puid] = luid
else:
self.localObjects[luid].incref()
return luid
def setNameForLocal(self, name, object):
"""Store a special (string) ID for this object.
This is how you specify a 'base' set of objects that the remote
protocol can connect to.
"""
assert object is not None
self.localObjects[name] = Local(object)
def remoteForName(self, name):
"""Returns an object from the remote name mapping.
Note that this does not check the validity of the name, only
creates a translucent reference for it.
"""
return RemoteReference(None, self, name, 0)
def cachedRemotelyAs(self, instance, incref=0):
"""Returns an ID that says what this instance is cached as remotely, or C{None} if it's not.
"""
puid = instance.processUniqueID()
luid = self.remotelyCachedLUIDs.get(puid)
if (luid is not None) and (incref):
self.remotelyCachedObjects[luid].incref()
return luid
def remotelyCachedForLUID(self, luid):
"""Returns an instance which is cached remotely, with this LUID.
"""
return self.remotelyCachedObjects[luid].object
def cacheRemotely(self, instance):
"""
XXX"""
puid = instance.processUniqueID()
luid = self.newLocalID()
if len(self.remotelyCachedObjects) > MAX_BROKER_REFS:
self.maxBrokerRefsViolations = self.maxBrokerRefsViolations + 1
if self.maxBrokerRefsViolations > 3:
self.transport.loseConnection()
raise Error("Maximum PB cache count exceeded. "
"Goodbye.")
raise Error("Maximum PB cache count exceeded.")
self.remotelyCachedLUIDs[puid] = luid
# This table may not be necessary -- for now, it's to make sure that no
# monkey business happens with id(instance)
self.remotelyCachedObjects[luid] = Local(instance, self.serializingPerspective)
return luid
def cacheLocally(self, cid, instance):
"""(internal)
Store a non-filled-out cached instance locally.
"""
self.locallyCachedObjects[cid] = instance
def cachedLocallyAs(self, cid):
instance = self.locallyCachedObjects[cid]
return instance
def serialize(self, object, perspective=None, method=None, args=None, kw=None):
"""Jelly an object according to the remote security rules for this broker.
"""
if isinstance(object, defer.Deferred):
object.addCallbacks(self.serialize, lambda x: x,
callbackKeywords={
'perspective': perspective,
'method': method,
'args': args,
'kw': kw
})
return object
# XXX This call is NOT REENTRANT and testing for reentrancy is just
# crazy, so it likely won't be. Don't ever write methods that call the
# broker's serialize() method recursively (e.g. sending a method call
# from within a getState (this causes concurrency problems anyway so
# you really, really shouldn't do it))
# self.jellier = _NetJellier(self)
self.serializingPerspective = perspective
self.jellyMethod = method
self.jellyArgs = args
self.jellyKw = kw
try:
return jelly(object, self.security, None, self)
finally:
self.serializingPerspective = None
self.jellyMethod = None
self.jellyArgs = None
self.jellyKw = None
def unserialize(self, sexp, perspective = None):
"""Unjelly an sexp according to the local security rules for this broker.
"""
self.unserializingPerspective = perspective
try:
return unjelly(sexp, self.security, None, self)
finally:
self.unserializingPerspective = None
def newLocalID(self):
"""Generate a new LUID.
"""
self.currentLocalID = self.currentLocalID + 1
return self.currentLocalID
def newRequestID(self):
"""Generate a new request ID.
"""
self.currentRequestID = self.currentRequestID + 1
return self.currentRequestID
def _sendMessage(self, prefix, perspective, objectID, message, args, kw):
pbc = None
pbe = None
answerRequired = 1
if kw.has_key('pbcallback'):
pbc = kw['pbcallback']
del kw['pbcallback']
if kw.has_key('pberrback'):
pbe = kw['pberrback']
del kw['pberrback']
if kw.has_key('pbanswer'):
assert (not pbe) and (not pbc), "You can't specify a no-answer requirement."
answerRequired = kw['pbanswer']
del kw['pbanswer']
if self.disconnected:
raise DeadReferenceError("Calling Stale Broker")
try:
netArgs = self.serialize(args, perspective=perspective, method=message)
netKw = self.serialize(kw, perspective=perspective, method=message)
except:
return defer.fail(failure.Failure())
requestID = self.newRequestID()
if answerRequired:
rval = defer.Deferred()
self.waitingForAnswers[requestID] = rval
if pbc or pbe:
log.msg('warning! using deprecated "pbcallback"')
rval.addCallbacks(pbc, pbe)
else:
rval = None
self.sendCall(prefix+"message", requestID, objectID, message, answerRequired, netArgs, netKw)
return rval
def proto_message(self, requestID, objectID, message, answerRequired, netArgs, netKw):
self._recvMessage(self.localObjectForID, requestID, objectID, message, answerRequired, netArgs, netKw)
def proto_cachemessage(self, requestID, objectID, message, answerRequired, netArgs, netKw):
self._recvMessage(self.cachedLocallyAs, requestID, objectID, message, answerRequired, netArgs, netKw)
def _recvMessage(self, findObjMethod, requestID, objectID, message, answerRequired, netArgs, netKw):
"""Received a message-send.
Look up message based on object, unserialize the arguments, and
invoke it with args, and send an 'answer' or 'error' response.
"""
try:
object = findObjMethod(objectID)
if object is None:
raise Error("Invalid Object ID")
netResult = object.remoteMessageReceived(self, message, netArgs, netKw)
except Error, e:
if answerRequired:
# If the error is Jellyable or explicitly allowed via our
# security options, send it back and let the code on the
# other end deal with unjellying. If it isn't Jellyable,
# wrap it in a CopyableFailure, which ensures it can be
# unjellied on the other end. We have to do this because
# all errors must be sent back.
if isinstance(e, Jellyable) or self.security.isClassAllowed(e.__class__):
self._sendError(e, requestID)
else:
self._sendError(CopyableFailure(e), requestID)
except:
if answerRequired:
log.msg("Peer will receive following PB traceback:", isError=True)
f = CopyableFailure()
self._sendError(f, requestID)
log.err()
else:
if answerRequired:
if isinstance(netResult, defer.Deferred):
args = (requestID,)
netResult.addCallbacks(self._sendAnswer, self._sendFailureOrError,
callbackArgs=args, errbackArgs=args)
# XXX Should this be done somewhere else?
else:
self._sendAnswer(netResult, requestID)
##
# success
##
def _sendAnswer(self, netResult, requestID):
"""(internal) Send an answer to a previously sent message.
"""
self.sendCall("answer", requestID, netResult)
def proto_answer(self, requestID, netResult):
"""(internal) Got an answer to a previously sent message.
Look up the appropriate callback and call it.
"""
d = self.waitingForAnswers[requestID]
del self.waitingForAnswers[requestID]
d.callback(self.unserialize(netResult))
##
# failure
##
def _sendFailureOrError(self, fail, requestID):
"""
Call L{_sendError} or L{_sendFailure}, depending on whether C{fail}
represents an L{Error} subclass or not.
"""
if fail.check(Error) is None:
self._sendFailure(fail, requestID)
else:
self._sendError(fail, requestID)
def _sendFailure(self, fail, requestID):
"""Log error and then send it."""
log.msg("Peer will receive following PB traceback:")
log.err(fail)
self._sendError(fail, requestID)
def _sendError(self, fail, requestID):
"""(internal) Send an error for a previously sent message.
"""
if isinstance(fail, failure.Failure):
# If the failures value is jellyable or allowed through security,
# send the value
if (isinstance(fail.value, Jellyable) or
self.security.isClassAllowed(fail.value.__class__)):
fail = fail.value
elif not isinstance(fail, CopyableFailure):
fail = failure2Copyable(fail, self.factory.unsafeTracebacks)
if isinstance(fail, CopyableFailure):
fail.unsafeTracebacks = self.factory.unsafeTracebacks
self.sendCall("error", requestID, self.serialize(fail))
def proto_error(self, requestID, fail):
"""(internal) Deal with an error.
"""
d = self.waitingForAnswers[requestID]
del self.waitingForAnswers[requestID]
d.errback(self.unserialize(fail))
##
# refcounts
##
def sendDecRef(self, objectID):
"""(internal) Send a DECREF directive.
"""
self.sendCall("decref", objectID)
def proto_decref(self, objectID):
"""(internal) Decrement the reference count of an object.
If the reference count is zero, it will free the reference to this
object.
"""
refs = self.localObjects[objectID].decref()
if refs == 0:
puid = self.localObjects[objectID].object.processUniqueID()
del self.luids[puid]
del self.localObjects[objectID]
##
# caching
##
def decCacheRef(self, objectID):
"""(internal) Send a DECACHE directive.
"""
self.sendCall("decache", objectID)
def proto_decache(self, objectID):
"""(internal) Decrement the reference count of a cached object.
If the reference count is zero, free the reference, then send an
'uncached' directive.
"""
refs = self.remotelyCachedObjects[objectID].decref()
# log.msg('decaching: %s #refs: %s' % (objectID, refs))
if refs == 0:
lobj = self.remotelyCachedObjects[objectID]
cacheable = lobj.object
perspective = lobj.perspective
# TODO: force_decache needs to be able to force-invalidate a
# cacheable reference.
try:
cacheable.stoppedObserving(perspective, RemoteCacheObserver(self, cacheable, perspective))
except:
log.deferr()
puid = cacheable.processUniqueID()
del self.remotelyCachedLUIDs[puid]
del self.remotelyCachedObjects[objectID]
self.sendCall("uncache", objectID)
def proto_uncache(self, objectID):
"""(internal) Tell the client it is now OK to uncache an object.
"""
# log.msg("uncaching locally %d" % objectID)
obj = self.locallyCachedObjects[objectID]
obj.broker = None
## def reallyDel(obj=obj):
## obj.__really_del__()
## obj.__del__ = reallyDel
del self.locallyCachedObjects[objectID]
def respond(challenge, password):
"""Respond to a challenge.
This is useful for challenge/response authentication.
"""
m = md5.new()
m.update(password)
hashedPassword = m.digest()
m = md5.new()
m.update(hashedPassword)
m.update(challenge)
doubleHashedPassword = m.digest()
return doubleHashedPassword
def challenge():
"""I return some random data."""
crap = ''
for x in range(random.randrange(15,25)):
crap = crap + chr(random.randint(65,90))
crap = md5.new(crap).digest()
return crap
class PBClientFactory(protocol.ClientFactory):
"""Client factory for PB brokers.
As with all client factories, use with reactor.connectTCP/SSL/etc..
getPerspective and getRootObject can be called either before or
after the connect.
"""
protocol = Broker
unsafeTracebacks = 0
def __init__(self):
self._reset()
def _reset(self):
self.rootObjectRequests = [] # list of deferred
self._broker = None
self._root = None
def _failAll(self, reason):
deferreds = self.rootObjectRequests
self._reset()
for d in deferreds:
d.errback(reason)
def clientConnectionFailed(self, connector, reason):
self._failAll(reason)
def clientConnectionLost(self, connector, reason, reconnecting=0):
"""Reconnecting subclasses should call with reconnecting=1."""
if reconnecting:
# any pending requests will go to next connection attempt
# so we don't fail them.
self._broker = None
self._root = None
else:
self._failAll(reason)
def clientConnectionMade(self, broker):
self._broker = broker
self._root = broker.remoteForName("root")
ds = self.rootObjectRequests
self.rootObjectRequests = []
for d in ds:
d.callback(self._root)
def getRootObject(self):
"""Get root object of remote PB server.
@return: Deferred of the root object.
"""
if self._broker and not self._broker.disconnected:
return defer.succeed(self._root)
d = defer.Deferred()
self.rootObjectRequests.append(d)
return d
def disconnect(self):
"""If the factory is connected, close the connection.
Note that if you set up the factory to reconnect, you will need to
implement extra logic to prevent automatic reconnection after this
is called.
"""
if self._broker:
self._broker.transport.loseConnection()
def _cbSendUsername(self, root, username, password, client):
return root.callRemote("login", username).addCallback(
self._cbResponse, password, client)
def _cbResponse(self, (challenge, challenger), password, client):
return challenger.callRemote("respond", respond(challenge, password), client)
def login(self, credentials, client=None):
"""Login and get perspective from remote PB server.
Currently only credentials implementing
L{twisted.cred.credentials.IUsernamePassword} are supported.
@return: Deferred of RemoteReference to the perspective.
"""
d = self.getRootObject()
d.addCallback(self._cbSendUsername, credentials.username, credentials.password, client)
return d
class PBServerFactory(protocol.ServerFactory):
"""Server factory for perspective broker.
Login is done using a Portal object, whose realm is expected to return
avatars implementing IPerspective. The credential checkers in the portal
should accept IUsernameHashedPassword or IUsernameMD5Password.
Alternatively, any object implementing or adaptable to IPBRoot can
be used instead of a portal to provide the root object of the PB
server.
"""
unsafeTracebacks = 0
# object broker factory
protocol = Broker
def __init__(self, root, unsafeTracebacks=False):
self.root = IPBRoot(root)
self.unsafeTracebacks = unsafeTracebacks
def buildProtocol(self, addr):
"""Return a Broker attached to me (as the service provider).
"""
proto = self.protocol(0)
proto.factory = self
proto.setNameForLocal("root", self.root.rootObject(proto))
return proto
def clientConnectionMade(self, protocol):
pass
class IUsernameMD5Password(ICredentials):
"""I encapsulate a username and a hashed password.
This credential is used for username/password over
PB. CredentialCheckers which check this kind of credential must
store the passwords in plaintext form or as a MD5 digest.
@type username: C{str} or C{Deferred}
@ivar username: The username associated with these credentials.
"""
def checkPassword(password):
"""Validate these credentials against the correct password.
@param password: The correct, plaintext password against which to
check.
@return: a deferred which becomes, or a boolean indicating if the
password matches.
"""
def checkMD5Password(password):
"""Validate these credentials against the correct MD5 digest of password.
@param password: The correct, plaintext password against which to
check.
@return: a deferred which becomes, or a boolean indicating if the
password matches.
"""
class _PortalRoot:
"""Root object, used to login to portal."""
implements(IPBRoot)
def __init__(self, portal):
self.portal = portal
def rootObject(self, broker):
return _PortalWrapper(self.portal, broker)
registerAdapter(_PortalRoot, Portal, IPBRoot)
class _PortalWrapper(Referenceable):
"""Root Referenceable object, used to login to portal."""
def __init__(self, portal, broker):
self.portal = portal
self.broker = broker
def remote_login(self, username):
"""Start of username/password login."""
c = challenge()
return c, _PortalAuthChallenger(self, username, c)
class _PortalAuthChallenger(Referenceable):
"""Called with response to password challenge."""
implements(IUsernameHashedPassword, IUsernameMD5Password)
def __init__(self, portalWrapper, username, challenge):
self.portalWrapper = portalWrapper
self.username = username
self.challenge = challenge
def remote_respond(self, response, mind):
self.response = response
d = self.portalWrapper.portal.login(self, mind, IPerspective)
d.addCallback(self._loggedIn)
return d
def _loggedIn(self, (interface, perspective, logout)):
if not IJellyable.providedBy(perspective):
perspective = AsReferenceable(perspective, "perspective")
self.portalWrapper.broker.notifyOnDisconnect(logout)
return perspective
# IUsernameHashedPassword:
def checkPassword(self, password):
return self.checkMD5Password(md5.md5(password).digest())
# IUsernameMD5Password
def checkMD5Password(self, md5Password):
md = md5.new()
md.update(md5Password)
md.update(self.challenge)
correct = md.digest()
return self.response == correct | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/spread/pb.py | pb.py |
__version__ = "$Revision: 1.17 $"[11:-2]
"""
Path-based references for PB, and other reference-based protocols.
Maintainer: U{Glyph Lefkowitz<mailto:[email protected]>}
Stability: semi-stable
Future Plans: None at this point besides a final overview and finalization
pass.
"""
from twisted.python import log
from flavors import Referenceable, Viewable
from copy import copy
import os
### "Server"-side objects
class PathReferenceContext:
def __init__(self, path, root):
self.metadata = {}
self.path = path
self.root = root
def __setitem__(self, key, item):
self.metadata[key] = item
def __getitem__(self, key):
return self.metadata[key]
def getObject(self):
o = self.root
for p in self.path:
o = o.getChild(p, self)
return o
class PathReference:
def __init__(self):
self.children = {}
def getChild(self, child, ctx):
return self.children[child]
class PathReferenceDirectory(Referenceable):
def __init__(self, root, prefix="remote"):
self.root = root
self.prefix = prefix
def remote_callPath(self, path, name, *args, **kw):
ctx = PathReferenceContext(path, self)
obj = ctx.getObject()
return apply(getattr(obj, "%s_%s" % (self.prefix, name)), args, kw)
class PathReferenceContextDirectory(Referenceable):
def __init__(self, root, prefix="remote"):
self.root = root
self.prefix = prefix
def remote_callPath(self, path, name, *args, **kw):
ctx = PathReferenceContext(path, self)
obj = ctx.getObject()
return apply(getattr(obj, "%s_%s" % (self.prefix, name)),
(ctx,)+args, kw)
class PathViewDirectory(Viewable):
def __init__(self, root, prefix="view"):
self.root = root
self.prefix = prefix
def view_callPath(self, perspective, path, name, *args, **kw):
ctx = PathReferenceContext(path, self)
obj = ctx.getObject()
return apply(getattr(obj, "%s_%s" % (self.prefix, name)),
(perspective,)+args, kw)
class PathViewContextDirectory(Viewable):
def __init__(self, root, prefix="view"):
self.root = root
self.prefix = prefix
def view_callPath(self, perspective, path, name, *args, **kw):
ctx = PathReferenceContext(path, self)
obj = ctx.getObject()
return apply(getattr(obj, "%s_%s" % (self.prefix, name)),
(perspective,ctx)+args, kw)
### "Client"-side objects
class RemotePathReference:
def __init__(self, ref, path):
self.ref = ref
self.path = path
def callRemote(self, name, *args, **kw):
apply(self.ref.callRemote,
("callPath", self.path, name)+args, kw) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/spread/refpath.py | refpath.py |
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
"""S-expression-based persistence of python objects.
Stability: semi-stable
Future Plans: Optimization. Lots of optimization. No semantic breakages
should be necessary, but if small tweaks are required to gain acceptable
large-scale performance then they will be made. Although Glyph is the
maintainer, Bruce Mitchener will be supervising most of the optimization work
here.
I do something very much like L{Pickle<pickle>}; however, pickle's main goal
seems to be efficiency (both in space and time); jelly's main goals are
security, human readability, and portability to other environments.
This is how Jelly converts various objects to s-expressions:
Boolean: True --> ['boolean', 'true']
Integer: 1 --> 1
List: [1, 2] --> ['list', 1, 2]
String: \"hello\" --> \"hello\"
Float: 2.3 --> 2.3
Dictionary: {'a' : 1, 'b' : 'c'} --> ['dictionary', ['b', 'c'], ['a', 1]]
Module: UserString --> ['module', 'UserString']
Class: UserString.UserString --> ['class', ['module', 'UserString'], 'UserString']
Function: string.join --> ['function', 'join', ['module', 'string']]
Instance: s is an instance of UserString.UserString, with a __dict__ {'data': 'hello'}:
[\"UserString.UserString\", ['dictionary', ['data', 'hello']]]
# ['instance', ['class', ['module', 'UserString'], 'UserString'], ['dictionary', ['data', 'hello']]]
Class Method: UserString.UserString.center:
['method', 'center', ['None'], ['class', ['module', 'UserString'], 'UserString']]
Instance Method: s.center, where s is an instance of UserString.UserString:
['method', 'center', ['instance', ['reference', 1, ['class', ['module', 'UserString'], 'UserString']], ['dictionary', ['data', 'd']]], ['dereference', 1]]
@author: U{Glyph Lefkowitz<mailto:[email protected]>}
"""
__version__ = "$Revision: 1.48 $"[11:-2]
# System Imports
import string
import pickle
import types
from types import StringType
try:
from types import UnicodeType
except ImportError:
UnicodeType = None
from types import IntType
from types import TupleType
from types import ListType
from types import LongType
from types import FloatType
from types import FunctionType
from types import MethodType
from types import ModuleType
from types import DictionaryType
from types import InstanceType
from types import NoneType
from types import ClassType
import copy
import datetime
from types import BooleanType
from new import instance
from new import instancemethod
from zope.interface import implements
# Twisted Imports
from twisted.python.reflect import namedObject, qual
from twisted.persisted.crefutil import NotKnown, _Tuple, _InstanceMethod, _DictKeyAndValue, _Dereference
from twisted.python import runtime
from twisted.spread.interfaces import IJellyable, IUnjellyable
if runtime.platform.getType() == "java":
from org.python.core import PyStringMap
DictTypes = (DictionaryType, PyStringMap)
else:
DictTypes = (DictionaryType,)
None_atom = "None" # N
# code
class_atom = "class" # c
module_atom = "module" # m
function_atom = "function" # f
# references
dereference_atom = 'dereference' # D
persistent_atom = 'persistent' # p
reference_atom = 'reference' # r
# mutable collections
dictionary_atom = "dictionary" # d
list_atom = 'list' # l
# immutable collections
# (assignment to __dict__ and __class__ still might go away!)
tuple_atom = "tuple" # t
instance_atom = 'instance' # i
# errors
unpersistable_atom = "unpersistable"# u
unjellyableRegistry = {}
unjellyableFactoryRegistry = {}
def _newInstance(cls, state):
"""Make a new instance of a class without calling its __init__ method.
'state' will be used to update inst.__dict__ . Supports both new- and
old-style classes.
"""
if not isinstance(cls, types.ClassType):
# new-style
inst = cls.__new__(cls)
inst.__dict__.update(state) # Copy 'instance' behaviour
else:
inst = instance(cls, state)
return inst
def _maybeClass(classnamep):
try:
object
except NameError:
isObject = 0
else:
isObject = isinstance(classnamep, type)
if isinstance(classnamep, ClassType) or isObject:
return qual(classnamep)
return classnamep
def setUnjellyableForClass(classname, unjellyable):
"""Set which local class will represent a remote type.
If you have written a Copyable class that you expect your client to be
receiving, write a local "copy" class to represent it, then call::
jellier.setUnjellyableForClass('module.package.Class', MyJellier).
Call this at the module level immediately after its class
definition. MyCopier should be a subclass of RemoteCopy.
The classname may be a special tag returned by
'Copyable.getTypeToCopyFor' rather than an actual classname.
This call is also for cached classes, since there will be no
overlap. The rules are the same.
"""
global unjellyableRegistry
classname = _maybeClass(classname)
unjellyableRegistry[classname] = unjellyable
globalSecurity.allowTypes(classname)
def setUnjellyableFactoryForClass(classname, copyFactory):
"""
Set the factory to construct a remote instance of a type::
jellier.setFactoryForClass('module.package.Class', MyFactory)
Call this at the module level immediately after its class definition.
C{copyFactory} should return an instance or subclass of
L{RemoteCopy<pb.RemoteCopy>}.
Similar to L{setUnjellyableForClass} except it uses a factory instead
of creating an instance.
"""
global unjellyableFactoryRegistry
classname = _maybeClass(classname)
unjellyableFactoryRegistry[classname] = copyFactory
globalSecurity.allowTypes(classname)
def setUnjellyableForClassTree(module, baseClass, prefix=None):
"""
Set all classes in a module derived from C{baseClass} as copiers for
a corresponding remote class.
When you have a heirarchy of Copyable (or Cacheable) classes on
one side, and a mirror structure of Copied (or RemoteCache)
classes on the other, use this to setCopierForClass all your
Copieds for the Copyables.
Each copyTag (the \"classname\" argument to getTypeToCopyFor, and
what the Copyable's getTypeToCopyFor returns) is formed from
adding a prefix to the Copied's class name. The prefix defaults
to module.__name__. If you wish the copy tag to consist of solely
the classname, pass the empty string \'\'.
@param module: a module object from which to pull the Copied classes.
(passing sys.modules[__name__] might be useful)
@param baseClass: the base class from which all your Copied classes derive.
@param prefix: the string prefixed to classnames to form the
unjellyableRegistry.
"""
if prefix is None:
prefix = module.__name__
if prefix:
prefix = "%s." % prefix
for i in dir(module):
i_ = getattr(module, i)
if type(i_) == types.ClassType:
if issubclass(i_, baseClass):
setUnjellyableForClass('%s%s' % (prefix, i), i_)
def getInstanceState(inst, jellier):
"""Utility method to default to 'normal' state rules in serialization.
"""
if hasattr(inst, "__getstate__"):
state = inst.__getstate__()
else:
state = inst.__dict__
sxp = jellier.prepare(inst)
sxp.extend([qual(inst.__class__), jellier.jelly(state)])
return jellier.preserve(inst, sxp)
def setInstanceState(inst, unjellier, jellyList):
"""Utility method to default to 'normal' state rules in unserialization.
"""
state = unjellier.unjelly(jellyList[1])
if hasattr(inst, "__setstate__"):
inst.__setstate__(state)
else:
inst.__dict__ = state
return inst
class Unpersistable:
"""
This is an instance of a class that comes back when something couldn't be
persisted.
"""
def __init__(self, reason):
"""
Initialize an unpersistable object with a descriptive `reason' string.
"""
self.reason = reason
def __repr__(self):
return "Unpersistable(%s)" % repr(self.reason)
class Jellyable:
"""
Inherit from me to Jelly yourself directly with the `getStateFor'
convenience method.
"""
implements(IJellyable)
def getStateFor(self, jellier):
return self.__dict__
def jellyFor(self, jellier):
"""
@see L{twisted.spread.interfaces.IJellyable.jellyFor}
"""
sxp = jellier.prepare(self)
sxp.extend([
qual(self.__class__),
jellier.jelly(self.getStateFor(jellier))])
return jellier.preserve(self, sxp)
class Unjellyable:
"""
Inherit from me to Unjelly yourself directly with the
`setStateFor' convenience method.
"""
implements(IUnjellyable)
def setStateFor(self, unjellier, state):
self.__dict__ = state
def unjellyFor(self, unjellier, jellyList):
"""
Perform the inverse operation of L{Jellyable.jellyFor}.
@see L{twisted.spread.interfaces.IUnjellyable.unjellyFor}
"""
state = unjellier.unjelly(jellyList[1])
self.setStateFor(unjellier, state)
return self
class _Jellier:
"""(Internal) This class manages state for a call to jelly()
"""
def __init__(self, taster, persistentStore, invoker):
"""Initialize.
"""
self.taster = taster
# `preserved' is a dict of previously seen instances.
self.preserved = {}
# `cooked' is a dict of previously backreferenced instances to their `ref' lists.
self.cooked = {}
self.cooker = {}
self._ref_id = 1
self.persistentStore = persistentStore
self.invoker = invoker
def _cook(self, object):
"""(internal)
backreference an object.
Notes on this method for the hapless future maintainer: If I've already
gone through the prepare/preserve cycle on the specified object (it is
being referenced after the serializer is \"done with\" it, e.g. this
reference is NOT circular), the copy-in-place of aList is relevant,
since the list being modified is the actual, pre-existing jelly
expression that was returned for that object. If not, it's technically
superfluous, since the value in self.preserved didn't need to be set,
but the invariant that self.preserved[id(object)] is a list is
convenient because that means we don't have to test and create it or
not create it here, creating fewer code-paths. that's why
self.preserved is always set to a list.
Sorry that this code is so hard to follow, but Python objects are
tricky to persist correctly. -glyph
"""
aList = self.preserved[id(object)]
newList = copy.copy(aList)
# make a new reference ID
refid = self._ref_id
self._ref_id = self._ref_id + 1
# replace the old list in-place, so that we don't have to track the
# previous reference to it.
aList[:] = [reference_atom, refid, newList]
self.cooked[id(object)] = [dereference_atom, refid]
return aList
def prepare(self, object):
"""(internal)
create a list for persisting an object to. this will allow
backreferences to be made internal to the object. (circular
references).
The reason this needs to happen is that we don't generate an ID for
every object, so we won't necessarily know which ID the object will
have in the future. When it is 'cooked' ( see _cook ), it will be
assigned an ID, and the temporary placeholder list created here will be
modified in-place to create an expression that gives this object an ID:
[reference id# [object-jelly]].
"""
# create a placeholder list to be preserved
self.preserved[id(object)] = []
# keep a reference to this object around, so it doesn't disappear!
# (This isn't always necessary, but for cases where the objects are
# dynamically generated by __getstate__ or getStateToCopyFor calls, it
# is; id() will return the same value for a different object if it gets
# garbage collected. This may be optimized later.)
self.cooker[id(object)] = object
return []
def preserve(self, object, sexp):
"""(internal)
mark an object's persistent list for later referral
"""
#if I've been cooked in the meanwhile,
if self.cooked.has_key(id(object)):
# replace the placeholder empty list with the real one
self.preserved[id(object)][2] = sexp
# but give this one back.
sexp = self.preserved[id(object)]
else:
self.preserved[id(object)] = sexp
return sexp
constantTypes = {types.StringType : 1, types.IntType : 1,
types.FloatType : 1, types.LongType : 1}
def _checkMutable(self,obj):
objId = id(obj)
if self.cooked.has_key(objId):
return self.cooked[objId]
if self.preserved.has_key(objId):
self._cook(obj)
return self.cooked[objId]
def jelly(self, obj):
if isinstance(obj, Jellyable):
preRef = self._checkMutable(obj)
if preRef:
return preRef
return obj.jellyFor(self)
objType = type(obj)
if self.taster.isTypeAllowed(qual(objType)):
# "Immutable" Types
if ((objType is StringType) or
(objType is IntType) or
(objType is LongType) or
(objType is FloatType)):
return obj
elif objType is MethodType:
return ["method",
obj.im_func.__name__,
self.jelly(obj.im_self),
self.jelly(obj.im_class)]
elif UnicodeType and objType is UnicodeType:
return ['unicode', obj.encode('UTF-8')]
elif objType is NoneType:
return ['None']
elif objType is FunctionType:
name = obj.__name__
return ['function', str(pickle.whichmodule(obj, obj.__name__))
+ '.' +
name]
elif objType is ModuleType:
return ['module', obj.__name__]
elif objType is BooleanType:
return ['boolean', obj and 'true' or 'false']
elif objType is datetime.datetime:
if obj.tzinfo:
raise NotImplementedError, "Currently can't jelly datetime objects with tzinfo"
return ['datetime', '%s %s %s %s %s %s %s' % (obj.year, obj.month, obj.day, obj.hour, obj.minute, obj.second, obj.microsecond)]
elif objType is datetime.time:
if obj.tzinfo:
raise NotImplementedError, "Currently can't jelly datetime objects with tzinfo"
return ['time', '%s %s %s %s' % (obj.hour, obj.minute, obj.second, obj.microsecond)]
elif objType is datetime.date:
return ['date', '%s %s %s' % (obj.year, obj.month, obj.day)]
elif objType is datetime.timedelta:
return ['timedelta', '%s %s %s' % (obj.days, obj.seconds, obj.microseconds)]
elif objType is ClassType or issubclass(objType, type):
return ['class', qual(obj)]
else:
preRef = self._checkMutable(obj)
if preRef:
return preRef
# "Mutable" Types
sxp = self.prepare(obj)
if objType is ListType:
sxp.append(list_atom)
for item in obj:
sxp.append(self.jelly(item))
elif objType is TupleType:
sxp.append(tuple_atom)
for item in obj:
sxp.append(self.jelly(item))
elif objType in DictTypes:
sxp.append(dictionary_atom)
for key, val in obj.items():
sxp.append([self.jelly(key), self.jelly(val)])
else:
className = qual(obj.__class__)
persistent = None
if self.persistentStore:
persistent = self.persistentStore(obj, self)
if persistent is not None:
sxp.append(persistent_atom)
sxp.append(persistent)
elif self.taster.isClassAllowed(obj.__class__):
sxp.append(className)
if hasattr(obj, "__getstate__"):
state = obj.__getstate__()
else:
state = obj.__dict__
sxp.append(self.jelly(state))
else:
self.unpersistable(
"instance of class %s deemed insecure" %
qual(obj.__class__), sxp)
return self.preserve(obj, sxp)
else:
if objType is InstanceType:
raise InsecureJelly("Class not allowed for instance: %s %s" %
(obj.__class__, obj))
raise InsecureJelly("Type not allowed for object: %s %s" %
(objType, obj))
def unpersistable(self, reason, sxp=None):
'''(internal)
Returns an sexp: (unpersistable "reason"). Utility method for making
note that a particular object could not be serialized.
'''
if sxp is None:
sxp = []
sxp.append(unpersistable_atom)
sxp.append(reason)
return sxp
class _Unjellier:
def __init__(self, taster, persistentLoad, invoker):
self.taster = taster
self.persistentLoad = persistentLoad
self.references = {}
self.postCallbacks = []
self.invoker = invoker
def unjellyFull(self, obj):
o = self.unjelly(obj)
for m in self.postCallbacks:
m()
return o
def unjelly(self, obj):
if type(obj) is not types.ListType:
return obj
jelType = obj[0]
if not self.taster.isTypeAllowed(jelType):
raise InsecureJelly(jelType)
regClass = unjellyableRegistry.get(jelType)
if regClass is not None:
if isinstance(regClass, ClassType):
inst = _Dummy() # XXX chomp, chomp
inst.__class__ = regClass
method = inst.unjellyFor
elif isinstance(regClass, type):
# regClass.__new__ does not call regClass.__init__
inst = regClass.__new__(regClass)
method = inst.unjellyFor
else:
method = regClass # this is how it ought to be done
val = method(self, obj)
if hasattr(val, 'postUnjelly'):
self.postCallbacks.append(inst.postUnjelly)
return val
regFactory = unjellyableFactoryRegistry.get(jelType)
if regFactory is not None:
state = self.unjelly(obj[1])
inst = regFactory(state)
if hasattr(inst, 'postUnjelly'):
self.postCallbacks.append(inst.postUnjelly)
return inst
thunk = getattr(self, '_unjelly_%s'%jelType, None)
if thunk is not None:
ret = thunk(obj[1:])
else:
nameSplit = string.split(jelType, '.')
modName = string.join(nameSplit[:-1], '.')
if not self.taster.isModuleAllowed(modName):
raise InsecureJelly("Module %s not allowed (in type %s)." % (modName, jelType))
clz = namedObject(jelType)
if not self.taster.isClassAllowed(clz):
raise InsecureJelly("Class %s not allowed." % jelType)
if hasattr(clz, "__setstate__"):
ret = _newInstance(clz, {})
state = self.unjelly(obj[1])
ret.__setstate__(state)
else:
state = self.unjelly(obj[1])
ret = _newInstance(clz, state)
if hasattr(clz, 'postUnjelly'):
self.postCallbacks.append(ret.postUnjelly)
return ret
def _unjelly_None(self, exp):
return None
def _unjelly_unicode(self, exp):
if UnicodeType:
return unicode(exp[0], "UTF-8")
else:
return Unpersistable(exp[0])
def _unjelly_boolean(self, exp):
if BooleanType:
assert exp[0] in ('true', 'false')
return exp[0] == 'true'
else:
return Unpersistable(exp[0])
def _unjelly_datetime(self, exp):
return datetime.datetime(*map(int, exp[0].split()))
def _unjelly_date(self, exp):
return datetime.date(*map(int, exp[0].split()))
def _unjelly_time(self, exp):
return datetime.time(*map(int, exp[0].split()))
def _unjelly_timedelta(self, exp):
days, seconds, microseconds = map(int, exp[0].split())
return datetime.timedelta(days=days, seconds=seconds, microseconds=microseconds)
def unjellyInto(self, obj, loc, jel):
o = self.unjelly(jel)
if isinstance(o, NotKnown):
o.addDependant(obj, loc)
obj[loc] = o
return o
def _unjelly_dereference(self, lst):
refid = lst[0]
x = self.references.get(refid)
if x is not None:
return x
der = _Dereference(refid)
self.references[refid] = der
return der
def _unjelly_reference(self, lst):
refid = lst[0]
exp = lst[1]
o = self.unjelly(exp)
ref = self.references.get(refid)
if (ref is None):
self.references[refid] = o
elif isinstance(ref, NotKnown):
ref.resolveDependants(o)
self.references[refid] = o
else:
assert 0, "Multiple references with same ID!"
return o
def _unjelly_tuple(self, lst):
l = range(len(lst))
finished = 1
for elem in l:
if isinstance(self.unjellyInto(l, elem, lst[elem]), NotKnown):
finished = 0
if finished:
return tuple(l)
else:
return _Tuple(l)
def _unjelly_list(self, lst):
l = range(len(lst))
for elem in l:
self.unjellyInto(l, elem, lst[elem])
return l
def _unjelly_dictionary(self, lst):
d = {}
for k, v in lst:
kvd = _DictKeyAndValue(d)
self.unjellyInto(kvd, 0, k)
self.unjellyInto(kvd, 1, v)
return d
def _unjelly_module(self, rest):
moduleName = rest[0]
if type(moduleName) != types.StringType:
raise InsecureJelly("Attempted to unjelly a module with a non-string name.")
if not self.taster.isModuleAllowed(moduleName):
raise InsecureJelly("Attempted to unjelly module named %s" % repr(moduleName))
mod = __import__(moduleName, {}, {},"x")
return mod
def _unjelly_class(self, rest):
clist = string.split(rest[0], '.')
modName = string.join(clist[:-1], '.')
if not self.taster.isModuleAllowed(modName):
raise InsecureJelly("module %s not allowed" % modName)
klaus = namedObject(rest[0])
if type(klaus) is not types.ClassType:
raise InsecureJelly("class %s unjellied to something that isn't a class: %s" % (repr(rest[0]), repr(klaus)))
if not self.taster.isClassAllowed(klaus):
raise InsecureJelly("class not allowed: %s" % qual(klaus))
return klaus
def _unjelly_function(self, rest):
modSplit = string.split(rest[0], '.')
modName = string.join(modSplit[:-1], '.')
if not self.taster.isModuleAllowed(modName):
raise InsecureJelly("Module not allowed: %s"% modName)
# XXX do I need an isFunctionAllowed?
function = namedObject(rest[0])
return function
def _unjelly_persistent(self, rest):
if self.persistentLoad:
pload = self.persistentLoad(rest[0], self)
return pload
else:
return Unpersistable("persistent callback not found")
def _unjelly_instance(self, rest):
clz = self.unjelly(rest[0])
if type(clz) is not types.ClassType:
raise InsecureJelly("Instance found with non-class class.")
if hasattr(clz, "__setstate__"):
inst = _newInstance(clz, {})
state = self.unjelly(rest[1])
inst.__setstate__(state)
else:
state = self.unjelly(rest[1])
inst = _newInstance(clz, state)
if hasattr(clz, 'postUnjelly'):
self.postCallbacks.append(inst.postUnjelly)
return inst
def _unjelly_unpersistable(self, rest):
return Unpersistable(rest[0])
def _unjelly_method(self, rest):
''' (internal) unjelly a method
'''
im_name = rest[0]
im_self = self.unjelly(rest[1])
im_class = self.unjelly(rest[2])
if type(im_class) is not types.ClassType:
raise InsecureJelly("Method found with non-class class.")
if im_class.__dict__.has_key(im_name):
if im_self is None:
im = getattr(im_class, im_name)
elif isinstance(im_self, NotKnown):
im = _InstanceMethod(im_name, im_self, im_class)
else:
im = instancemethod(im_class.__dict__[im_name],
im_self,
im_class)
else:
raise 'instance method changed'
return im
class _Dummy:
"""(Internal)
Dummy class, used for unserializing instances.
"""
class _DummyNewStyle(object):
"""(Internal)
Dummy class, used for unserializing instances of new-style classes.
"""
#### Published Interface.
class InsecureJelly(Exception):
"""
This exception will be raised when a jelly is deemed `insecure'; e.g. it
contains a type, class, or module disallowed by the specified `taster'
"""
class DummySecurityOptions:
"""DummySecurityOptions() -> insecure security options
Dummy security options -- this class will allow anything.
"""
def isModuleAllowed(self, moduleName):
"""DummySecurityOptions.isModuleAllowed(moduleName) -> boolean
returns 1 if a module by that name is allowed, 0 otherwise
"""
return 1
def isClassAllowed(self, klass):
"""DummySecurityOptions.isClassAllowed(class) -> boolean
Assumes the module has already been allowed. Returns 1 if the given
class is allowed, 0 otherwise.
"""
return 1
def isTypeAllowed(self, typeName):
"""DummySecurityOptions.isTypeAllowed(typeName) -> boolean
Returns 1 if the given type is allowed, 0 otherwise.
"""
return 1
class SecurityOptions:
"""
This will by default disallow everything, except for 'none'.
"""
basicTypes = ["dictionary", "list", "tuple",
"reference", "dereference", "unpersistable",
"persistent", "long_int", "long", "dict"]
def __init__(self):
"""SecurityOptions()
Initialize.
"""
# I don't believe any of these types can ever pose a security hazard,
# except perhaps "reference"...
self.allowedTypes = {"None": 1,
"bool": 1,
"boolean": 1,
"string": 1,
"str": 1,
"int": 1,
"float": 1,
"datetime": 1,
"time": 1,
"date": 1,
"timedelta": 1,
"NoneType": 1}
if hasattr(types, 'UnicodeType'):
self.allowedTypes['unicode'] = 1
self.allowedModules = {}
self.allowedClasses = {}
def allowBasicTypes(self):
"""SecurityOptions.allowBasicTypes()
Allow all `basic' types. (Dictionary and list. Int, string, and float are implicitly allowed.)
"""
self.allowTypes(*self.basicTypes)
def allowTypes(self, *types):
"""SecurityOptions.allowTypes(typeString): Allow a particular type, by its name.
"""
for typ in types:
if not isinstance(typ, str):
typ = qual(typ)
self.allowedTypes[typ] = 1
def allowInstancesOf(self, *classes):
"""SecurityOptions.allowInstances(klass, klass, ...): allow instances
of the specified classes
This will also allow the 'instance', 'class' (renamed 'classobj' in
Python 2.3), and 'module' types, as well as basic types.
"""
self.allowBasicTypes()
self.allowTypes("instance", "class", "classobj", "module")
for klass in classes:
self.allowTypes(qual(klass))
self.allowModules(klass.__module__)
self.allowedClasses[klass] = 1
def allowModules(self, *modules):
"""SecurityOptions.allowModules(module, module, ...): allow modules by name
This will also allow the 'module' type.
"""
for module in modules:
if type(module) == types.ModuleType:
module = module.__name__
self.allowedModules[module] = 1
def isModuleAllowed(self, moduleName):
"""SecurityOptions.isModuleAllowed(moduleName) -> boolean
returns 1 if a module by that name is allowed, 0 otherwise
"""
return self.allowedModules.has_key(moduleName)
def isClassAllowed(self, klass):
"""SecurityOptions.isClassAllowed(class) -> boolean
Assumes the module has already been allowed. Returns 1 if the given
class is allowed, 0 otherwise.
"""
return self.allowedClasses.has_key(klass)
def isTypeAllowed(self, typeName):
"""SecurityOptions.isTypeAllowed(typeName) -> boolean
Returns 1 if the given type is allowed, 0 otherwise.
"""
return (self.allowedTypes.has_key(typeName) or
'.' in typeName)
globalSecurity = SecurityOptions()
globalSecurity.allowBasicTypes()
def jelly(object, taster = DummySecurityOptions(), persistentStore=None, invoker=None):
"""Serialize to s-expression.
Returns a list which is the serialized representation of an object. An
optional 'taster' argument takes a SecurityOptions and will mark any
insecure objects as unpersistable rather than serializing them.
"""
return _Jellier(taster, persistentStore, invoker).jelly(object)
def unjelly(sexp, taster = DummySecurityOptions(), persistentLoad=None, invoker=None):
"""Unserialize from s-expression.
Takes an list that was the result from a call to jelly() and unserializes
an arbitrary object from it. The optional 'taster' argument, an instance
of SecurityOptions, will cause an InsecureJelly exception to be raised if a
disallowed type, module, or class attempted to unserialize.
"""
return _Unjellier(taster, persistentLoad, invoker).unjellyFull(sexp) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/spread/jelly.py | jelly.py |
__version__ = "$Revision: 1.32 $"[11:-2]
# NOTE: this module should NOT import pb; it is supposed to be a module which
# abstractly defines remotely accessible types. Many of these types expect to
# be serialized by Jelly, but they ought to be accessible through other
# mechanisms (like XMLRPC)
# system imports
import sys
from zope.interface import implements, Interface
# twisted imports
from twisted.python import log, reflect
# sibling imports
from jelly import setUnjellyableForClass, setUnjellyableForClassTree, setUnjellyableFactoryForClass, unjellyableRegistry
from jelly import Jellyable, Unjellyable, _Dummy, _DummyNewStyle
from jelly import setInstanceState, getInstanceState
# compatibility
setCopierForClass = setUnjellyableForClass
setCopierForClassTree = setUnjellyableForClassTree
setFactoryForClass = setUnjellyableFactoryForClass
copyTags = unjellyableRegistry
copy_atom = "copy"
cache_atom = "cache"
cached_atom = "cached"
remote_atom = "remote"
class NoSuchMethod(AttributeError):
"""Raised if there is no such remote method"""
class IPBRoot(Interface):
"""Factory for root Referenceable objects for PB servers."""
def rootObject(broker):
"""Return root Referenceable for broker."""
class Serializable(Jellyable):
"""An object that can be passed remotely.
I am a style of object which can be serialized by Perspective
Broker. Objects which wish to be referenceable or copied remotely
have to subclass Serializable. However, clients of Perspective
Broker will probably not want to directly subclass Serializable; the
Flavors of transferable objects are listed below.
What it means to be \"Serializable\" is that an object can be
passed to or returned from a remote method. Certain basic types
(dictionaries, lists, tuples, numbers, strings) are serializable by
default; however, classes need to choose a specific serialization
style: L{Referenceable}, L{Viewable}, L{Copyable} or L{Cacheable}.
You may also pass C{[lists, dictionaries, tuples]} of L{Serializable}
instances to or return them from remote methods, as many levels deep
as you like.
"""
def processUniqueID(self):
"""Return an ID which uniquely represents this object for this process.
By default, this uses the 'id' builtin, but can be overridden to
indicate that two values are identity-equivalent (such as proxies
for the same object).
"""
return id(self)
class Referenceable(Serializable):
perspective = None
"""I am an object sent remotely as a direct reference.
When one of my subclasses is sent as an argument to or returned
from a remote method call, I will be serialized by default as a
direct reference.
This means that the peer will be able to call methods on me;
a method call xxx() from my peer will be resolved to methods
of the name remote_xxx.
"""
def remoteMessageReceived(self, broker, message, args, kw):
"""A remote message has been received. Dispatch it appropriately.
The default implementation is to dispatch to a method called
'remote_messagename' and call it with the same arguments.
"""
args = broker.unserialize(args)
kw = broker.unserialize(kw)
method = getattr(self, "remote_%s" % message, None)
if method is None:
raise NoSuchMethod("No such method: remote_%s" % (message,))
try:
state = method(*args, **kw)
except TypeError:
log.msg("%s didn't accept %s and %s" % (method, args, kw))
raise
return broker.serialize(state, self.perspective)
def jellyFor(self, jellier):
"""(internal)
Return a tuple which will be used as the s-expression to
serialize this to a peer.
"""
return "remote", jellier.invoker.registerReference(self)
class Root(Referenceable):
"""I provide a root object to L{pb.Broker}s for a L{pb.BrokerFactory}.
When a L{pb.BrokerFactory} produces a L{pb.Broker}, it supplies that
L{pb.Broker} with an object named \"root\". That object is obtained
by calling my rootObject method.
See also: L{pb.getObjectAt}
"""
implements(IPBRoot)
def rootObject(self, broker):
"""A L{pb.BrokerFactory} is requesting to publish me as a root object.
When a L{pb.BrokerFactory} is sending me as the root object, this
method will be invoked to allow per-broker versions of an
object. By default I return myself.
"""
return self
class ViewPoint(Referenceable):
"""
I act as an indirect reference to an object accessed through a
L{pb.Perspective}.
Simply put, I combine an object with a perspective so that when a
peer calls methods on the object I refer to, the method will be
invoked with that perspective as a first argument, so that it can
know who is calling it.
While L{Viewable} objects will be converted to ViewPoints by default
when they are returned from or sent as arguments to a remote
method, any object may be manually proxied as well. (XXX: Now that
this class is no longer named C{Proxy}, this is the only occourance
of the term 'proxied' in this docstring, and may be unclear.)
This can be useful when dealing with L{pb.Perspective}s, L{Copyable}s,
and L{Cacheable}s. It is legal to implement a method as such on
a perspective::
| def perspective_getViewPointForOther(self, name):
| defr = self.service.getPerspectiveRequest(name)
| defr.addCallbacks(lambda x, self=self: ViewPoint(self, x), log.msg)
| return defr
This will allow you to have references to Perspective objects in two
different ways. One is through the initial 'attach' call -- each
peer will have a L{pb.RemoteReference} to their perspective directly. The
other is through this method; each peer can get a L{pb.RemoteReference} to
all other perspectives in the service; but that L{pb.RemoteReference} will
be to a L{ViewPoint}, not directly to the object.
The practical offshoot of this is that you can implement 2 varieties
of remotely callable methods on this Perspective; view_xxx and
C{perspective_xxx}. C{view_xxx} methods will follow the rules for
ViewPoint methods (see ViewPoint.L{remoteMessageReceived}), and
C{perspective_xxx} methods will follow the rules for Perspective
methods.
"""
def __init__(self, perspective, object):
"""Initialize me with a Perspective and an Object.
"""
self.perspective = perspective
self.object = object
def processUniqueID(self):
"""Return an ID unique to a proxy for this perspective+object combination.
"""
return (id(self.perspective), id(self.object))
def remoteMessageReceived(self, broker, message, args, kw):
"""A remote message has been received. Dispatch it appropriately.
The default implementation is to dispatch to a method called
'C{view_messagename}' to my Object and call it on my object with
the same arguments, modified by inserting my Perspective as
the first argument.
"""
args = broker.unserialize(args, self.perspective)
kw = broker.unserialize(kw, self.perspective)
method = getattr(self.object, "view_%s" % message)
try:
state = apply(method, (self.perspective,)+args, kw)
except TypeError:
log.msg("%s didn't accept %s and %s" % (method, args, kw))
raise
rv = broker.serialize(state, self.perspective, method, args, kw)
return rv
class Viewable(Serializable):
"""I will be converted to a L{ViewPoint} when passed to or returned from a remote method.
The beginning of a peer's interaction with a PB Service is always
through a perspective. However, if a C{perspective_xxx} method returns
a Viewable, it will be serialized to the peer as a response to that
method.
"""
def jellyFor(self, jellier):
"""Serialize a L{ViewPoint} for me and the perspective of the given broker.
"""
return ViewPoint(jellier.invoker.serializingPerspective, self).jellyFor(jellier)
class Copyable(Serializable):
"""Subclass me to get copied each time you are returned from or passed to a remote method.
When I am returned from or passed to a remote method call, I will be
converted into data via a set of callbacks (see my methods for more
info). That data will then be serialized using Jelly, and sent to
the peer.
The peer will then look up the type to represent this with; see
L{RemoteCopy} for details.
"""
def getStateToCopy(self):
"""Gather state to send when I am serialized for a peer.
I will default to returning self.__dict__. Override this to
customize this behavior.
"""
return self.__dict__
def getStateToCopyFor(self, perspective):
"""
Gather state to send when I am serialized for a particular
perspective.
I will default to calling L{getStateToCopy}. Override this to
customize this behavior.
"""
return self.getStateToCopy()
def getTypeToCopy(self):
"""Determine what type tag to send for me.
By default, send the string representation of my class
(package.module.Class); normally this is adequate, but
you may override this to change it.
"""
return reflect.qual(self.__class__)
def getTypeToCopyFor(self, perspective):
"""Determine what type tag to send for me.
By default, defer to self.L{getTypeToCopy}() normally this is
adequate, but you may override this to change it.
"""
return self.getTypeToCopy()
def jellyFor(self, jellier):
"""Assemble type tag and state to copy for this broker.
This will call L{getTypeToCopyFor} and L{getStateToCopy}, and
return an appropriate s-expression to represent me.
"""
if jellier.invoker is None:
return getInstanceState(self, jellier)
p = jellier.invoker.serializingPerspective
t = self.getTypeToCopyFor(p)
state = self.getStateToCopyFor(p)
sxp = jellier.prepare(self)
sxp.extend([t, jellier.jelly(state)])
return jellier.preserve(self, sxp)
class Cacheable(Copyable):
"""A cached instance.
This means that it's copied; but there is some logic to make sure
that it's only copied once. Additionally, when state is retrieved,
it is passed a "proto-reference" to the state as it will exist on
the client.
XXX: The documentation for this class needs work, but it's the most
complex part of PB and it is inherently difficult to explain.
"""
def getStateToCacheAndObserveFor(self, perspective, observer):
"""
Get state to cache on the client and client-cache reference
to observe locally.
This is similiar to getStateToCopyFor, but it additionally
passes in a reference to the client-side RemoteCache instance
that will be created when it is unserialized. This allows
Cacheable instances to keep their RemoteCaches up to date when
they change, such that no changes can occur between the point
at which the state is initially copied and the client receives
it that are not propogated.
"""
return self.getStateToCopyFor(perspective)
def jellyFor(self, jellier):
"""Return an appropriate tuple to serialize me.
Depending on whether this broker has cached me or not, this may
return either a full state or a reference to an existing cache.
"""
if jellier.invoker is None:
return getInstanceState(self, jellier)
luid = jellier.invoker.cachedRemotelyAs(self, 1)
if luid is None:
luid = jellier.invoker.cacheRemotely(self)
p = jellier.invoker.serializingPerspective
type_ = self.getTypeToCopyFor(p)
observer = RemoteCacheObserver(jellier.invoker, self, p)
state = self.getStateToCacheAndObserveFor(p, observer)
l = jellier.prepare(self)
jstate = jellier.jelly(state)
l.extend([type_, luid, jstate])
return jellier.preserve(self, l)
else:
return cached_atom, luid
def stoppedObserving(self, perspective, observer):
"""This method is called when a client has stopped observing me.
The 'observer' argument is the same as that passed in to
getStateToCacheAndObserveFor.
"""
class RemoteCopy(Unjellyable):
"""I am a remote copy of a Copyable object.
When the state from a L{Copyable} object is received, an instance will
be created based on the copy tags table (see setUnjellyableForClass) and
sent the L{setCopyableState} message. I provide a reasonable default
implementation of that message; subclass me if you wish to serve as
a copier for remote data.
NOTE: copiers are invoked with no arguments. Do not implement a
constructor which requires args in a subclass of L{RemoteCopy}!
"""
def setCopyableState(self, state):
"""I will be invoked with the state to copy locally.
'state' is the data returned from the remote object's
'getStateToCopyFor' method, which will often be the remote
object's dictionary (or a filtered approximation of it depending
on my peer's perspective).
"""
self.__dict__ = state
def unjellyFor(self, unjellier, jellyList):
if unjellier.invoker is None:
return setInstanceState(self, unjellier, jellyList)
self.setCopyableState(unjellier.unjelly(jellyList[1]))
return self
class RemoteCache(RemoteCopy, Serializable):
"""A cache is a local representation of a remote L{Cacheable} object.
This represents the last known state of this object. It may
also have methods invoked on it -- in order to update caches,
the cached class generates a L{pb.RemoteReference} to this object as
it is originally sent.
Much like copy, I will be invoked with no arguments. Do not
implement a constructor that requires arguments in one of my
subclasses.
"""
def remoteMessageReceived(self, broker, message, args, kw):
"""A remote message has been received. Dispatch it appropriately.
The default implementation is to dispatch to a method called
'C{observe_messagename}' and call it on my with the same arguments.
"""
args = broker.unserialize(args)
kw = broker.unserialize(kw)
method = getattr(self, "observe_%s" % message)
try:
state = apply(method, args, kw)
except TypeError:
log.msg("%s didn't accept %s and %s" % (method, args, kw))
raise
return broker.serialize(state, None, method, args, kw)
def jellyFor(self, jellier):
"""serialize me (only for the broker I'm for) as the original cached reference
"""
if jellier.invoker is None:
return getInstanceState(self, jellier)
assert jellier.invoker is self.broker, "You cannot exchange cached proxies between brokers."
return 'lcache', self.luid
def unjellyFor(self, unjellier, jellyList):
if unjellier.invoker is None:
return setInstanceState(self, unjellier, jellyList)
self.broker = unjellier.invoker
self.luid = jellyList[1]
if isinstance(self.__class__, type): #new-style class
cProxy = _DummyNewStyle()
else:
cProxy = _Dummy()
cProxy.__class__ = self.__class__
cProxy.__dict__ = self.__dict__
# XXX questionable whether this was a good design idea...
init = getattr(cProxy, "__init__", None)
if init:
init()
unjellier.invoker.cacheLocally(jellyList[1], self)
cProxy.setCopyableState(unjellier.unjelly(jellyList[2]))
# Might have changed due to setCopyableState method; we'll assume that
# it's bad form to do so afterwards.
self.__dict__ = cProxy.__dict__
# chomp, chomp -- some existing code uses "self.__dict__ =", some uses
# "__dict__.update". This is here in order to handle both cases.
self.broker = unjellier.invoker
self.luid = jellyList[1]
return cProxy
## def __really_del__(self):
## """Final finalization call, made after all remote references have been lost.
## """
def __cmp__(self, other):
"""Compare me [to another RemoteCache.
"""
if isinstance(other, self.__class__):
return cmp(id(self.__dict__), id(other.__dict__))
else:
return cmp(id(self.__dict__), other)
def __hash__(self):
"""Hash me.
"""
return int(id(self.__dict__) % sys.maxint)
broker = None
luid = None
def __del__(self):
"""Do distributed reference counting on finalize.
"""
try:
# log.msg( ' --- decache: %s %s' % (self, self.luid) )
if self.broker:
self.broker.decCacheRef(self.luid)
except:
log.deferr()
def unjellyCached(unjellier, unjellyList):
luid = unjellyList[1]
cNotProxy = unjellier.invoker.cachedLocallyAs(luid)
cProxy = _Dummy()
cProxy.__class__ = cNotProxy.__class__
cProxy.__dict__ = cNotProxy.__dict__
return cProxy
setUnjellyableForClass("cached", unjellyCached)
def unjellyLCache(unjellier, unjellyList):
luid = unjellyList[1]
obj = unjellier.invoker.remotelyCachedForLUID(luid)
return obj
setUnjellyableForClass("lcache", unjellyLCache)
def unjellyLocal(unjellier, unjellyList):
obj = unjellier.invoker.localObjectForID(unjellyList[1])
return obj
setUnjellyableForClass("local", unjellyLocal)
class RemoteCacheMethod:
"""A method on a reference to a L{RemoteCache}.
"""
def __init__(self, name, broker, cached, perspective):
"""(internal) initialize.
"""
self.name = name
self.broker = broker
self.perspective = perspective
self.cached = cached
def __cmp__(self, other):
return cmp((self.name, self.broker, self.perspective, self.cached), other)
def __hash__(self):
return hash((self.name, self.broker, self.perspective, self.cached))
def __call__(self, *args, **kw):
"""(internal) action method.
"""
cacheID = self.broker.cachedRemotelyAs(self.cached)
if cacheID is None:
from pb import ProtocolError
raise ProtocolError("You can't call a cached method when the object hasn't been given to the peer yet.")
return self.broker._sendMessage('cache', self.perspective, cacheID, self.name, args, kw)
class RemoteCacheObserver:
"""I am a reverse-reference to the peer's L{RemoteCache}.
I am generated automatically when a cache is serialized. I
represent a reference to the client's L{RemoteCache} object that
will represent a particular L{Cacheable}; I am the additional
object passed to getStateToCacheAndObserveFor.
"""
def __init__(self, broker, cached, perspective):
"""(internal) Initialize me.
@param broker: a L{pb.Broker} instance.
@param cached: a L{Cacheable} instance that this L{RemoteCacheObserver}
corresponds to.
@param perspective: a reference to the perspective who is observing this.
"""
self.broker = broker
self.cached = cached
self.perspective = perspective
def __repr__(self):
return "<RemoteCacheObserver(%s, %s, %s) at %s>" % (
self.broker, self.cached, self.perspective, id(self))
def __hash__(self):
"""Generate a hash unique to all L{RemoteCacheObserver}s for this broker/perspective/cached triplet
"""
return ( (hash(self.broker) % 2**10)
+ (hash(self.perspective) % 2**10)
+ (hash(self.cached) % 2**10))
def __cmp__(self, other):
"""Compare me to another L{RemoteCacheObserver}.
"""
return cmp((self.broker, self.perspective, self.cached), other)
def callRemote(self, _name, *args, **kw):
"""(internal) action method.
"""
cacheID = self.broker.cachedRemotelyAs(self.cached)
if cacheID is None:
from pb import ProtocolError
raise ProtocolError("You can't call a cached method when the "
"object hasn't been given to the peer yet.")
return self.broker._sendMessage('cache', self.perspective, cacheID,
_name, args, kw)
def remoteMethod(self, key):
"""Get a L{pb.RemoteMethod} for this key.
"""
return RemoteCacheMethod(key, self.broker, self.cached, self.perspective) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/spread/flavors.py | flavors.py |
# Twisted imports
from twisted.internet import defer
# sibling imports
import jelly
import banana
import flavors
# System Imports
import time
class Publishable(flavors.Cacheable):
"""An object whose cached state persists across sessions.
"""
def __init__(self, publishedID):
self.republish()
self.publishedID = publishedID
def republish(self):
"""Set the timestamp to current and (TODO) update all observers.
"""
self.timestamp = time.time()
def view_getStateToPublish(self, perspective):
'(internal)'
return self.getStateToPublishFor(perspective)
def getStateToPublishFor(self, perspective):
"""Implement me to special-case your state for a perspective.
"""
return self.getStateToPublish()
def getStateToPublish(self):
"""Implement me to return state to copy as part of the publish phase.
"""
raise NotImplementedError("%s.getStateToPublishFor" % self.__class__)
def getStateToCacheAndObserveFor(self, perspective, observer):
"""Get all necessary metadata to keep a clientside cache.
"""
if perspective:
pname = perspective.perspectiveName
sname = perspective.getService().serviceName
else:
pname = "None"
sname = "None"
return {"remote": flavors.ViewPoint(perspective, self),
"publishedID": self.publishedID,
"perspective": pname,
"service": sname,
"timestamp": self.timestamp}
class RemotePublished(flavors.RemoteCache):
"""The local representation of remote Publishable object.
"""
isActivated = 0
_wasCleanWhenLoaded = 0
def getFileName(self, ext='pub'):
return ("%s-%s-%s.%s" %
(self.service, self.perspective, str(self.publishedID), ext))
def setCopyableState(self, state):
self.__dict__.update(state)
self._activationListeners = []
try:
data = open(self.getFileName()).read()
except IOError:
recent = 0
else:
newself = jelly.unjelly(banana.decode(data))
recent = (newself.timestamp == self.timestamp)
if recent:
self._cbGotUpdate(newself.__dict__)
self._wasCleanWhenLoaded = 1
else:
self.remote.callRemote('getStateToPublish').addCallbacks(self._cbGotUpdate)
def __getstate__(self):
other = self.__dict__.copy()
# Remove PB-specific attributes
del other['broker']
del other['remote']
del other['luid']
# remove my own runtime-tracking stuff
del other['_activationListeners']
del other['isActivated']
return other
def _cbGotUpdate(self, newState):
self.__dict__.update(newState)
self.isActivated = 1
# send out notifications
for listener in self._activationListeners:
listener(self)
self._activationListeners = []
self.activated()
open(self.getFileName(), "wb").write(banana.encode(jelly.jelly(self)))
def activated(self):
"""Implement this method if you want to be notified when your
publishable subclass is activated.
"""
def callWhenActivated(self, callback):
"""Externally register for notification when this publishable has received all relevant data.
"""
if self.isActivated:
callback(self)
else:
self._activationListeners.append(callback)
def whenReady(d):
"""
Wrap a deferred returned from a pb method in another deferred that
expects a RemotePublished as a result. This will allow you to wait until
the result is really available.
Idiomatic usage would look like::
publish.whenReady(serverObject.getMeAPublishable()).addCallback(lookAtThePublishable)
"""
d2 = defer.Deferred()
d.addCallbacks(_pubReady, d2.errback,
callbackArgs=(d2,))
return d2
def _pubReady(result, d2):
'(internal)'
result.callWhenActivated(d2.callback) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/spread/publish.py | publish.py |
from __future__ import nested_scopes
import gtk
from twisted import copyright
from twisted.internet import defer
from twisted.python import failure, log, util
from twisted.spread import pb
from twisted.cred.credentials import UsernamePassword
from twisted.internet import error as netError
def login(client=None, **defaults):
"""
@param host:
@param port:
@param identityName:
@param password:
@param serviceName:
@param perspectiveName:
@returntype: Deferred RemoteReference of Perspective
"""
d = defer.Deferred()
LoginDialog(client, d, defaults)
return d
class GladeKeeper:
"""
@cvar gladefile: The file in which the glade GUI definition is kept.
@type gladefile: str
@cvar _widgets: Widgets that should be attached to me as attributes.
@type _widgets: list of strings
"""
gladefile = None
_widgets = ()
def __init__(self):
from gtk import glade
self.glade = glade.XML(self.gladefile)
# mold can go away when we get a newer pygtk (post 1.99.14)
mold = {}
for k in dir(self):
mold[k] = getattr(self, k)
self.glade.signal_autoconnect(mold)
self._setWidgets()
def _setWidgets(self):
get_widget = self.glade.get_widget
for widgetName in self._widgets:
setattr(self, "_" + widgetName, get_widget(widgetName))
class LoginDialog(GladeKeeper):
# IdentityConnector host port identityName password
# requestLogin -> identityWrapper or login failure
# requestService serviceName perspectiveName client
# window killed
# cancel button pressed
# login button activated
fields = ['host','port','identityName','password',
'perspectiveName']
_widgets = ("hostEntry", "portEntry", "identityNameEntry", "passwordEntry",
"perspectiveNameEntry", "statusBar",
"loginDialog")
_advancedControls = ['perspectiveLabel', 'perspectiveNameEntry',
'protocolLabel', 'versionLabel']
gladefile = util.sibpath(__file__, "login2.glade")
def __init__(self, client, deferred, defaults):
self.client = client
self.deferredResult = deferred
GladeKeeper.__init__(self)
self.setDefaults(defaults)
self._loginDialog.show()
def setDefaults(self, defaults):
if not defaults.has_key('port'):
defaults['port'] = str(pb.portno)
elif isinstance(defaults['port'], (int, long)):
defaults['port'] = str(defaults['port'])
for k, v in defaults.iteritems():
if k in self.fields:
widget = getattr(self, "_%sEntry" % (k,))
widget.set_text(v)
def _setWidgets(self):
GladeKeeper._setWidgets(self)
self._statusContext = self._statusBar.get_context_id("Login dialog.")
get_widget = self.glade.get_widget
get_widget("versionLabel").set_text(copyright.longversion)
get_widget("protocolLabel").set_text("Protocol PB-%s" %
(pb.Broker.version,))
def _on_loginDialog_response(self, widget, response):
handlers = {gtk.RESPONSE_NONE: self._windowClosed,
gtk.RESPONSE_DELETE_EVENT: self._windowClosed,
gtk.RESPONSE_OK: self._doLogin,
gtk.RESPONSE_CANCEL: self._cancelled}
handler = handlers.get(response)
if handler is not None:
handler()
else:
log.msg("Unexpected dialog response %r from %s" % (response,
widget))
def _on_loginDialog_close(self, widget, userdata=None):
self._windowClosed()
def _on_loginDialog_destroy_event(self, widget, userdata=None):
self._windowClosed()
def _cancelled(self):
if not self.deferredResult.called:
self.deferredResult.errback(netError.UserError("User hit Cancel."))
self._loginDialog.destroy()
def _windowClosed(self, reason=None):
if not self.deferredResult.called:
self.deferredResult.errback(netError.UserError("Window closed."))
def _doLogin(self):
idParams = {}
idParams['host'] = self._hostEntry.get_text()
idParams['port'] = self._portEntry.get_text()
idParams['identityName'] = self._identityNameEntry.get_text()
idParams['password'] = self._passwordEntry.get_text()
try:
idParams['port'] = int(idParams['port'])
except ValueError:
pass
f = pb.PBClientFactory()
from twisted.internet import reactor
reactor.connectTCP(idParams['host'], idParams['port'], f)
creds = UsernamePassword(idParams['identityName'], idParams['password'])
f.login(creds, self.client
).addCallbacks(self._cbGotPerspective, self._ebFailedLogin
).setTimeout(30
)
self.statusMsg("Contacting server...")
# serviceName = self._serviceNameEntry.get_text()
# perspectiveName = self._perspectiveNameEntry.get_text()
# if not perspectiveName:
# perspectiveName = idParams['identityName']
# d = _identityConnector.requestService(serviceName, perspectiveName,
# self.client)
# d.addCallbacks(self._cbGotPerspective, self._ebFailedLogin)
# setCursor to waiting
def _cbGotPerspective(self, perspective):
self.statusMsg("Connected to server.")
self.deferredResult.callback(perspective)
# clear waiting cursor
self._loginDialog.destroy()
def _ebFailedLogin(self, reason):
if isinstance(reason, failure.Failure):
reason = reason.value
self.statusMsg(reason)
if isinstance(reason, (unicode, str)):
text = reason
else:
text = unicode(reason)
msg = gtk.MessageDialog(self._loginDialog,
gtk.DIALOG_DESTROY_WITH_PARENT,
gtk.MESSAGE_ERROR,
gtk.BUTTONS_CLOSE,
text)
msg.show_all()
msg.connect("response", lambda *a: msg.destroy())
# hostname not found
# host unreachable
# connection refused
# authentication failed
# no such service
# no such perspective
# internal server error
def _on_advancedButton_toggled(self, widget, userdata=None):
active = widget.get_active()
if active:
op = "show"
else:
op = "hide"
for widgetName in self._advancedControls:
widget = self.glade.get_widget(widgetName)
getattr(widget, op)()
def statusMsg(self, text):
if not isinstance(text, (unicode, str)):
text = unicode(text)
return self._statusBar.push(self._statusContext, text) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/spread/ui/gtk2util.py | gtk2util.py |
import os
from Tkinter import *
class Node:
def __init__(self):
"""
Do whatever you want here.
"""
self.item=None
def getName(self):
"""
Return the name of this node in the tree.
"""
pass
def isExpandable(self):
"""
Return true if this node is expandable.
"""
return len(self.getSubNodes())>0
def getSubNodes(self):
"""
Return the sub nodes of this node.
"""
return []
def gotDoubleClick(self):
"""
Called when we are double clicked.
"""
pass
def updateMe(self):
"""
Call me when something about me changes, so that my representation
changes.
"""
if self.item:
self.item.update()
class FileNode(Node):
def __init__(self,name):
Node.__init__(self)
self.name=name
def getName(self):
return os.path.basename(self.name)
def isExpandable(self):
return os.path.isdir(self.name)
def getSubNodes(self):
names=map(lambda x,n=self.name:os.path.join(n,x),os.listdir(self.name))
return map(FileNode,names)
class TreeItem:
def __init__(self,widget,parent,node):
self.widget=widget
self.node=node
node.item=self
if self.node.isExpandable():
self.expand=0
else:
self.expand=None
self.parent=parent
if parent:
self.level=self.parent.level+1
else:
self.level=0
self.first=0 # gets set in Tree.expand()
self.subitems=[]
def __del__(self):
del self.node
del self.widget
def __repr__(self):
return "<Item for Node %s at level %s>"%(self.node.getName(),self.level)
def render(self):
"""
Override in a subclass.
"""
raise NotImplementedError
def update(self):
self.widget.update(self)
class ListboxTreeItem(TreeItem):
def render(self):
start=self.level*"| "
if self.expand==None and not self.first:
start=start+"|"
elif self.expand==0:
start=start+"L"
elif self.expand==1:
start=start+"+"
else:
start=start+"\\"
r=[start+"- "+self.node.getName()]
if self.expand:
for i in self.subitems:
r.extend(i.render())
return r
class ListboxTree:
def __init__(self,parent=None,**options):
self.box=apply(Listbox,[parent],options)
self.box.bind("<Double-1>",self.flip)
self.roots=[]
self.items=[]
def pack(self,*args,**kw):
"""
for packing.
"""
apply(self.box.pack,args,kw)
def grid(self,*args,**kw):
"""
for gridding.
"""
apply(self.box.grid,args,kw)
def yview(self,*args,**kw):
"""
for scrolling.
"""
apply(self.box.yview,args,kw)
def addRoot(self,node):
r=ListboxTreeItem(self,None,node)
self.roots.append(r)
self.items.append(r)
self.box.insert(END,r.render()[0])
return r
def curselection(self):
c=self.box.curselection()
if not c: return
return self.items[int(c[0])]
def flip(self,*foo):
if not self.box.curselection(): return
item=self.items[int(self.box.curselection()[0])]
if item.expand==None: return
if not item.expand:
self.expand(item)
else:
self.close(item)
item.node.gotDoubleClick()
def expand(self,item):
if item.expand or item.expand==None: return
item.expand=1
item.subitems=map(lambda x,i=item,s=self:ListboxTreeItem(s,i,x),item.node.getSubNodes())
if item.subitems:
item.subitems[0].first=1
i=self.items.index(item)
self.items,after=self.items[:i+1],self.items[i+1:]
self.items=self.items+item.subitems+after
c=self.items.index(item)
self.box.delete(c)
r=item.render()
for i in r:
self.box.insert(c,i)
c=c+1
def close(self,item):
if not item.expand: return
item.expand=0
length=len(item.subitems)
for i in item.subitems:
self.close(i)
c=self.items.index(item)
del self.items[c+1:c+1+length]
for i in range(length+1):
self.box.delete(c)
self.box.insert(c,item.render()[0])
def remove(self,item):
if item.expand:
self.close(item)
c=self.items.index(item)
del self.items[c]
if item.parent:
item.parent.subitems.remove(item)
self.box.delete(c)
def update(self,item):
if item.expand==None:
c=self.items.index(item)
self.box.delete(c)
self.box.insert(c,item.render()[0])
elif item.expand:
self.close(item)
self.expand(item)
if __name__=="__main__":
tk=Tk()
s=Scrollbar()
t=ListboxTree(tk,yscrollcommand=s.set)
t.pack(side=LEFT,fill=BOTH)
s.config(command=t.yview)
s.pack(side=RIGHT,fill=Y)
t.addRoot(FileNode("C:/"))
#mainloop() | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/spread/ui/tktree.py | tktree.py |
from Tkinter import *
from tkSimpleDialog import _QueryString
from tkFileDialog import _Dialog
from twisted.spread import pb
from twisted.internet import reactor
from twisted import copyright
import string
#normalFont = Font("-adobe-courier-medium-r-normal-*-*-120-*-*-m-*-iso8859-1")
#boldFont = Font("-adobe-courier-bold-r-normal-*-*-120-*-*-m-*-iso8859-1")
#errorFont = Font("-adobe-courier-medium-o-normal-*-*-120-*-*-m-*-iso8859-1")
class _QueryPassword(_QueryString):
def body(self, master):
w = Label(master, text=self.prompt, justify=LEFT)
w.grid(row=0, padx=5, sticky=W)
self.entry = Entry(master, name="entry",show="*")
self.entry.grid(row=1, padx=5, sticky=W+E)
if self.initialvalue:
self.entry.insert(0, self.initialvalue)
self.entry.select_range(0, END)
return self.entry
def askpassword(title, prompt, **kw):
'''get a password from the user
@param title: the dialog title
@param prompt: the label text
@param **kw: see L{SimpleDialog} class
@returns: a string
'''
d = apply(_QueryPassword, (title, prompt), kw)
return d.result
def grid_setexpand(widget):
cols,rows=widget.grid_size()
for i in range(cols):
widget.columnconfigure(i,weight=1)
for i in range(rows):
widget.rowconfigure(i,weight=1)
class CList(Frame):
def __init__(self,parent,labels,disablesorting=0,**kw):
Frame.__init__(self,parent)
self.labels=labels
self.lists=[]
self.disablesorting=disablesorting
kw["exportselection"]=0
for i in range(len(labels)):
b=Button(self,text=labels[i],anchor=W,height=1,pady=0)
b.config(command=lambda s=self,i=i:s.setSort(i))
b.grid(column=i,row=0,sticky=N+E+W)
box=apply(Listbox,(self,),kw)
box.grid(column=i,row=1,sticky=N+E+S+W)
self.lists.append(box)
grid_setexpand(self)
self.rowconfigure(0,weight=0)
self._callall("bind",'<Button-1>',self.Button1)
self._callall("bind",'<B1-Motion>',self.Button1)
self.bind('<Up>',self.UpKey)
self.bind('<Down>',self.DownKey)
self.sort=None
def _callall(self,funcname,*args,**kw):
rets=[]
for l in self.lists:
func=getattr(l,funcname)
ret=apply(func,args,kw)
if ret!=None: rets.append(ret)
if rets: return rets
def Button1(self,e):
index=self.nearest(e.y)
self.select_clear(0,END)
self.select_set(index)
self.activate(index)
return "break"
def UpKey(self,e):
index=self.index(ACTIVE)
if index:
self.select_clear(0,END)
self.select_set(index-1)
return "break"
def DownKey(self,e):
index=self.index(ACTIVE)
if index!=self.size()-1:
self.select_clear(0,END)
self.select_set(index+1)
return "break"
def setSort(self,index):
if self.sort==None:
self.sort=[index,1]
elif self.sort[0]==index:
self.sort[1]=-self.sort[1]
else:
self.sort=[index,1]
self._sort()
def _sort(self):
if self.disablesorting:
return
if self.sort==None:
return
ind,direc=self.sort
li=list(self.get(0,END))
li.sort(lambda x,y,i=ind,d=direc:d*cmp(x[i],y[i]))
self.delete(0,END)
for l in li:
self._insert(END,l)
def activate(self,index):
self._callall("activate",index)
# def bbox(self,index):
# return self._callall("bbox",index)
def curselection(self):
return self.lists[0].curselection()
def delete(self,*args):
apply(self._callall,("delete",)+args)
def get(self,*args):
bad=apply(self._callall,("get",)+args)
if len(args)==1:
return bad
ret=[]
for i in range(len(bad[0])):
r=[]
for j in range(len(bad)):
r.append(bad[j][i])
ret.append(r)
return ret
def index(self,index):
return self.lists[0].index(index)
def insert(self,index,items):
self._insert(index,items)
self._sort()
def _insert(self,index,items):
for i in range(len(items)):
self.lists[i].insert(index,items[i])
def nearest(self,y):
return self.lists[0].nearest(y)
def see(self,index):
self._callall("see",index)
def size(self):
return self.lists[0].size()
def selection_anchor(self,index):
self._callall("selection_anchor",index)
select_anchor=selection_anchor
def selection_clear(self,*args):
apply(self._callall,("selection_clear",)+args)
select_clear=selection_clear
def selection_includes(self,index):
return self.lists[0].select_includes(index)
select_includes=selection_includes
def selection_set(self,*args):
apply(self._callall,("selection_set",)+args)
select_set=selection_set
def xview(self,*args):
if not args: return self.lists[0].xview()
apply(self._callall,("xview",)+args)
def yview(self,*args):
if not args: return self.lists[0].yview()
apply(self._callall,("yview",)+args)
class ProgressBar:
def __init__(self, master=None, orientation="horizontal",
min=0, max=100, width=100, height=18,
doLabel=1, appearance="sunken",
fillColor="blue", background="gray",
labelColor="yellow", labelFont="Verdana",
labelText="", labelFormat="%d%%",
value=0, bd=2):
# preserve various values
self.master=master
self.orientation=orientation
self.min=min
self.max=max
self.width=width
self.height=height
self.doLabel=doLabel
self.fillColor=fillColor
self.labelFont= labelFont
self.labelColor=labelColor
self.background=background
self.labelText=labelText
self.labelFormat=labelFormat
self.value=value
self.frame=Frame(master, relief=appearance, bd=bd)
self.canvas=Canvas(self.frame, height=height, width=width, bd=0,
highlightthickness=0, background=background)
self.scale=self.canvas.create_rectangle(0, 0, width, height,
fill=fillColor)
self.label=self.canvas.create_text(self.canvas.winfo_reqwidth() / 2,
height / 2, text=labelText,
anchor="c", fill=labelColor,
font=self.labelFont)
self.update()
self.canvas.pack(side='top', fill='x', expand='no')
def updateProgress(self, newValue, newMax=None):
if newMax:
self.max = newMax
self.value = newValue
self.update()
def update(self):
# Trim the values to be between min and max
value=self.value
if value > self.max:
value = self.max
if value < self.min:
value = self.min
# Adjust the rectangle
if self.orientation == "horizontal":
self.canvas.coords(self.scale, 0, 0,
float(value) / self.max * self.width, self.height)
else:
self.canvas.coords(self.scale, 0,
self.height - (float(value) /
self.max*self.height),
self.width, self.height)
# Now update the colors
self.canvas.itemconfig(self.scale, fill=self.fillColor)
self.canvas.itemconfig(self.label, fill=self.labelColor)
# And update the label
if self.doLabel:
if value:
if value >= 0:
pvalue = int((float(value) / float(self.max)) *
100.0)
else:
pvalue = 0
self.canvas.itemconfig(self.label, text=self.labelFormat
% pvalue)
else:
self.canvas.itemconfig(self.label, text='')
else:
self.canvas.itemconfig(self.label, text=self.labelFormat %
self.labelText)
self.canvas.update_idletasks()
class DirectoryBrowser(_Dialog):
command = "tk_chooseDirectory"
def askdirectory(**options):
"Ask for a directory to save to."
return apply(DirectoryBrowser, (), options).show()
class GenericLogin(Toplevel):
def __init__(self,callback,buttons):
Toplevel.__init__(self)
self.callback=callback
Label(self,text="Twisted v%s"%copyright.version).grid(column=0,row=0,columnspan=2)
self.entries={}
row=1
for stuff in buttons:
label,value=stuff[:2]
if len(stuff)==3:
dict=stuff[2]
else: dict={}
Label(self,text=label+": ").grid(column=0,row=row)
e=apply(Entry,(self,),dict)
e.grid(column=1,row=row)
e.insert(0,value)
self.entries[label]=e
row=row+1
Button(self,text="Login",command=self.doLogin).grid(column=0,row=row)
Button(self,text="Cancel",command=self.close).grid(column=1,row=row)
self.protocol('WM_DELETE_WINDOW',self.close)
def close(self):
self.tk.quit()
self.destroy()
def doLogin(self):
values={}
for k in self.entries.keys():
values[string.lower(k)]=self.entries[k].get()
self.callback(values)
self.destroy()
class Login(Toplevel):
def __init__(self,
callback,
referenced = None,
initialUser = "guest",
initialPassword = "guest",
initialHostname = "localhost",
initialService = "",
initialPortno = pb.portno):
Toplevel.__init__(self)
version_label = Label(self,text="Twisted v%s" % copyright.version)
self.pbReferenceable = referenced
self.pbCallback = callback
# version_label.show()
self.username = Entry(self)
self.password = Entry(self,show='*')
self.hostname = Entry(self)
self.service = Entry(self)
self.port = Entry(self)
self.username.insert(0,initialUser)
self.password.insert(0,initialPassword)
self.service.insert(0,initialService)
self.hostname.insert(0,initialHostname)
self.port.insert(0,str(initialPortno))
userlbl=Label(self,text="Username:")
passlbl=Label(self,text="Password:")
servicelbl=Label(self,text="Service:")
hostlbl=Label(self,text="Hostname:")
portlbl=Label(self,text="Port #:")
self.logvar=StringVar()
self.logvar.set("Protocol PB-%s"%pb.Broker.version)
self.logstat = Label(self,textvariable=self.logvar)
self.okbutton = Button(self,text="Log In", command=self.login)
version_label.grid(column=0,row=0,columnspan=2)
z=0
for i in [[userlbl,self.username],
[passlbl,self.password],
[hostlbl,self.hostname],
[servicelbl,self.service],
[portlbl,self.port]]:
i[0].grid(column=0,row=z+1)
i[1].grid(column=1,row=z+1)
z = z+1
self.logstat.grid(column=0,row=6,columnspan=2)
self.okbutton.grid(column=0,row=7,columnspan=2)
self.protocol('WM_DELETE_WINDOW',self.tk.quit)
def loginReset(self):
self.logvar.set("Idle.")
def loginReport(self, txt):
self.logvar.set(txt)
self.after(30000, self.loginReset)
def login(self):
host = self.hostname.get()
port = self.port.get()
service = self.service.get()
try:
port = int(port)
except:
pass
user = self.username.get()
pswd = self.password.get()
pb.connect(host, port, user, pswd, service,
client=self.pbReferenceable).addCallback(self.pbCallback).addErrback(
self.couldNotConnect)
def couldNotConnect(self,f):
self.loginReport("could not connect:"+f.getErrorMessage())
if __name__=="__main__":
root=Tk()
o=CList(root,["Username","Online","Auto-Logon","Gateway"])
o.pack()
for i in range(0,16,4):
o.insert(END,[i,i+1,i+2,i+3])
mainloop() | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/spread/ui/tkutil.py | tkutil.py |
import gtk
import string
from twisted.spread import pb
from twisted import copyright
from twisted.python import reflect
from twisted.cred.credentials import UsernamePassword
normalFont = gtk.load_font("-adobe-courier-medium-r-normal-*-*-120-*-*-m-*-iso8859-1")
boldFont = gtk.load_font("-adobe-courier-bold-r-normal-*-*-120-*-*-m-*-iso8859-1")
errorFont = gtk.load_font("-adobe-courier-medium-o-normal-*-*-120-*-*-m-*-iso8859-1")
def selectAll(widget,event):
widget.select_region(0,-1)
def cbutton(name, callback):
b = gtk.GtkButton(name)
b.connect('clicked', callback)
return b
class ButtonBar:
barButtons = None
def getButtonList(self, prefix='button_', container=None):
result = []
buttons = self.barButtons or \
reflect.prefixedMethodNames(self.__class__, prefix)
for b in buttons:
bName = string.replace(b, '_', ' ')
result.append(cbutton(bName, getattr(self,prefix+b)))
if container:
map(container.add, result)
return result
def scrollify(widget):
#widget.set_word_wrap(gtk.TRUE)
scrl=gtk.GtkScrolledWindow()
scrl.add(widget)
scrl.set_policy(gtk.POLICY_NEVER, gtk.POLICY_ALWAYS)
# scrl.set_update_policy(gtk.POLICY_AUTOMATIC)
return scrl
def defocusify(widget):
widget.unset_flags(gtk.CAN_FOCUS)
class GetString(gtk.GtkWindow):
def __init__(self, im, desc):
gtk.GtkWindow.__init__(self, gtk.WINDOW_TOPLEVEL)
self.set_title(desc)
self.im = im
button = cbutton(desc, self.clicked)
self.entry = gtk.GtkEntry()
self.entry.connect('activate', self.clicked)
hb = gtk.GtkHBox()
hb.add(self.entry)
hb.add(button)
self.add(hb)
self.show_all()
def clicked(self, btn):
raise NotImplementedError
class Login(gtk.GtkWindow):
_resetTimeout = None
def __init__(self, callback,
referenceable=None,
initialUser="guest", initialPassword="guest",
initialHostname="localhost",initialPortno=str(pb.portno),
initialService="", initialPerspective=""):
gtk.GtkWindow.__init__(self,gtk.WINDOW_TOPLEVEL)
version_label = gtk.GtkLabel("Twisted v%s" % copyright.version)
self.pbReferenceable = referenceable
self.pbCallback = callback
# version_label.show()
self.username = gtk.GtkEntry()
self.password = gtk.GtkEntry()
self.service = gtk.GtkEntry()
self.perspective = gtk.GtkEntry()
self.hostname = gtk.GtkEntry()
self.port = gtk.GtkEntry()
self.password.set_visibility(gtk.FALSE)
self.username.set_text(initialUser)
self.password.set_text(initialPassword)
self.service.set_text(initialService)
self.perspective.set_text(initialPerspective)
self.hostname.set_text(initialHostname)
self.port.set_text(str(initialPortno))
userlbl=gtk.GtkLabel("Username:")
passlbl=gtk.GtkLabel("Password:")
servicelbl=gtk.GtkLabel("Service:")
perspeclbl=gtk.GtkLabel("Perspective:")
hostlbl=gtk.GtkLabel("Hostname:")
portlbl=gtk.GtkLabel("Port #:")
self.allLabels = [
userlbl, passlbl, servicelbl, perspeclbl, hostlbl, portlbl
]
self.logstat = gtk.GtkLabel("Protocol PB-%s" % pb.Broker.version)
self.okbutton = cbutton("Log In", self.login)
self.okbutton["can_default"] = 1
self.okbutton["receives_default"] = 1
okbtnbx = gtk.GtkHButtonBox()
okbtnbx.add(self.okbutton)
vbox = gtk.GtkVBox()
vbox.add(version_label)
table = gtk.GtkTable(2,6)
row=0
for label, entry in [(userlbl, self.username),
(passlbl, self.password),
(hostlbl, self.hostname),
(servicelbl, self.service),
(perspeclbl, self.perspective),
(portlbl, self.port)]:
table.attach(label, 0, 1, row, row+1)
table.attach(entry, 1, 2, row, row+1)
row = row+1
vbox.add(table)
vbox.add(self.logstat)
vbox.add(okbtnbx)
self.add(vbox)
self.username.grab_focus()
self.okbutton.grab_default()
for fld in self.username, self.password, self.hostname, self.service, self.perspective:
fld.signal_connect('activate',self.login)
fld.signal_connect('focus_in_event',selectAll)
self.signal_connect('destroy',gtk.mainquit,None)
def loginReset(self):
print 'doing login reset'
self.logstat.set_text("Idle.")
self._resetTimeout = None
return 0
def loginReport(self, txt):
print 'setting login report',repr(txt)
self.logstat.set_text(txt)
if not (self._resetTimeout is None):
gtk.timeout_remove(self._resetTimeout)
self._resetTimeout = gtk.timeout_add(59000, self.loginReset)
def login(self, btn):
host = self.hostname.get_text()
port = self.port.get_text()
service = self.service.get_text()
perspective = self.perspective.get_text()
# Maybe we're connecting to a unix socket, so don't make any
# assumptions
try:
port = int(port)
except:
pass
user = self.username.get_text()
pswd = self.password.get_text()
self.loginReport("connecting...")
# putting this off to avoid a stupid bug in gtk where it won't redraw
# if you input_add a connecting socket (!??)
self.user_tx = user
self.pswd_tx = pswd
self.host_tx = host
self.port_tx = port
self.service_tx = service
self.perspective_tx = perspective or user
afterOneTimeout(10, self.__actuallyConnect)
def __actuallyConnect(self):
from twisted.application import internet
f = pb.PBClientFactory()
internet.TCPClient(self.host_tx, self.port_tx, f)
creds = UsernamePassword(self.user_tx, self.pswd_tx)
f.login(creds, self.pbReferenceable
).addCallbacks(self.pbCallback, self.couldNotConnect
).setTimeout(30
)
def couldNotConnect(self, msg):
self.loginReport("couldn't connect: %s" % str(msg))
class _TimerOuter:
def __init__(self, timeout, cmd, args):
self.args = args
self.cmd = cmd
self.tid = gtk.timeout_add(timeout, self.doIt)
def doIt(self):
gtk.timeout_remove(self.tid)
apply(self.cmd, self.args)
def afterOneTimeout(timeout, cmd, *args):
_TimerOuter(timeout, cmd, args) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/spread/ui/gtkutil.py | gtkutil.py |
import types
NOQUOTE = 1
USEQUOTE = 2
dbTypeMap = {
"bigint": NOQUOTE,
"bool": USEQUOTE,
"boolean": USEQUOTE,
"bytea": USEQUOTE,
"date": USEQUOTE,
"int2": NOQUOTE,
"int4": NOQUOTE,
"int8": NOQUOTE,
"int": NOQUOTE,
"integer": NOQUOTE,
"float4": NOQUOTE,
"float8": NOQUOTE,
"numeric": NOQUOTE,
"real": NOQUOTE,
"smallint": NOQUOTE,
"char": USEQUOTE,
"text": USEQUOTE,
"time": USEQUOTE,
"timestamp": USEQUOTE,
"varchar": USEQUOTE
}
class DBError(Exception):
pass
### Utility functions
def getKeyColumn(rowClass, name):
lcname = name.lower()
for keyColumn, type in rowClass.rowKeyColumns:
if lcname == keyColumn.lower():
return name
return None
def safe(text):
"""Make a string safe to include in an SQL statement
"""
return text.replace("'", "''").replace("\\", "\\\\")
def quote(value, typeCode, string_escaper=safe):
"""Add quotes for text types and no quotes for integer types.
NOTE: uses Postgresql type codes.
"""
q = dbTypeMap.get(typeCode, None)
if q is None:
raise DBError("Type %s not known" % typeCode)
if value is None:
return 'null'
if q == NOQUOTE:
return str(value)
elif q == USEQUOTE:
if typeCode.startswith('bool'):
if value:
value = '1'
else:
value = '0'
if typeCode == "bytea":
l = ["'"]
for c in value:
i = ord(c)
if i == 0:
l.append("\\\\000")
elif i == 92:
l.append(c * 4)
elif 32 <= i <= 126:
l.append(c)
else:
l.append("\\%03o" % i)
l.append("'")
return "".join(l)
if not isinstance(value, types.StringType) and \
not isinstance(value, types.UnicodeType):
value = str(value)
return "'%s'" % string_escaper(value)
def makeKW(rowClass, args):
"""Utility method to construct a dictionary for the attributes
of an object from set of args. This also fixes the case of column names.
"""
kw = {}
for i in range(0,len(args)):
columnName = rowClass.dbColumns[i][0].lower()
for attr in rowClass.rowColumns:
if attr.lower() == columnName:
kw[attr] = args[i]
break
return kw
def defaultFactoryMethod(rowClass, data, kw):
"""Used by loadObjects to create rowObject instances.
"""
newObject = rowClass()
newObject.__dict__.update(kw)
return newObject
### utility classes
class _TableInfo:
"""(internal)
Info about a table/class and it's relationships. Also serves as a container for
generated SQL.
"""
def __init__(self, rc):
self.rowClass = rc
self.rowTableName = rc.rowTableName
self.rowKeyColumns = rc.rowKeyColumns
self.rowColumns = rc.rowColumns
if hasattr(rc, "rowForeignKeys"):
self.rowForeignKeys = rc.rowForeignKeys
else:
self.rowForeignKeys = []
if hasattr(rc, "rowFactoryMethod"):
if rc.rowFactoryMethod:
self.rowFactoryMethod = rc.rowFactoryMethod
else:
self.rowFactoryMethod = [defaultFactoryMethod]
else:
self.rowFactoryMethod = [defaultFactoryMethod]
self.updateSQL = None
self.deleteSQL = None
self.insertSQL = None
self.relationships = []
self.dbColumns = []
def addForeignKey(self, childColumns, parentColumns, childRowClass, containerMethod, autoLoad):
"""This information is attached to the "parent" table
childColumns - columns of the "child" table
parentColumns - columns of the "parent" table, the one being joined to... the "foreign" table
"""
self.relationships.append( _TableRelationship(childColumns, parentColumns,
childRowClass, containerMethod, autoLoad) )
def getRelationshipFor(self, tableName):
for relationship in self.relationships:
if relationship.childRowClass.rowTableName == tableName:
return relationship
return None
class _TableRelationship:
"""(Internal)
A foreign key relationship between two tables.
"""
def __init__(self,
childColumns,
parentColumns,
childRowClass,
containerMethod,
autoLoad):
self.childColumns = childColumns
self.parentColumns = parentColumns
self.childRowClass = childRowClass
self.containerMethod = containerMethod
self.autoLoad = autoLoad
__all__ = ['NOQUOTE', 'USEQUOTE', 'dbTypeMap', 'DBError', 'getKeyColumn',
'safe', 'quote'] | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/enterprise/util.py | util.py |
from twisted.internet import defer, threads
from twisted.python import reflect, log
from twisted.enterprise.util import safe # backwards compat
class ConnectionLost(Exception):
"""This exception means that a db connection has been lost.
Client code may try again."""
pass
class Connection(object):
"""A wrapper for a DB-API connection instance.
The wrapper passes almost everything to the wrapped connection and so has
the same API. However, the Connection knows about its pool and also
handle reconnecting should when the real connection dies.
"""
def __init__(self, pool):
self._pool = pool
self._connection = None
self.reconnect()
def close(self):
# The way adbapi works right now means that closing a connection is
# a really bad thing as it leaves a dead connection associated with
# a thread in the thread pool.
# Really, I think closing a pooled connection should return it to the
# pool but that's handled by the runWithConnection method already so,
# rather than upsetting anyone by raising an exception, let's ignore
# the request
pass
def rollback(self):
if not self._pool.reconnect:
self._connection.rollback()
return
try:
self._connection.rollback()
curs = self._connection.cursor()
curs.execute(self._pool.good_sql)
curs.close()
self._connection.commit()
return
except:
pass
self._pool.disconnect(self._connection)
if self._pool.noisy:
log.msg('Connection lost.')
raise ConnectionLost()
def reconnect(self):
if self._connection is not None:
self._pool.disconnect(self._connection)
self._connection = self._pool.connect()
def __getattr__(self, name):
return getattr(self._connection, name)
class Transaction:
"""A lightweight wrapper for a DB-API 'cursor' object.
Relays attribute access to the DB cursor. That is, you can call
execute(), fetchall(), etc., and they will be called on the
underlying DB-API cursor object. Attributes will also be
retrieved from there.
"""
_cursor = None
def __init__(self, pool, connection):
self._pool = pool
self._connection = connection
self.reopen()
def close(self):
_cursor = self._cursor
self._cursor = None
_cursor.close()
def reopen(self):
if self._cursor is not None:
self.close()
try:
self._cursor = self._connection.cursor()
return
except:
if not self._pool.reconnect:
raise
if self._pool.noisy:
log.msg('Connection lost, reconnecting')
self.reconnect()
self._cursor = self._connection.cursor()
def reconnect(self):
self._connection.reconnect()
self._cursor = None
def __getattr__(self, name):
return getattr(self._cursor, name)
class ConnectionPool:
"""I represent a pool of connections to a DB-API 2.0 compliant database.
"""
CP_ARGS = "min max name noisy openfun reconnect good_sql".split()
noisy = True # if true, generate informational log messages
min = 3 # minimum number of connections in pool
max = 5 # maximum number of connections in pool
name = None # Name to assign to thread pool for debugging
openfun = None # A function to call on new connections
reconnect = False # reconnect when connections fail
good_sql = 'select 1' # a query which should always succeed
running = False # true when the pool is operating
def __init__(self, dbapiName, *connargs, **connkw):
"""Create a new ConnectionPool.
Any positional or keyword arguments other than those documented here
are passed to the DB-API object when connecting. Use these arguments to
pass database names, usernames, passwords, etc.
@param dbapiName: an import string to use to obtain a DB-API compatible
module (e.g. 'pyPgSQL.PgSQL')
@param cp_min: the minimum number of connections in pool (default 3)
@param cp_max: the maximum number of connections in pool (default 5)
@param cp_noisy: generate informational log messages during operation
(default False)
@param cp_openfun: a callback invoked after every connect() on the
underlying DB-API object. The callback is passed a
new DB-API connection object. This callback can
setup per-connection state such as charset,
timezone, etc.
@param cp_reconnect: detect connections which have failed and reconnect
(default False). Failed connections may result in
ConnectionLost exceptions, which indicate the
query may need to be re-sent.
@param cp_good_sql: an sql query which should always succeed and change
no state (default 'select 1')
"""
self.dbapiName = dbapiName
self.dbapi = reflect.namedModule(dbapiName)
if getattr(self.dbapi, 'apilevel', None) != '2.0':
log.msg('DB API module not DB API 2.0 compliant.')
if getattr(self.dbapi, 'threadsafety', 0) < 1:
log.msg('DB API module not sufficiently thread-safe.')
self.connargs = connargs
self.connkw = connkw
for arg in self.CP_ARGS:
cp_arg = 'cp_%s' % arg
if connkw.has_key(cp_arg):
setattr(self, arg, connkw[cp_arg])
del connkw[cp_arg]
self.min = min(self.min, self.max)
self.max = max(self.min, self.max)
self.connections = {} # all connections, hashed on thread id
# these are optional so import them here
from twisted.python import threadpool
import thread
self.threadID = thread.get_ident
self.threadpool = threadpool.ThreadPool(self.min, self.max)
from twisted.internet import reactor
self.startID = reactor.callWhenRunning(self._start)
def _start(self):
self.startID = None
return self.start()
def start(self):
"""Start the connection pool.
If you are using the reactor normally, this function does *not*
need to be called.
"""
if not self.running:
from twisted.internet import reactor
self.threadpool.start()
self.shutdownID = reactor.addSystemEventTrigger('during',
'shutdown',
self.finalClose)
self.running = True
def runWithConnection(self, func, *args, **kw):
return self._deferToThread(self._runWithConnection,
func, *args, **kw)
def _runWithConnection(self, func, *args, **kw):
conn = Connection(self)
try:
result = func(conn, *args, **kw)
conn.commit()
return result
except:
conn.rollback()
raise
def runInteraction(self, interaction, *args, **kw):
"""Interact with the database and return the result.
The 'interaction' is a callable object which will be executed
in a thread using a pooled connection. It will be passed an
L{Transaction} object as an argument (whose interface is
identical to that of the database cursor for your DB-API
module of choice), and its results will be returned as a
Deferred. If running the method raises an exception, the
transaction will be rolled back. If the method returns a
value, the transaction will be committed.
NOTE that the function you pass is *not* run in the main
thread: you may have to worry about thread-safety in the
function you pass to this if it tries to use non-local
objects.
@param interaction: a callable object whose first argument is
L{adbapi.Transaction}. *args,**kw will be passed as
additional arguments.
@return: a Deferred which will fire the return value of
'interaction(Transaction(...))', or a Failure.
"""
return self._deferToThread(self._runInteraction,
interaction, *args, **kw)
def runQuery(self, *args, **kw):
"""Execute an SQL query and return the result.
A DB-API cursor will will be invoked with cursor.execute(*args, **kw).
The exact nature of the arguments will depend on the specific flavor
of DB-API being used, but the first argument in *args be an SQL
statement. The result of a subsequent cursor.fetchall() will be
fired to the Deferred which is returned. If either the 'execute' or
'fetchall' methods raise an exception, the transaction will be rolled
back and a Failure returned.
The *args and **kw arguments will be passed to the DB-API cursor's
'execute' method.
@return: a Deferred which will fire the return value of a DB-API
cursor's 'fetchall' method, or a Failure.
"""
return self.runInteraction(self._runQuery, *args, **kw)
def runOperation(self, *args, **kw):
"""Execute an SQL query and return None.
A DB-API cursor will will be invoked with cursor.execute(*args, **kw).
The exact nature of the arguments will depend on the specific flavor
of DB-API being used, but the first argument in *args will be an SQL
statement. This method will not attempt to fetch any results from the
query and is thus suitable for INSERT, DELETE, and other SQL statements
which do not return values. If the 'execute' method raises an
exception, the transaction will be rolled back and a Failure returned.
The args and kw arguments will be passed to the DB-API cursor's
'execute' method.
return: a Deferred which will fire None or a Failure.
"""
return self.runInteraction(self._runOperation, *args, **kw)
def close(self):
"""Close all pool connections and shutdown the pool."""
from twisted.internet import reactor
if self.shutdownID:
reactor.removeSystemEventTrigger(self.shutdownID)
self.shutdownID = None
if self.startID:
reactor.removeSystemEventTrigger(self.startID)
self.startID = None
self.finalClose()
def finalClose(self):
"""This should only be called by the shutdown trigger."""
self.shutdownID = None
self.threadpool.stop()
self.running = False
for conn in self.connections.values():
self._close(conn)
self.connections.clear()
def connect(self):
"""Return a database connection when one becomes available.
This method blocks and should be run in a thread from the internal
threadpool. Don't call this method directly from non-threaded code.
Using this method outside the external threadpool may exceed the
maximum number of connections in the pool.
@return: a database connection from the pool.
"""
tid = self.threadID()
conn = self.connections.get(tid)
if conn is None:
if self.noisy:
log.msg('adbapi connecting: %s %s%s' % (self.dbapiName,
self.connargs or '',
self.connkw or ''))
conn = self.dbapi.connect(*self.connargs, **self.connkw)
if self.openfun != None:
self.openfun(conn)
self.connections[tid] = conn
return conn
def disconnect(self, conn):
"""Disconnect a database connection associated with this pool.
Note: This function should only be used by the same thread which
called connect(). As with connect(), this function is not used
in normal non-threaded twisted code.
"""
tid = self.threadID()
if conn is not self.connections.get(tid):
raise Exception("wrong connection for thread")
if conn is not None:
self._close(conn)
del self.connections[tid]
def _close(self, conn):
if self.noisy:
log.msg('adbapi closing: %s' % (self.dbapiName,))
try:
conn.close()
except:
pass
def _runInteraction(self, interaction, *args, **kw):
conn = Connection(self)
trans = Transaction(self, conn)
try:
result = interaction(trans, *args, **kw)
trans.close()
conn.commit()
return result
except:
conn.rollback()
raise
def _runQuery(self, trans, *args, **kw):
trans.execute(*args, **kw)
return trans.fetchall()
def _runOperation(self, trans, *args, **kw):
trans.execute(*args, **kw)
def __getstate__(self):
return {'dbapiName': self.dbapiName,
'min': self.min,
'max': self.max,
'noisy': self.noisy,
'reconnect': self.reconnect,
'good_sql': self.good_sql,
'connargs': self.connargs,
'connkw': self.connkw}
def __setstate__(self, state):
self.__dict__ = state
self.__init__(self.dbapiName, *self.connargs, **self.connkw)
def _deferToThread(self, f, *args, **kwargs):
"""Internal function.
Call f in one of the connection pool's threads.
"""
d = defer.Deferred()
self.threadpool.callInThread(threads._putResultInDeferred,
d, f, args, kwargs)
return d
__all__ = ['Transaction', 'ConnectionPool'] | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/enterprise/adbapi.py | adbapi.py |
from twisted.enterprise import reflector
from twisted.enterprise.util import DBError, getKeyColumn, quote, safe
from twisted.enterprise.util import _TableInfo
from twisted.enterprise.row import RowObject
from twisted.python import reflect
class SQLReflector(reflector.Reflector):
"""I reflect on a database and load RowObjects from it.
In order to do this, I interrogate a relational database to
extract schema information and interface with RowObject class
objects that can interact with specific tables.
"""
populated = 0
conditionalLabels = {
reflector.EQUAL : "=",
reflector.LESSTHAN : "<",
reflector.GREATERTHAN : ">",
reflector.LIKE : "like"
}
def __init__(self, dbpool, rowClasses):
"""Initialize me against a database.
"""
reflector.Reflector.__init__(self, rowClasses)
self.dbpool = dbpool
def _populate(self):
self._transPopulateSchema()
def _transPopulateSchema(self):
"""Used to construct the row classes in a single interaction.
"""
for rc in self.rowClasses:
if not issubclass(rc, RowObject):
raise DBError("Stub class (%s) is not derived from RowObject" % reflect.qual(rc.rowClass))
self._populateSchemaFor(rc)
self.populated = 1
def _populateSchemaFor(self, rc):
"""Construct all the SQL templates for database operations on
<tableName> and populate the class <rowClass> with that info.
"""
attributes = ("rowColumns", "rowKeyColumns", "rowTableName" )
for att in attributes:
if not hasattr(rc, att):
raise DBError("RowClass %s must have class variable: %s" % (rc, att))
tableInfo = _TableInfo(rc)
tableInfo.updateSQL = self.buildUpdateSQL(tableInfo)
tableInfo.insertSQL = self.buildInsertSQL(tableInfo)
tableInfo.deleteSQL = self.buildDeleteSQL(tableInfo)
self.populateSchemaFor(tableInfo)
def escape_string(self, text):
"""Escape a string for use in an SQL statement. The default
implementation escapes ' with '' and \ with \\. Redefine this
function in a subclass if your database server uses different
escaping rules.
"""
return safe(text)
def quote_value(self, value, type):
"""Format a value for use in an SQL statement.
@param value: a value to format as data in SQL.
@param type: a key in util.dbTypeMap.
"""
return quote(value, type, string_escaper=self.escape_string)
def loadObjectsFrom(self, tableName, parentRow=None, data=None,
whereClause=None, forceChildren=0):
"""Load a set of RowObjects from a database.
Create a set of python objects of <rowClass> from the contents
of a table populated with appropriate data members.
Example::
| class EmployeeRow(row.RowObject):
| pass
|
| def gotEmployees(employees):
| for emp in employees:
| emp.manager = "fred smith"
| manager.updateRow(emp)
|
| reflector.loadObjectsFrom("employee",
| data = userData,
| whereClause = [("manager" , EQUAL, "fred smith")]
| ).addCallback(gotEmployees)
NOTE: the objects and all children should be loaded in a single transaction.
NOTE: can specify a parentRow _OR_ a whereClause.
"""
if parentRow and whereClause:
raise DBError("Must specify one of parentRow _OR_ whereClause")
if parentRow:
info = self.getTableInfo(parentRow)
relationship = info.getRelationshipFor(tableName)
whereClause = self.buildWhereClause(relationship, parentRow)
elif whereClause:
pass
else:
whereClause = []
return self.dbpool.runInteraction(self._rowLoader, tableName,
parentRow, data, whereClause,
forceChildren)
def _rowLoader(self, transaction, tableName, parentRow, data,
whereClause, forceChildren):
"""immediate loading of rowobjects from the table with the whereClause.
"""
tableInfo = self.schema[tableName]
# Build the SQL for the query
sql = "SELECT "
first = 1
for column, type in tableInfo.rowColumns:
if first:
first = 0
else:
sql = sql + ","
sql = sql + " %s" % column
sql = sql + " FROM %s " % (tableName)
if whereClause:
sql += " WHERE "
first = 1
for wItem in whereClause:
if first:
first = 0
else:
sql += " AND "
(columnName, cond, value) = wItem
t = self.findTypeFor(tableName, columnName)
quotedValue = self.quote_value(value, t)
sql += "%s %s %s" % (columnName, self.conditionalLabels[cond],
quotedValue)
# execute the query
transaction.execute(sql)
rows = transaction.fetchall()
# construct the row objects
results = []
newRows = []
for args in rows:
kw = {}
for i in range(0,len(args)):
ColumnName = tableInfo.rowColumns[i][0].lower()
for attr, type in tableInfo.rowClass.rowColumns:
if attr.lower() == ColumnName:
kw[attr] = args[i]
break
# find the row in the cache or add it
resultObject = self.findInCache(tableInfo.rowClass, kw)
if not resultObject:
meth = tableInfo.rowFactoryMethod[0]
resultObject = meth(tableInfo.rowClass, data, kw)
self.addToCache(resultObject)
newRows.append(resultObject)
results.append(resultObject)
# add these rows to the parentRow if required
if parentRow:
self.addToParent(parentRow, newRows, tableName)
# load children or each of these rows if required
for relationship in tableInfo.relationships:
if not forceChildren and not relationship.autoLoad:
continue
for row in results:
# build where clause
childWhereClause = self.buildWhereClause(relationship, row)
# load the children immediately, but do nothing with them
self._rowLoader(transaction,
relationship.childRowClass.rowTableName,
row, data, childWhereClause, forceChildren)
return results
def findTypeFor(self, tableName, columnName):
tableInfo = self.schema[tableName]
columnName = columnName.lower()
for column, type in tableInfo.rowColumns:
if column.lower() == columnName:
return type
def buildUpdateSQL(self, tableInfo):
"""(Internal) Build SQL template to update a RowObject.
Returns: SQL that is used to contruct a rowObject class.
"""
sql = "UPDATE %s SET" % tableInfo.rowTableName
# build update attributes
first = 1
for column, type in tableInfo.rowColumns:
if getKeyColumn(tableInfo.rowClass, column):
continue
if not first:
sql = sql + ", "
sql = sql + " %s = %s" % (column, "%s")
first = 0
# build where clause
first = 1
sql = sql + " WHERE "
for keyColumn, type in tableInfo.rowKeyColumns:
if not first:
sql = sql + " AND "
sql = sql + " %s = %s " % (keyColumn, "%s")
first = 0
return sql
def buildInsertSQL(self, tableInfo):
"""(Internal) Build SQL template to insert a new row.
Returns: SQL that is used to insert a new row for a rowObject
instance not created from the database.
"""
sql = "INSERT INTO %s (" % tableInfo.rowTableName
# build column list
first = 1
for column, type in tableInfo.rowColumns:
if not first:
sql = sql + ", "
sql = sql + column
first = 0
sql = sql + " ) VALUES ("
# build values list
first = 1
for column, type in tableInfo.rowColumns:
if not first:
sql = sql + ", "
sql = sql + "%s"
first = 0
sql = sql + ")"
return sql
def buildDeleteSQL(self, tableInfo):
"""Build the SQL template to delete a row from the table.
"""
sql = "DELETE FROM %s " % tableInfo.rowTableName
# build where clause
first = 1
sql = sql + " WHERE "
for keyColumn, type in tableInfo.rowKeyColumns:
if not first:
sql = sql + " AND "
sql = sql + " %s = %s " % (keyColumn, "%s")
first = 0
return sql
def updateRowSQL(self, rowObject):
"""Build SQL to update the contents of rowObject.
"""
args = []
tableInfo = self.schema[rowObject.rowTableName]
# build update attributes
for column, type in tableInfo.rowColumns:
if not getKeyColumn(rowObject.__class__, column):
args.append(self.quote_value(rowObject.findAttribute(column),
type))
# build where clause
for keyColumn, type in tableInfo.rowKeyColumns:
args.append(self.quote_value(rowObject.findAttribute(keyColumn),
type))
return self.getTableInfo(rowObject).updateSQL % tuple(args)
def updateRow(self, rowObject):
"""Update the contents of rowObject to the database.
"""
sql = self.updateRowSQL(rowObject)
rowObject.setDirty(0)
return self.dbpool.runOperation(sql)
def insertRowSQL(self, rowObject):
"""Build SQL to insert the contents of rowObject.
"""
args = []
tableInfo = self.schema[rowObject.rowTableName]
# build values
for column, type in tableInfo.rowColumns:
args.append(self.quote_value(rowObject.findAttribute(column),type))
return self.getTableInfo(rowObject).insertSQL % tuple(args)
def insertRow(self, rowObject):
"""Insert a new row for rowObject.
"""
rowObject.setDirty(0)
sql = self.insertRowSQL(rowObject)
return self.dbpool.runOperation(sql)
def deleteRowSQL(self, rowObject):
"""Build SQL to delete rowObject from the database.
"""
args = []
tableInfo = self.schema[rowObject.rowTableName]
# build where clause
for keyColumn, type in tableInfo.rowKeyColumns:
args.append(self.quote_value(rowObject.findAttribute(keyColumn),
type))
return self.getTableInfo(rowObject).deleteSQL % tuple(args)
def deleteRow(self, rowObject):
"""Delete the row for rowObject from the database.
"""
sql = self.deleteRowSQL(rowObject)
self.removeFromCache(rowObject)
return self.dbpool.runOperation(sql)
__all__ = ['SQLReflector'] | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/enterprise/sqlreflector.py | sqlreflector.py |
from twisted.enterprise.util import DBError, NOQUOTE, getKeyColumn, dbTypeMap
class RowObject:
"""I represent a row in a table in a relational database.
My class is "populated" by a Reflector object. After I am
populated, instances of me are able to interact with a particular
database table.
You should use a class derived from this class for each database
table.
reflector.loadObjectsFrom() is used to create sets of
instance of objects of this class from database tables.
Once created, the "key column" attributes cannot be changed.
Class Attributes that users must supply::
rowKeyColumns # list of key columns in form: [(columnName, typeName)]
rowTableName # name of database table
rowColumns # list of the columns in the table with the correct
# case.this will be used to create member variables.
rowFactoryMethod # method to create an instance of this class.
# HACK: must be in a list!!! [factoryMethod] (optional)
rowForeignKeys # keys to other tables (optional)
"""
populated = 0 # set on the class when the class is "populated" with SQL
dirty = 0 # set on an instance when the instance is out-of-sync with the database
def assignKeyAttr(self, attrName, value):
"""Assign to a key attribute.
This cannot be done through normal means to protect changing
keys of db objects.
"""
found = 0
for keyColumn, type in self.rowKeyColumns:
if keyColumn == attrName:
found = 1
if not found:
raise DBError("%s is not a key columns." % attrName)
self.__dict__[attrName] = value
def findAttribute(self, attrName):
"""Find an attribute by caseless name.
"""
for attr, type in self.rowColumns:
if attr.lower() == attrName.lower():
return getattr(self, attr)
raise DBError("Unable to find attribute %s" % attrName)
def __setattr__(self, name, value):
"""Special setattr to prevent changing of key values.
"""
# build where clause
if getKeyColumn(self.__class__, name):
raise DBError("cannot assign value <%s> to key column attribute <%s> of RowObject class" % (value,name))
if name in self.rowColumns:
if value != self.__dict__.get(name,None) and not self.dirty:
self.setDirty(1)
self.__dict__[name] = value
def createDefaultAttributes(self):
"""Populate instance with default attributes.
This is used when creating a new instance NOT from the
database.
"""
for attr in self.rowColumns:
if getKeyColumn(self.__class__, attr):
continue
for column, ctype, typeid in self.dbColumns:
if column.lower(column) == attr.lower():
q = dbTypeMap.get(ctype, None)
if q == NOQUOTE:
setattr(self, attr, 0)
else:
setattr(self, attr, "")
def setDirty(self, flag):
"""Use this to set the 'dirty' flag.
(note: this avoids infinite recursion in __setattr__, and
prevents the 'dirty' flag )
"""
self.__dict__["dirty"] = flag
def getKeyTuple(self):
keys = []
keys.append(self.rowTableName)
for keyName, keyType in self.rowKeyColumns:
keys.append( getattr(self, keyName) )
return tuple(keys)
__all__ = ['RowObject'] | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/enterprise/row.py | row.py |
import weakref
from twisted.enterprise.util import DBError
class Reflector:
"""Base class for enterprise reflectors. This implements row caching.
"""
populated = 0
def __init__(self, rowClasses):
"""
Initialize me against a database.
@param rowClasses: a list of row class objects that describe the
database schema.
"""
self.rowCache = weakref.WeakValueDictionary() # does not hold references to cached rows.
self.rowClasses = rowClasses
self.schema = {}
self._populate()
def __getstate__(self):
d = self.__dict__.copy()
del d['rowCache']
return d
def __setstate__(self, state):
self.__dict__ = state
self.rowCache = weakref.WeakValueDictionary()
self._populate()
def _populate(self):
"""Implement me to populate schema information for the reflector.
"""
raise DBError("not implemented")
def populateSchemaFor(self, tableInfo):
"""This is called once for each registered rowClass to add it
and its foreign key relationships for that rowClass to the
schema."""
self.schema[ tableInfo.rowTableName ] = tableInfo
# add the foreign key to the foreign table.
for foreignTableName, childColumns, parentColumns, containerMethod, autoLoad in tableInfo.rowForeignKeys:
self.schema[foreignTableName].addForeignKey(childColumns,
parentColumns, tableInfo.rowClass,
containerMethod, autoLoad)
def getTableInfo(self, rowObject):
"""Get a TableInfo record about a particular instance.
This record contains various information about the instance's
class as registered with this reflector.
@param rowObject: a L{RowObject} instance of a class previously
registered with me.
@raises twisted.enterprise.row.DBError: raised if this class was not
previously registered.
"""
try:
return self.schema[rowObject.rowTableName]
except KeyError:
raise DBError("class %s was not registered with %s" % (
rowObject.__class__, self))
def buildWhereClause(self, relationship, row):
"""util method used by reflectors. builds a where clause to link a row to another table.
"""
whereClause = []
for i in range(0,len(relationship.childColumns)):
value = getattr(row, relationship.parentColumns[i][0])
whereClause.append( [relationship.childColumns[i][0], EQUAL, value] )
return whereClause
def addToParent(self, parentRow, rows, tableName):
"""util method used by reflectors. adds these rows to the parent row object.
If a rowClass does not have a containerMethod, then a list attribute "childRows"
will be used.
"""
parentInfo = self.getTableInfo(parentRow)
relationship = parentInfo.getRelationshipFor(tableName)
if not relationship:
raise DBError("no relationship from %s to %s" % ( parentRow.rowTableName, tableName) )
if not relationship.containerMethod:
if hasattr(parentRow, "childRows"):
for row in rows:
if row not in parentRow.childRows:
parentRow.childRows.append(row)
else:
parentRow.childRows = rows
return
if not hasattr(parentRow, relationship.containerMethod):
raise DBError("parent row (%s) doesnt have container method <%s>!" % (parentRow, relationship.containerMethod))
meth = getattr(parentRow, relationship.containerMethod)
for row in rows:
meth(row)
####### Row Cache ########
def addToCache(self, rowObject):
"""NOTE: Should this be recursive?! requires better container knowledge..."""
self.rowCache[ rowObject.getKeyTuple() ] = rowObject
def findInCache(self, rowClass, kw):
keys = []
keys.append(rowClass.rowTableName)
for keyName, keyType in rowClass.rowKeyColumns:
keys.append( kw[keyName] )
keyTuple = tuple(keys)
return self.rowCache.get(keyTuple)
def removeFromCache(self, rowObject):
"""NOTE: should this be recursive!??"""
key = rowObject.getKeyTuple()
if self.rowCache.has_key(key):
del self.rowCache[key]
####### Row Operations ########
def loadObjectsFrom(self, tableName, parent=None, data=None,
whereClause=[], loadChildren=1):
"""Implement me to load objects from the database.
@param whereClause: a list of tuples of (columnName, conditional, value)
so it can be parsed by all types of reflectors. eg.::
whereClause = [("name", EQUALS, "fred"), ("age", GREATERTHAN, 18)]
"""
raise DBError("not implemented")
def updateRow(self, rowObject):
"""update this rowObject to the database.
"""
raise DBError("not implemented")
def insertRow(self, rowObject):
"""insert a new row for this object instance.
"""
raise DBError("not implemented")
def deleteRow(self, rowObject):
"""delete the row for this object from the database.
"""
raise DBError("not implemented")
# conditionals
EQUAL = 0
LESSTHAN = 1
GREATERTHAN = 2
LIKE = 3
__all__ = ['Reflector', 'EQUAL', 'LESSTHAN', 'GREATERTHAN', 'LIKE'] | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/enterprise/reflector.py | reflector.py |
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
from __future__ import nested_scopes, generators
__version__ = '$Revision: 1.51 $'[11:-2]
import os, sys, hmac, errno, new, inspect
from UserDict import UserDict
class InsensitiveDict:
"""Dictionary, that has case-insensitive keys.
Normally keys are retained in their original form when queried with
.keys() or .items(). If initialized with preserveCase=0, keys are both
looked up in lowercase and returned in lowercase by .keys() and .items().
"""
"""
Modified recipe at
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66315 originally
contributed by Sami Hangaslammi.
"""
def __init__(self, dict=None, preserve=1):
"""Create an empty dictionary, or update from 'dict'."""
self.data = {}
self.preserve=preserve
if dict:
self.update(dict)
def __delitem__(self, key):
k=self._lowerOrReturn(key)
del self.data[k]
def _lowerOrReturn(self, key):
if isinstance(key, str) or isinstance(key, unicode):
return key.lower()
else:
return key
def __getitem__(self, key):
"""Retrieve the value associated with 'key' (in any case)."""
k = self._lowerOrReturn(key)
return self.data[k][1]
def __setitem__(self, key, value):
"""Associate 'value' with 'key'. If 'key' already exists, but
in different case, it will be replaced."""
k = self._lowerOrReturn(key)
self.data[k] = (key, value)
def has_key(self, key):
"""Case insensitive test whether 'key' exists."""
k = self._lowerOrReturn(key)
return self.data.has_key(k)
__contains__=has_key
def _doPreserve(self, key):
if not self.preserve and (isinstance(key, str)
or isinstance(key, unicode)):
return key.lower()
else:
return key
def keys(self):
"""List of keys in their original case."""
return list(self.iterkeys())
def values(self):
"""List of values."""
return list(self.itervalues())
def items(self):
"""List of (key,value) pairs."""
return list(self.iteritems())
def get(self, key, default=None):
"""Retrieve value associated with 'key' or return default value
if 'key' doesn't exist."""
try:
return self[key]
except KeyError:
return default
def setdefault(self, key, default):
"""If 'key' doesn't exists, associate it with the 'default' value.
Return value associated with 'key'."""
if not self.has_key(key):
self[key] = default
return self[key]
def update(self, dict):
"""Copy (key,value) pairs from 'dict'."""
for k,v in dict.items():
self[k] = v
def __repr__(self):
"""String representation of the dictionary."""
items = ", ".join([("%r: %r" % (k,v)) for k,v in self.items()])
return "InsensitiveDict({%s})" % items
def iterkeys(self):
for v in self.data.itervalues():
yield self._doPreserve(v[0])
def itervalues(self):
for v in self.data.itervalues():
yield v[1]
def iteritems(self):
for (k, v) in self.data.itervalues():
yield self._doPreserve(k), v
def popitem(self):
i=self.items()[0]
del self[i[0]]
return i
def clear(self):
for k in self.keys():
del self[k]
def copy(self):
return InsensitiveDict(self, self.preserve)
def __len__(self):
return len(self.data)
def __eq__(self, other):
for k,v in self.items():
if not (k in other) or not (other[k]==v):
return 0
return len(self)==len(other)
class OrderedDict(UserDict):
"""A UserDict that preserves insert order whenever possible."""
def __init__(self, dict=None, **kwargs):
self._order = []
self.data = {}
if dict is not None:
if hasattr(dict,'keys'):
self.update(dict)
else:
for k,v in dict: # sequence
self[k] = v
if len(kwargs):
self.update(kwargs)
def __repr__(self):
return '{'+', '.join([('%r: %r' % item) for item in self.items()])+'}'
def __setitem__(self, key, value):
if not self.has_key(key):
self._order.append(key)
UserDict.__setitem__(self, key, value)
def copy(self):
return self.__class__(self)
def __delitem__(self, key):
UserDict.__delitem__(self, key)
self._order.remove(key)
def iteritems(self):
for item in self._order:
yield (item, self[item])
def items(self):
return list(self.iteritems())
def itervalues(self):
for item in self._order:
yield self[item]
def values(self):
return list(self.itervalues())
def iterkeys(self):
return iter(self._order)
def keys(self):
return list(self._order)
def popitem(self):
key = self._order[-1]
value = self[key]
del self[key]
return (key, value)
def setdefault(self, item, default):
if self.has_key(item):
return self[item]
self[item] = default
return default
def update(self, d):
for k, v in d.items():
self[k] = v
def uniquify(lst):
"""Make the elements of a list unique by inserting them into a dictionary.
This must not change the order of the input lst.
"""
dct = {}
result = []
for k in lst:
if not dct.has_key(k): result.append(k)
dct[k] = 1
return result
def padTo(n, seq, default=None):
"""Pads a sequence out to n elements,
filling in with a default value if it is not long enough.
If the input sequence is longer than n, raises ValueError.
Details, details:
This returns a new list; it does not extend the original sequence.
The new list contains the values of the original sequence, not copies.
"""
if len(seq) > n:
raise ValueError, "%d elements is more than %d." % (len(seq), n)
blank = [default] * n
blank[:len(seq)] = list(seq)
return blank
def getPluginDirs():
import twisted
systemPlugins = os.path.join(os.path.dirname(os.path.dirname(
os.path.abspath(twisted.__file__))), 'plugins')
userPlugins = os.path.expanduser("~/TwistedPlugins")
confPlugins = os.path.expanduser("~/.twisted")
allPlugins = filter(os.path.isdir, [systemPlugins, userPlugins, confPlugins])
return allPlugins
def addPluginDir():
sys.path.extend(getPluginDirs())
def sibpath(path, sibling):
"""Return the path to a sibling of a file in the filesystem.
This is useful in conjunction with the special __file__ attribute
that Python provides for modules, so modules can load associated
resource files.
"""
return os.path.join(os.path.dirname(os.path.abspath(path)), sibling)
def _getpass(prompt):
"""Helper to turn IOErrors into KeyboardInterrupts"""
import getpass
try:
return getpass.getpass(prompt)
except IOError, e:
if e.errno == errno.EINTR:
raise KeyboardInterrupt
raise
except EOFError:
raise KeyboardInterrupt
def getPassword(prompt = 'Password: ', confirm = 0, forceTTY = 0,
confirmPrompt = 'Confirm password: ',
mismatchMessage = "Passwords don't match."):
"""Obtain a password by prompting or from stdin.
If stdin is a terminal, prompt for a new password, and confirm (if
C{confirm} is true) by asking again to make sure the user typed the same
thing, as keystrokes will not be echoed.
If stdin is not a terminal, and C{forceTTY} is not true, read in a line
and use it as the password, less the trailing newline, if any. If
C{forceTTY} is true, attempt to open a tty and prompt for the password
using it. Raise a RuntimeError if this is not possible.
@returns: C{str}
"""
isaTTY = hasattr(sys.stdin, 'isatty') and sys.stdin.isatty()
old = None
try:
if not isaTTY:
if forceTTY:
try:
old = sys.stdin, sys.stdout
sys.stdin = sys.stdout = open('/dev/tty', 'r+')
except:
raise RuntimeError("Cannot obtain a TTY")
else:
password = sys.stdin.readline()
if password[-1] == '\n':
password = password[:-1]
return password
while 1:
try1 = _getpass(prompt)
if not confirm:
return try1
try2 = _getpass(confirmPrompt)
if try1 == try2:
return try1
else:
sys.stderr.write(mismatchMessage + "\n")
finally:
if old:
sys.stdin.close()
sys.stdin, sys.stdout = old
def dict(*a, **k):
import warnings
import __builtin__
warnings.warn('twisted.python.util.dict is deprecated. Use __builtin__.dict instead')
return __builtin__.dict(*a, **k)
def println(*a):
sys.stdout.write(' '.join(map(str, a))+'\n')
# XXX
# This does not belong here
# But where does it belong?
def str_xor(s, b):
return ''.join([chr(ord(c) ^ b) for c in s])
def keyed_md5(secret, challenge):
"""Create the keyed MD5 string for the given secret and challenge."""
import warnings
warnings.warn(
"keyed_md5() is deprecated. Use the stdlib module hmac instead.",
DeprecationWarning, stacklevel=2
)
return hmac.HMAC(secret, challenge).hexdigest()
def makeStatBar(width, maxPosition, doneChar = '=', undoneChar = '-', currentChar = '>'):
"""Creates a function that will return a string representing a progress bar.
"""
aValue = width / float(maxPosition)
def statBar(position, force = 0, last = ['']):
assert len(last) == 1, "Don't mess with the last parameter."
done = int(aValue * position)
toDo = width - done - 2
result = "[%s%s%s]" % (doneChar * done, currentChar, undoneChar * toDo)
if force:
last[0] = result
return result
if result == last[0]:
return ''
last[0] = result
return result
statBar.__doc__ = """statBar(position, force = 0) -> '[%s%s%s]'-style progress bar
returned string is %d characters long, and the range goes from 0..%d.
The 'position' argument is where the '%s' will be drawn. If force is false,
'' will be returned instead if the resulting progress bar is identical to the
previously returned progress bar.
""" % (doneChar * 3, currentChar, undoneChar * 3, width, maxPosition, currentChar)
return statBar
def spewer(frame, s, ignored):
"""A trace function for sys.settrace that prints every function or method call."""
from twisted.python import reflect
if frame.f_locals.has_key('self'):
se = frame.f_locals['self']
if hasattr(se, '__class__'):
k = reflect.qual(se.__class__)
else:
k = reflect.qual(type(se))
print 'method %s of %s at %s' % (
frame.f_code.co_name, k, id(se)
)
else:
print 'function %s in %s, line %s' % (
frame.f_code.co_name,
frame.f_code.co_filename,
frame.f_lineno)
def searchupwards(start, files=[], dirs=[]):
"""Walk upwards from start, looking for a directory containing
all files and directories given as arguments::
>>> searchupwards('.', ['foo.txt'], ['bar', 'bam'])
If not found, return None
"""
start=os.path.abspath(start)
parents=start.split(os.sep)
exists=os.path.exists; join=os.sep.join; isdir=os.path.isdir
while len(parents):
candidate=join(parents)+os.sep
allpresent=1
for f in files:
if not exists("%s%s" % (candidate, f)):
allpresent=0
break
if allpresent:
for d in dirs:
if not isdir("%s%s" % (candidate, d)):
allpresent=0
break
if allpresent: return candidate
parents.pop(-1)
return None
class LineLog:
"""
A limited-size line-based log, useful for logging line-based
protocols such as SMTP.
When the log fills up, old entries drop off the end.
"""
def __init__(self, size=10):
"""
Create a new log, with size lines of storage (default 10).
A log size of 0 (or less) means an infinite log.
"""
if size < 0:
size = 0
self.log = [None]*size
self.size = size
def append(self,line):
if self.size:
self.log[:-1] = self.log[1:]
self.log[-1] = line
else:
self.log.append(line)
def str(self):
return '\n'.join(filter(None,self.log))
def __getitem__(self, item):
return filter(None,self.log)[item]
def clear(self):
"""Empty the log"""
self.log = [None]*self.size
def raises(exception, f, *args, **kwargs):
"""Determine whether the given call raises the given exception"""
try:
f(*args, **kwargs)
except exception:
return 1
return 0
class IntervalDifferential:
"""
Given a list of intervals, generate the amount of time to sleep between
\"instants\".
For example, given 7, 11 and 13, the three (infinite) sequences::
7 14 21 28 35 ...
11 22 33 44 ...
13 26 39 52 ...
will be generated, merged, and used to produce::
(7, 0) (4, 1) (2, 2) (1, 0) (7, 0) (1, 1) (4, 2) (2, 0) (5, 1) (2, 0)
New intervals may be added or removed as iteration proceeds using the
proper methods.
"""
def __init__(self, intervals, default=60):
"""
@type intervals: C{list} of C{int}, C{long}, or C{float} param
@param intervals: The intervals between instants.
@type default: C{int}, C{long}, or C{float}
@param default: The duration to generate if the intervals list
becomes empty.
"""
self.intervals = intervals[:]
self.default = default
def __iter__(self):
return _IntervalDifferentialIterator(self.intervals, self.default)
class _IntervalDifferentialIterator:
def __init__(self, i, d):
self.intervals = [[e, e, n] for (e, n) in zip(i, range(len(i)))]
self.default = d
self.last = 0
def next(self):
if not self.intervals:
return (self.default, None)
last, index = self.intervals[0][0], self.intervals[0][2]
self.intervals[0][0] += self.intervals[0][1]
self.intervals.sort()
result = last - self.last
self.last = last
return result, index
def addInterval(self, i):
if self.intervals:
delay = self.intervals[0][0] - self.intervals[0][1]
self.intervals.append([delay + i, i, len(self.intervals)])
self.intervals.sort()
else:
self.intervals.append([i, i, 0])
def removeInterval(self, interval):
for i in range(len(self.intervals)):
if self.intervals[i][1] == interval:
index = self.intervals[i][2]
del self.intervals[i]
for i in self.intervals:
if i[2] > index:
i[2] -= 1
return
raise ValueError, "Specified interval not in IntervalDifferential"
class FancyStrMixin:
"""
Set showAttributes to a sequence of strings naming attributes, OR
sequences of (attributeName, displayName, formatCharacter)
"""
showAttributes = ()
def __str__(self):
r = ['<', hasattr(self, 'fancybasename') and self.fancybasename or self.__class__.__name__]
for attr in self.showAttributes:
if isinstance(attr, str):
r.append(' %s=%r' % (attr, getattr(self, attr)))
else:
r.append((' %s=' + attr[2]) % (attr[1], getattr(self, attr[0])))
r.append('>')
return ''.join(r)
__repr__ = __str__
class FancyEqMixin:
compareAttributes = ()
def __eq__(self, other):
if not self.compareAttributes:
return self is other
#XXX Maybe get rid of this, and rather use hasattr()s
if not isinstance(other, self.__class__):
return False
for attr in self.compareAttributes:
if not getattr(self, attr) == getattr(other, attr):
return False
return True
def __ne__(self, other):
return not self.__eq__(other)
def dsu(list, key):
L2 = [(key(e), i, e) for (i, e) in zip(range(len(list)), list)]
L2.sort()
return [e[2] for e in L2]
try:
import pwd, grp
from os import setgroups, getgroups
def _setgroups_until_success(l):
while(1):
# NASTY NASTY HACK (but glibc does it so it must be okay):
# In case sysconfig didn't give the right answer, find the limit
# on max groups by just looping, trying to set fewer and fewer
# groups each time until it succeeds.
try:
setgroups(l)
except ValueError:
# This exception comes from python itself restricting
# number of groups allowed.
if len(l) > 1:
del l[-1]
else:
raise
except OSError, e:
if e.errno == errno.EINVAL and len(l) > 1:
# This comes from the OS saying too many groups
del l[-1]
else:
raise
else:
# Success, yay!
return
def initgroups(uid, primaryGid):
"""Initializes the group access list.
This is done by reading the group database /etc/group and using all
groups of which C{uid} is a member. The additional group
C{primaryGid} is also added to the list.
If the given user is a member of more than C{NGROUPS}, arbitrary
groups will be silently discarded to bring the number below that
limit.
"""
try:
# Try to get the maximum number of groups
max_groups = os.sysconf("SC_NGROUPS_MAX")
except:
# No predefined limit
max_groups = 0
username = pwd.getpwuid(uid)[0]
l = []
if primaryGid is not None:
l.append(primaryGid)
for groupname, password, gid, userlist in grp.getgrall():
if username in userlist:
l.append(gid)
if len(l) == max_groups:
break # No more groups, ignore any more
try:
_setgroups_until_success(l)
except OSError, e:
# We might be able to remove this code now that we
# don't try to setgid/setuid even when not asked to.
if e.errno == errno.EPERM:
for g in getgroups():
if g not in l:
raise
else:
raise
except:
def initgroups(uid, primaryGid):
"""Do nothing.
Underlying platform support require to manipulate groups is missing.
"""
def switchUID(uid, gid, euid=False):
if euid:
setuid = os.seteuid
setgid = os.setegid
else:
setuid = os.setuid
setgid = os.setgid
if gid is not None:
setgid(gid)
if uid is not None:
initgroups(uid, gid)
setuid(uid)
class SubclassableCStringIO(object):
"""A wrapper around cStringIO to allow for subclassing"""
__csio = None
def __init__(self, *a, **kw):
from cStringIO import StringIO
self.__csio = StringIO(*a, **kw)
def __iter__(self):
return self.__csio.__iter__()
def next(self):
return self.__csio.next()
def close(self):
return self.__csio.close()
def isatty(self):
return self.__csio.isatty()
def seek(self, pos, mode=0):
return self.__csio.seek(pos, mode)
def tell(self):
return self.__csio.tell()
def read(self, n=-1):
return self.__csio.read(n)
def readline(self, length=None):
return self.__csio.readline(length)
def readlines(self, sizehint=0):
return self.__csio.readlines(sizehint)
def truncate(self, size=None):
return self.__csio.truncate(size)
def write(self, s):
return self.__csio.write(s)
def writelines(self, list):
return self.__csio.writelines(list)
def flush(self):
return self.__csio.flush()
def getvalue(self):
return self.__csio.getvalue()
def moduleMovedForSplit(origModuleName, newModuleName, moduleDesc,
projectName, projectURL, globDict):
from twisted.python import reflect
modoc = """
%(moduleDesc)s
This module is DEPRECATED. It has been split off into a third party
package, Twisted %(projectName)s. Please see %(projectURL)s.
This is just a place-holder that imports from the third-party %(projectName)s
package for backwards compatibility. To use it, you need to install
that package.
""" % {'moduleDesc': moduleDesc,
'projectName': projectName,
'projectURL': projectURL}
#origModule = reflect.namedModule(origModuleName)
try:
newModule = reflect.namedModule(newModuleName)
except ImportError:
raise ImportError("You need to have the Twisted %s "
"package installed to use %s. "
"See %s."
% (projectName, origModuleName, projectURL))
# Populate the old module with the new module's contents
for k,v in vars(newModule).items():
globDict[k] = v
globDict['__doc__'] = modoc
import warnings
warnings.warn("%s has moved to %s. See %s." % (origModuleName, newModuleName,
projectURL),
DeprecationWarning, stacklevel=3)
return
def untilConcludes(f, *a, **kw):
while True:
try:
return f(*a, **kw)
except (IOError, OSError), e:
if e.args[0] == errno.EINTR:
continue
raise
# A value about twice as large as any Python int, to which negative values
# from id() will be added, moving them into a range which should begin just
# above where positive values from id() leave off.
_HUGEINT = (sys.maxint + 1L) * 2L
def unsignedID(obj):
"""
Return the id of an object as an unsigned number so that its hex
representation makes sense
"""
rval = id(obj)
if rval < 0:
rval += _HUGEINT
return rval
def mergeFunctionMetadata(f, g):
"""
Overwrite C{g}'s docstring and name with values from C{f}. Update
C{g}'s instance dictionary with C{f}'s.
"""
try:
g.__doc__ = f.__doc__
except (TypeError, AttributeError):
pass
try:
g.__dict__.update(f.__dict__)
except (TypeError, AttributeError):
pass
try:
g.__name__ = f.__name__
except TypeError:
try:
g = new.function(
g.func_code, g.func_globals,
f.__name__, inspect.getargspec(g)[-1],
g.func_closure)
except TypeError:
pass
return g
def nameToLabel(mname):
"""
Convert a string like a variable name into a slightly more human-friendly
string with spaces and capitalized letters.
@type mname: C{str}
@param mname: The name to convert to a label. This must be a string
which could be used as a Python identifier. Strings which do not take
this form will result in unpredictable behavior.
@rtype: C{str}
"""
labelList = []
word = ''
lastWasUpper = False
for letter in mname:
if letter.isupper() == lastWasUpper:
# Continuing a word.
word += letter
else:
# breaking a word OR beginning a word
if lastWasUpper:
# could be either
if len(word) == 1:
# keep going
word += letter
else:
# acronym
# we're processing the lowercase letter after the acronym-then-capital
lastWord = word[:-1]
firstLetter = word[-1]
labelList.append(lastWord)
word = firstLetter + letter
else:
# definitely breaking: lower to upper
labelList.append(word)
word = letter
lastWasUpper = letter.isupper()
if labelList:
labelList[0] = labelList[0].capitalize()
else:
return mname.capitalize()
labelList.append(word)
return ' '.join(labelList)
__all__ = [
"uniquify", "padTo", "getPluginDirs", "addPluginDir", "sibpath",
"getPassword", "dict", "println", "keyed_md5", "makeStatBar",
"OrderedDict", "InsensitiveDict", "spewer", "searchupwards", "LineLog",
"raises", "IntervalDifferential", "FancyStrMixin", "FancyEqMixin",
"dsu", "switchUID", "SubclassableCStringIO", "moduleMovedForSplit",
"unsignedID", "mergeFunctionMetadata", "nameToLabel",
] | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/python/util.py | util.py |
__metaclass__ = type
import errno, os
from time import time as _uniquefloat
def unique():
return str(long(_uniquefloat() * 1000))
try:
from os import symlink
from os import readlink
from os import remove as rmlink
from os import rename as mvlink
except:
# XXX Implement an atomic thingamajig for win32
import shutil
def symlink(value, filename):
newlinkname = filename+"."+unique()+'.newlink'
newvalname = os.path.join(newlinkname,"symlink")
os.mkdir(newlinkname)
f = open(newvalname,'wb')
f.write(value)
f.flush()
f.close()
try:
os.rename(newlinkname, filename)
except:
os.remove(newvalname)
os.rmdir(newlinkname)
raise
def readlink(filename):
return open(os.path.join(filename,'symlink'),'rb').read()
def rmlink(filename):
shutil.rmtree(filename)
def mvlink(src, dest):
try:
shutil.rmtree(dest)
except:
pass
os.rename(src,dest)
class FilesystemLock:
"""A mutex.
This relies on the filesystem property that creating
a symlink is an atomic operation and that it will
fail if the symlink already exists. Deleting the
symlink will release the lock.
@ivar name: The name of the file associated with this lock.
@ivar clean: Indicates whether this lock was released cleanly by its
last owner. Only meaningful after C{lock} has been called and returns
True.
"""
clean = None
locked = False
def __init__(self, name):
self.name = name
def lock(self):
"""Acquire this lock.
@rtype: C{bool}
@return: True if the lock is acquired, false otherwise.
@raise: Any exception os.symlink() may raise, other than
EEXIST.
"""
try:
pid = readlink(self.name)
except (OSError, IOError), e:
if e.errno != errno.ENOENT:
raise
self.clean = True
else:
if not hasattr(os, 'kill'):
return False
try:
os.kill(int(pid), 0)
except (OSError, IOError), e:
if e.errno != errno.ESRCH:
raise
rmlink(self.name)
self.clean = False
else:
return False
symlink(str(os.getpid()), self.name)
self.locked = True
return True
def unlock(self):
"""Release this lock.
This deletes the directory with the given name.
@raise: Any exception os.readlink() may raise, or
ValueError if the lock is not owned by this process.
"""
pid = readlink(self.name)
if int(pid) != os.getpid():
raise ValueError("Lock %r not owned by this process" % (self.name,))
rmlink(self.name)
self.locked = False
def isLocked(name):
"""Determine if the lock of the given name is held or not.
@type name: C{str}
@param name: The filesystem path to the lock to test
@rtype: C{bool}
@return: True if the lock is held, False otherwise.
"""
l = FilesystemLock(name)
result = None
try:
result = l.lock()
finally:
if result:
l.unlock()
return not result
__all__ = ['FilesystemLock', 'isLocked'] | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/python/lockfile.py | lockfile.py |
#
"""
Dynamic pseudo-scoping for Python.
Call functions with context.call({key: value}, func); func and
functions that it calls will be able to use 'context.get(key)' to
retrieve 'value'.
This is thread-safe.
"""
try:
from threading import local
except ImportError:
local = None
from twisted.python import threadable
defaultContextDict = {}
setDefault = defaultContextDict.__setitem__
class ContextTracker:
def __init__(self):
self.contexts = [defaultContextDict]
def callWithContext(self, ctx, func, *args, **kw):
newContext = self.contexts[-1].copy()
newContext.update(ctx)
self.contexts.append(newContext)
try:
return func(*args,**kw)
finally:
self.contexts.pop()
def getContext(self, key, default=None):
return self.contexts[-1].get(key, default)
class _ThreadedContextTracker:
def __init__(self):
self.threadId = threadable.getThreadID
self.contextPerThread = {}
def currentContext(self):
tkey = self.threadId()
try:
return self.contextPerThread[tkey]
except KeyError:
ct = self.contextPerThread[tkey] = ContextTracker()
return ct
def callWithContext(self, ctx, func, *args, **kw):
return self.currentContext().callWithContext(ctx, func, *args, **kw)
def getContext(self, key, default=None):
return self.currentContext().getContext(key, default)
class _TLSContextTracker(_ThreadedContextTracker):
def __init__(self):
self.storage = local()
def currentContext(self):
try:
return self.storage.ct
except AttributeError:
ct = self.storage.ct = ContextTracker()
return ct
if local is None:
ThreadedContextTracker = _ThreadedContextTracker
else:
ThreadedContextTracker = _TLSContextTracker
def installContextTracker(ctr):
global theContextTracker
global call
global get
theContextTracker = ctr
call = theContextTracker.callWithContext
get = theContextTracker.getContext
installContextTracker(ThreadedContextTracker()) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/python/context.py | context.py |
import sys, os
class IncomparableVersions(TypeError):
"""
Two versions could not be compared.
"""
class Version(object):
"""
An object that represents a three-part version number.
If running from an svn checkout, include the revision number in
the version string.
"""
def __init__(self, package, major, minor, micro):
self.package = package
self.major = major
self.minor = minor
self.micro = micro
def short(self):
"""
Return a string in canonical short version format,
<major>.<minor>.<micro>[+rSVNVer].
"""
s = self.base()
svnver = self._getSVNVersion()
if svnver:
s += '+r'+svnver
return s
def base(self):
"""
Like L{short}, but without the +rSVNVer.
"""
return '%d.%d.%d' % (self.major,
self.minor,
self.micro)
def __repr__(self):
svnver = self._formatSVNVersion()
if svnver:
svnver = ' #' + svnver
return '%s(%r, %d, %d, %d)%s' % (
self.__class__.__name__,
self.package,
self.major,
self.minor,
self.micro,
svnver)
def __str__(self):
return '[%s, version %d.%d.%d%s]' % (
self.package,
self.major,
self.minor,
self.micro,
self._formatSVNVersion())
def __cmp__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
if self.package != other.package:
raise IncomparableVersions()
return cmp((self.major,
self.minor,
self.micro),
(other.major,
other.minor,
other.micro))
def _parseSVNEntries(self, entriesFile):
"""
Given a readable file object which represents a .svn/entries
file, return the revision as a string. If the file cannot be
parsed, return the string "Unknown".
"""
try:
from xml.dom.minidom import parse
doc = parse(entriesFile).documentElement
for node in doc.childNodes:
if hasattr(node, 'getAttribute'):
rev = node.getAttribute('revision')
if rev is not None:
return rev.encode('ascii')
except:
return "Unknown"
def _getSVNVersion(self):
"""
Figure out the SVN revision number based on the existance of
twisted/.svn/entries, and its contents. This requires parsing the
entries file and reading the first XML tag in the xml document that has
a revision="" attribute.
@return: None or string containing SVN Revision number.
"""
mod = sys.modules.get(self.package)
if mod:
ent = os.path.join(os.path.dirname(mod.__file__),
'.svn',
'entries')
if os.path.exists(ent):
return self._parseSVNEntries(open(ent))
def _formatSVNVersion(self):
ver = self._getSVNVersion()
if ver is None:
return ''
return ' (SVN r%s)' % (ver,) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/python/versions.py | versions.py |
from win32com.shell import shell
import pythoncom
import os
def open(filename):
"""Open an existing shortcut for reading.
@return: The shortcut object
@rtype: Shortcut
"""
sc=Shortcut()
sc.load(filename)
return sc
class Shortcut:
"""A shortcut on Win32.
>>> sc=Shortcut(path, arguments, description, workingdir, iconpath, iconidx)
@param path: Location of the target
@param arguments: If path points to an executable, optional arguments to
pass
@param description: Human-readable decription of target
@param workingdir: Directory from which target is launched
@param iconpath: Filename that contains an icon for the shortcut
@param iconidx: If iconpath is set, optional index of the icon desired
"""
def __init__(self,
path=None,
arguments=None,
description=None,
workingdir=None,
iconpath=None,
iconidx=0):
self._base = pythoncom.CoCreateInstance(
shell.CLSID_ShellLink, None,
pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink
)
data = map(None,
['"%s"' % os.path.abspath(path), arguments, description,
os.path.abspath(workingdir), os.path.abspath(iconpath)],
("SetPath", "SetArguments", "SetDescription",
"SetWorkingDirectory") )
for value, function in data:
if value and function:
# call function on each non-null value
getattr(self, function)(value)
if iconpath:
self.SetIconLocation(iconpath, iconidx)
def load( self, filename ):
"""Read a shortcut file from disk."""
self._base.QueryInterface(pythoncom.IID_IPersistFile).Load(filename)
def save( self, filename ):
"""Write the shortcut to disk.
The file should be named something.lnk.
"""
self._base.QueryInterface(pythoncom.IID_IPersistFile).Save(filename, 0)
def __getattr__( self, name ):
if name != "_base":
return getattr(self._base, name)
raise AttributeError, "%s instance has no attribute %s" % \
(self.__class__.__name__, name) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/python/shortcut.py | shortcut.py |
# System Imports
import string
### Public Interface
class HookError(Exception):
"An error which will fire when an invariant is violated."
def addPre(klass, name, func):
"""hook.addPre(klass, name, func) -> None
Add a function to be called before the method klass.name is invoked.
"""
_addHook(klass, name, PRE, func)
def addPost(klass, name, func):
"""hook.addPost(klass, name, func) -> None
Add a function to be called after the method klass.name is invoked.
"""
_addHook(klass, name, POST, func)
def removePre(klass, name, func):
"""hook.removePre(klass, name, func) -> None
Remove a function (previously registered with addPre) so that it
is no longer executed before klass.name.
"""
_removeHook(klass, name, PRE, func)
def removePost(klass, name, func):
"""hook.removePre(klass, name, func) -> None
Remove a function (previously registered with addPost) so that it
is no longer executed after klass.name.
"""
_removeHook(klass, name, POST, func)
### "Helper" functions.
hooked_func = """
import %(module)s
def %(name)s(*args, **kw):
klazz = %(module)s.%(klass)s
for preMethod in klazz.%(preName)s:
preMethod(*args, **kw)
try:
return klazz.%(originalName)s(*args, **kw)
finally:
for postMethod in klazz.%(postName)s:
postMethod(*args, **kw)
"""
_PRE = '__hook_pre_%s_%s_%s__'
_POST = '__hook_post_%s_%s_%s__'
_ORIG = '__hook_orig_%s_%s_%s__'
def _XXX(k,n,s):
"string manipulation garbage"
x = s % (string.replace(k.__module__,'.','_'), k.__name__, n)
return x
def PRE(k,n):
"(private) munging to turn a method name into a pre-hook-method-name"
return _XXX(k,n,_PRE)
def POST(k,n):
"(private) munging to turn a method name into a post-hook-method-name"
return _XXX(k,n,_POST)
def ORIG(k,n):
"(private) munging to turn a method name into an `original' identifier"
return _XXX(k,n,_ORIG)
def _addHook(klass, name, phase, func):
"(private) adds a hook to a method on a class"
_enhook(klass, name)
if not hasattr(klass, phase(klass, name)):
setattr(klass, phase(klass, name), [])
phaselist = getattr(klass, phase(klass, name))
phaselist.append(func)
def _removeHook(klass, name, phase, func):
"(private) removes a hook from a method on a class"
phaselistname = phase(klass, name)
if not hasattr(klass, ORIG(klass,name)):
raise HookError("no hooks present!")
phaselist = getattr(klass, phase(klass, name))
try: phaselist.remove(func)
except ValueError:
raise HookError("hook %s not found in removal list for %s"%
(name,klass))
if not getattr(klass, PRE(klass,name)) and not getattr(klass, POST(klass, name)):
_dehook(klass, name)
def _enhook(klass, name):
"(private) causes a certain method name to be hooked on a class"
if hasattr(klass, ORIG(klass, name)):
return
def newfunc(*args, **kw):
for preMethod in getattr(klass, PRE(klass, name)):
preMethod(*args, **kw)
try:
return getattr(klass, ORIG(klass, name))(*args, **kw)
finally:
for postMethod in getattr(klass, POST(klass, name)):
postMethod(*args, **kw)
try:
newfunc.func_name = name
except TypeError:
# Older python's don't let you do this
pass
oldfunc = getattr(klass, name).im_func
setattr(klass, ORIG(klass, name), oldfunc)
setattr(klass, PRE(klass, name), [])
setattr(klass, POST(klass, name), [])
setattr(klass, name, newfunc)
def _dehook(klass, name):
"(private) causes a certain method name no longer to be hooked on a class"
if not hasattr(klass, ORIG(klass, name)):
raise HookError("Cannot unhook!")
setattr(klass, name, getattr(klass, ORIG(klass,name)))
delattr(klass, PRE(klass,name))
delattr(klass, POST(klass,name))
delattr(klass, ORIG(klass,name)) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/python/hook.py | hook.py |
import warnings
from twisted.python import hook
class DummyLock(object):
"""
Hack to allow locks to be unpickled on an unthreaded system.
"""
def __reduce__(self):
return (unpickle_lock, ())
def unpickle_lock():
if threadingmodule is not None:
return XLock()
else:
return DummyLock()
unpickle_lock.__safe_for_unpickling__ = True
def _synchPre(self, *a, **b):
if '_threadable_lock' not in self.__dict__:
_synchLockCreator.acquire()
if '_threadable_lock' not in self.__dict__:
self.__dict__['_threadable_lock'] = XLock()
_synchLockCreator.release()
self._threadable_lock.acquire()
def _synchPost(self, *a, **b):
self._threadable_lock.release()
def synchronize(*klasses):
"""Make all methods listed in each class' synchronized attribute synchronized.
The synchronized attribute should be a list of strings, consisting of the
names of methods that must be synchronized. If we are running in threaded
mode these methods will be wrapped with a lock.
"""
if threadmodule is not None:
for klass in klasses:
for methodName in klass.synchronized:
hook.addPre(klass, methodName, _synchPre)
hook.addPost(klass, methodName, _synchPost)
def init(with_threads=1):
"""Initialize threading.
Don't bother calling this. If it needs to happen, it will happen.
"""
global threaded, _synchLockCreator, XLock
if with_threads:
if not threaded:
if threadmodule is not None:
threaded = True
class XLock(threadingmodule._RLock, object):
def __reduce__(self):
return (unpickle_lock, ())
_synchLockCreator = XLock()
else:
raise RuntimeError("Cannot initialize threading, platform lacks thread support")
else:
if threaded:
raise RuntimeError("Cannot uninitialize threads")
else:
pass
_dummyID = object()
def getThreadID():
if threadmodule is None:
return _dummyID
return threadmodule.get_ident()
def isInIOThread():
"""Are we in the thread responsable for I/O requests (the event loop)?
"""
return ioThread == getThreadID()
def registerAsIOThread():
"""Mark the current thread as responsable for I/O requests.
"""
global ioThread
ioThread = getThreadID()
ioThread = None
threaded = False
def whenThreaded(cb):
warnings.warn("threadable.whenThreaded is deprecated. "
"Use application-level logic instead.",
DeprecationWarning, stacklevel=2)
cb()
try:
import thread as threadmodule
import threading as threadingmodule
except ImportError:
threadmodule = None
threadingmodule = None
else:
init(True)
__all__ = ['isInIOThread', 'registerAsIOThread', 'getThreadID', 'XLock',
'whenThreaded'] | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/python/threadable.py | threadable.py |
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
"""Asynchronous-friendly error mechanism.
See L{Failure}.
"""
# System Imports
import sys
import linecache
import string
import inspect
from cStringIO import StringIO
import types
count = 0
traceupLength = 4
class DefaultException(Exception):
pass
def format_frames(frames, write, detail="default"):
"""Format and write frames.
@param frames: is a list of frames as used by Failure.frames, with
each frame being a list of
(funcName, fileName, lineNumber, locals.items(), globals.items())
@type frames: list
@param write: this will be called with formatted strings.
@type write: callable
@param detail: Three detail levels are available:
default, brief, and verbose.
@type detail: string
"""
if detail not in ('default', 'brief', 'verbose'):
raise ValueError, "Detail must be default, brief, or verbose. (not %r)" % (detail,)
w = write
if detail == "brief":
for method, filename, lineno, localVars, globalVars in frames:
w('%s:%s:%s\n' % (filename, lineno, method))
elif detail == "default":
for method, filename, lineno, localVars, globalVars in frames:
w( ' File "%s", line %s, in %s\n' % (filename, lineno, method))
w( ' %s\n' % string.strip(linecache.getline(filename, lineno)))
elif detail == "verbose":
for method, filename, lineno, localVars, globalVars in frames:
w("%s:%d: %s(...)\n" % (filename, lineno, method))
w(' [ Locals ]\n')
# Note: the repr(val) was (self.pickled and val) or repr(val)))
for name, val in localVars:
w(" %s : %s\n" % (name, repr(val)))
w(' ( Globals )\n')
for name, val in globalVars:
w(" %s : %s\n" % (name, repr(val)))
# slyphon: i have a need to check for this value in trial
# so I made it a module-level constant
EXCEPTION_CAUGHT_HERE = "--- <exception caught here> ---"
class NoCurrentExceptionError(Exception):
"""
Raised when trying to create a Failure from the current interpreter
exception state and there is no current exception state.
"""
class Failure:
"""A basic abstraction for an error that has occurred.
This is necessary because Python's built-in error mechanisms are
inconvenient for asynchronous communication.
@ivar value: The exception instance responsible for this failure.
@ivar type: The exception's class.
"""
pickled = 0
stack = None
def __init__(self, exc_value=None, exc_type=None, exc_tb=None):
"""Initialize me with an explanation of the error.
By default, this will use the current X{exception}
(L{sys.exc_info}()). However, if you want to specify a
particular kind of failure, you can pass an exception as an
argument.
"""
global count
count = count + 1
self.count = count
self.type = self.value = tb = None
#strings Exceptions/Failures are bad, mmkay?
if ((isinstance(exc_value, types.StringType) or
isinstance(exc_value, types.UnicodeType))
and exc_type is None):
import warnings
warnings.warn(
"Don't pass strings (like %r) to failure.Failure (replacing with a DefaultException)." %
exc_value, DeprecationWarning, stacklevel=2)
exc_value = DefaultException(exc_value)
stackOffset = 0
if exc_value is None:
self.type, self.value, tb = sys.exc_info()
if self.type is None:
raise NoCurrentExceptionError()
stackOffset = 1
elif exc_type is None:
if isinstance(exc_value, Exception):
self.type = exc_value.__class__
else: #allow arbitrary objects.
self.type = type(exc_value)
self.value = exc_value
else:
self.type = exc_type
self.value = exc_value
if isinstance(self.value, Failure):
self.__dict__ = self.value.__dict__
return
if tb is None:
if exc_tb:
tb = exc_tb
# else:
# log.msg("Erf, %r created with no traceback, %s %s." % (
# repr(self), repr(exc_value), repr(exc_type)))
# for s in traceback.format_stack():
# log.msg(s)
frames = self.frames = []
stack = self.stack = []
# added 2003-06-23 by Chris Armstrong. Yes, I actually have a
# use case where I need this traceback object, and I've made
# sure that it'll be cleaned up.
self.tb = tb
if tb:
f = tb.tb_frame
elif not isinstance(self.value, Failure):
# we don't do frame introspection since it's expensive,
# and if we were passed a plain exception with no
# traceback, it's not useful anyway
f = stackOffset = None
while stackOffset and f:
# This excludes this Failure.__init__ frame from the
# stack, leaving it to start with our caller instead.
f = f.f_back
stackOffset -= 1
# Keeps the *full* stack. Formerly in spread.pb.print_excFullStack:
#
# The need for this function arises from the fact that several
# PB classes have the peculiar habit of discarding exceptions
# with bareword "except:"s. This premature exception
# catching means tracebacks generated here don't tend to show
# what called upon the PB object.
while f:
localz = f.f_locals.copy()
if f.f_locals is f.f_globals:
globalz = {}
else:
globalz = f.f_globals.copy()
for d in globalz, localz:
if d.has_key("__builtins__"):
del d["__builtins__"]
stack.insert(0, [
f.f_code.co_name,
f.f_code.co_filename,
f.f_lineno,
localz.items(),
globalz.items(),
])
f = f.f_back
while tb is not None:
f = tb.tb_frame
localz = f.f_locals.copy()
if f.f_locals is f.f_globals:
globalz = {}
else:
globalz = f.f_globals.copy()
for d in globalz, localz:
if d.has_key("__builtins__"):
del d["__builtins__"]
frames.append([
f.f_code.co_name,
f.f_code.co_filename,
tb.tb_lineno,
localz.items(),
globalz.items(),
])
tb = tb.tb_next
if inspect.isclass(self.type) and issubclass(self.type, Exception):
parentCs = reflect.allYourBase(self.type)
self.parents = map(reflect.qual, parentCs)
self.parents.append(reflect.qual(self.type))
else:
self.parents = [self.type]
def trap(self, *errorTypes):
"""Trap this failure if its type is in a predetermined list.
This allows you to trap a Failure in an error callback. It will be
automatically re-raised if it is not a type that you expect.
The reason for having this particular API is because it's very useful
in Deferred errback chains:
| def _ebFoo(self, failure):
| r = failure.trap(Spam, Eggs)
| print 'The Failure is due to either Spam or Eggs!'
| if r == Spam:
| print 'Spam did it!'
| elif r == Eggs:
| print 'Eggs did it!'
If the failure is not a Spam or an Eggs, then the Failure
will be 'passed on' to the next errback.
@type errorTypes: L{Exception}
"""
error = self.check(*errorTypes)
if not error:
raise self
return error
def check(self, *errorTypes):
"""Check if this failure's type is in a predetermined list.
@type errorTypes: list of L{Exception} classes or
fully-qualified class names.
@returns: the matching L{Exception} type, or None if no match.
"""
for error in errorTypes:
err = error
if inspect.isclass(error) and issubclass(error, Exception):
err = reflect.qual(error)
if err in self.parents:
return error
return None
def raiseException(self):
"""
raise the original exception, preserving traceback
information if available.
"""
raise self.type, self.value, self.tb
def __repr__(self):
return "<%s %s>" % (self.__class__, self.type)
def __str__(self):
return "[Failure instance: %s]" % self.getBriefTraceback()
def __getstate__(self):
"""Avoid pickling objects in the traceback.
"""
if self.pickled:
return self.__dict__
c = self.__dict__.copy()
c['frames'] = [
[
v[0], v[1], v[2],
[(j[0], reflect.safe_repr(j[1])) for j in v[3]],
[(j[0], reflect.safe_repr(j[1])) for j in v[4]]
] for v in self.frames
]
# added 2003-06-23. See comment above in __init__
c['tb'] = None
if self.stack is not None:
# XXX: This is a band-aid. I can't figure out where these
# (failure.stack is None) instances are coming from.
c['stack'] = [
[
v[0], v[1], v[2],
[(j[0], reflect.safe_repr(j[1])) for j in v[3]],
[(j[0], reflect.safe_repr(j[1])) for j in v[4]]
] for v in self.stack
]
c['pickled'] = 1
return c
def cleanFailure(self):
"""Remove references to other objects, replacing them with strings.
"""
self.__dict__ = self.__getstate__()
def getErrorMessage(self):
"""Get a string of the exception which caused this Failure."""
if isinstance(self.value, Failure):
return self.value.getErrorMessage()
return reflect.safe_str(self.value)
def getBriefTraceback(self):
io = StringIO()
self.printBriefTraceback(file=io)
return io.getvalue()
def getTraceback(self, elideFrameworkCode=0, detail='default'):
io = StringIO()
self.printTraceback(file=io, elideFrameworkCode=elideFrameworkCode, detail=detail)
return io.getvalue()
def printTraceback(self, file=None, elideFrameworkCode=0, detail='default'):
"""Emulate Python's standard error reporting mechanism.
"""
if file is None: file = log.logerr
w = file.write
# Preamble
if detail == 'verbose':
w( '*--- Failure #%d%s---\n' %
(self.count,
(self.pickled and ' (pickled) ') or ' '))
elif detail == 'brief':
if self.frames:
hasFrames = 'Traceback'
else:
hasFrames = 'Traceback (failure with no frames)'
w("%s: %s: %s\n" % (hasFrames, self.type, self.value))
else:
w( 'Traceback (most recent call last):\n')
# Frames, formatted in appropriate style
if self.frames:
if not elideFrameworkCode:
format_frames(self.stack[-traceupLength:], w, detail)
w("%s\n" % (EXCEPTION_CAUGHT_HERE,))
format_frames(self.frames, w, detail)
elif not detail == 'brief':
# Yeah, it's not really a traceback, despite looking like one...
w("Failure: ")
# postamble, if any
if not detail == 'brief':
w("%s: %s\n" % (reflect.qual(self.type),
reflect.safe_str(self.value)))
# chaining
if isinstance(self.value, Failure):
# TODO: indentation for chained failures?
file.write(" (chained Failure)\n")
self.value.printTraceback(file, elideFrameworkCode, detail)
if detail == 'verbose':
w('*--- End of Failure #%d ---\n' % self.count)
def printBriefTraceback(self, file=None, elideFrameworkCode=0):
"""Print a traceback as densely as possible.
"""
self.printTraceback(file, elideFrameworkCode, detail='brief')
def printDetailedTraceback(self, file=None, elideFrameworkCode=0):
"""Print a traceback with detailed locals and globals information.
"""
self.printTraceback(file, elideFrameworkCode, detail='verbose')
# slyphon: make post-morteming exceptions tweakable
DO_POST_MORTEM = True
def _debuginit(self, exc_value=None, exc_type=None, exc_tb=None,
Failure__init__=Failure.__init__.im_func):
if (exc_value, exc_type, exc_tb) == (None, None, None):
exc = sys.exc_info()
if not exc[0] == self.__class__ and DO_POST_MORTEM:
print "Jumping into debugger for post-mortem of exception '%s':" % exc[1]
import pdb
pdb.post_mortem(exc[2])
Failure__init__(self, exc_value, exc_type, exc_tb)
def startDebugMode():
"""Enable debug hooks for Failures."""
Failure.__init__ = _debuginit
def visualtest():
def c():
1/0
def b():
c()
def a():
b()
def _frameworkCode(detailLevel, elideFrameworkCode):
try:
a()
except:
Failure().printTraceback(sys.stdout, detail=detailLevel, elideFrameworkCode=elideFrameworkCode)
def _moreFrameworkCode(*a, **kw):
return _frameworkCode(*a, **kw)
def frameworkCode(*a, **kw):
return _moreFrameworkCode(*a, **kw)
print 'Failure visual test case:'
for verbosity in ['brief', 'default', 'verbose']:
for truth in True, False:
print
print '----- next ----'
print 'detail: ',verbosity
print 'elideFrameworkCode:', truth
print
frameworkCode(verbosity, truth)
# Sibling imports - at the bottom and unqualified to avoid unresolvable
# circularity
import reflect, log
if __name__ == '__main__':
visualtest() | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/python/failure.py | failure.py |
# System imports
import os
import sys
import time
import imp
def shortPythonVersion():
hv = sys.hexversion
major = (hv & 0xff000000L) >> 24
minor = (hv & 0x00ff0000L) >> 16
teeny = (hv & 0x0000ff00L) >> 8
return "%s.%s.%s" % (major,minor,teeny)
knownPlatforms = {
'nt': 'win32',
'ce': 'win32',
'posix': 'posix',
'java': 'java',
'org.python.modules.os': 'java',
}
_timeFunctions = {
#'win32': time.clock,
'win32': time.time,
}
class Platform:
"""Gives us information about the platform we're running on"""
type = knownPlatforms.get(os.name)
seconds = staticmethod(_timeFunctions.get(type, time.time))
def __init__(self, name=None):
if name is not None:
self.type = knownPlatforms.get(name)
self.seconds = _timeFunctions.get(self.type, time.time)
def isKnown(self):
"""Do we know about this platform?"""
return self.type != None
def getType(self):
"""Return 'posix', 'win32' or 'java'"""
return self.type
def isMacOSX(self):
"""Return if we are runnng on Mac OS X."""
return sys.platform == "darwin"
def isWinNT(self):
"""Are we running in Windows NT?"""
if self.getType() == 'win32':
import _winreg
try:
k=_winreg.OpenKeyEx(_winreg.HKEY_LOCAL_MACHINE,
r'Software\Microsoft\Windows NT\CurrentVersion')
_winreg.QueryValueEx(k, 'SystemRoot')
return 1
except WindowsError:
return 0
# not windows NT
return 0
def isWindows(self):
return self.getType() == 'win32'
def supportsThreads(self):
"""Can threads be created?
"""
try:
return imp.find_module('thread')[0] is None
except ImportError:
return False
platform = Platform()
platformType = platform.getType()
seconds = platform.seconds | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/python/runtime.py | runtime.py |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.