code
stringlengths 501
5.19M
| package
stringlengths 2
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
#
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
"""
A miscellany of code used to run Trial tests.
Maintainer: Jonathan Lange <[email protected]>
"""
from __future__ import generators
import pdb, shutil, sets
import os, types, warnings, sys, inspect, imp
import random, doctest, time
from twisted.python import reflect, log, failure, modules
from twisted.python.util import dsu
from twisted.internet import defer, interfaces
from twisted.trial import util, unittest
from twisted.trial.itrial import ITestCase
pyunit = __import__('unittest')
def isPackage(module):
"""Given an object return True if the object looks like a package"""
if not isinstance(module, types.ModuleType):
return False
basename = os.path.splitext(os.path.basename(module.__file__))[0]
return basename == '__init__'
def isPackageDirectory(dirname):
"""Is the directory at path 'dirname' a Python package directory?
Returns the name of the __init__ file (it may have a weird extension)
if dirname is a package directory. Otherwise, returns False"""
for ext in zip(*imp.get_suffixes())[0]:
initFile = '__init__' + ext
if os.path.exists(os.path.join(dirname, initFile)):
return initFile
return False
def samefile(filename1, filename2):
"""
A hacky implementation of C{os.path.samefile}. Used by L{filenameToModule}
when the platform doesn't provide C{os.path.samefile}. Do not use this.
"""
return os.path.abspath(filename1) == os.path.abspath(filename2)
def filenameToModule(fn):
"""
Given a filename, do whatever possible to return a module object matching
that file.
If the file in question is a module in Python path, properly import and
return that module. Otherwise, load the source manually.
@param fn: A filename.
@return: A module object.
@raise ValueError: If C{fn} does not exist.
"""
if not os.path.exists(fn):
raise ValueError("%r doesn't exist" % (fn,))
try:
ret = reflect.namedAny(reflect.filenameToModuleName(fn))
except (ValueError, AttributeError):
# Couldn't find module. The file 'fn' is not in PYTHONPATH
return _importFromFile(fn)
# ensure that the loaded module matches the file
retFile = os.path.splitext(ret.__file__)[0] + '.py'
# not all platforms (e.g. win32) have os.path.samefile
same = getattr(os.path, 'samefile', samefile)
if os.path.isfile(fn) and not same(fn, retFile):
del sys.modules[ret.__name__]
ret = _importFromFile(fn)
return ret
def _importFromFile(fn, moduleName=None):
fn = _resolveDirectory(fn)
if not moduleName:
moduleName = os.path.splitext(os.path.split(fn)[-1])[0]
if moduleName in sys.modules:
return sys.modules[moduleName]
fd = open(fn, 'r')
try:
module = imp.load_source(moduleName, fn, fd)
finally:
fd.close()
return module
def _resolveDirectory(fn):
if os.path.isdir(fn):
initFile = isPackageDirectory(fn)
if initFile:
fn = os.path.join(fn, initFile)
else:
raise ValueError('%r is not a package directory' % (fn,))
return fn
def suiteVisit(suite, visitor):
"""
Visit each test in C{suite} with C{visitor}.
@param visitor: A callable which takes a single argument, the L{TestCase}
instance to visit.
@return: None
"""
for case in suite._tests:
visit = getattr(case, 'visit', None)
if visit is not None:
visit(visitor)
elif isinstance(case, pyunit.TestCase):
case = PyUnitTestCase(case)
case.visit(visitor)
elif isinstance(case, pyunit.TestSuite):
suiteVisit(case, visitor)
else:
case.visit(visitor)
class TestSuite(pyunit.TestSuite):
"""
Extend the standard library's C{TestSuite} with support for the visitor
pattern and a consistently overrideable C{run} method.
"""
visit = suiteVisit
def __call__(self, result):
return self.run(result)
def run(self, result):
"""
Call C{run} on every member of the suite.
"""
# we implement this because Python 2.3 unittest defines this code
# in __call__, whereas 2.4 defines the code in run.
for test in self._tests:
if result.shouldStop:
break
test(result)
return result
# When an error occurs outside of any test, the user will see this string
# in place of a test's name.
NOT_IN_TEST = "<not in test>"
class LoggedSuite(TestSuite):
"""
Any errors logged in this suite will be reported to the L{TestResult}
object.
"""
def run(self, result):
"""
Run the suite, storing all errors in C{result}. If an error is logged
while no tests are running, then it will be added as an error to
C{result}.
@param result: A L{TestResult} object.
"""
observer = unittest._logObserver
observer._add()
super(LoggedSuite, self).run(result)
observer._remove()
for error in observer.getErrors():
result.addError(TestHolder(NOT_IN_TEST), error)
observer.flushErrors()
class DocTestSuite(TestSuite):
"""
Behaves like doctest.DocTestSuite, but decorates individual TestCases so
they support visit and so that id() behaviour is meaningful and consistent
between Python versions.
"""
def __init__(self, testModule):
TestSuite.__init__(self)
suite = doctest.DocTestSuite(testModule)
for test in suite._tests: #yay encapsulation
self.addTest(DocTestCase(test))
class PyUnitTestCase(object):
"""
This class decorates the pyunit.TestCase class, mainly to work around the
differences between unittest in Python 2.3, 2.4, and 2.5. These
differences are::
- The way doctest unittests describe themselves
- Where the implementation of TestCase.run is (used to be in __call__)
- Where the test method name is kept (mangled-private or non-mangled
private variable)
It also implements visit, which we like.
"""
def __init__(self, test):
self._test = test
test.id = self.id
def id(self):
cls = self._test.__class__
tmn = getattr(self._test, '_TestCase__testMethodName', None)
if tmn is None:
# python2.5's 'unittest' module is more sensible; but different.
tmn = self._test._testMethodName
return (cls.__module__ + '.' + cls.__name__ + '.' +
tmn)
def __repr__(self):
return 'PyUnitTestCase<%r>'%(self.id(),)
def __call__(self, results):
return self._test(results)
def visit(self, visitor):
"""
Call the given visitor with the original, standard library, test case
that C{self} wraps. See L{unittest.TestCase.visit}.
"""
visitor(self._test)
def __getattr__(self, name):
return getattr(self._test, name)
class DocTestCase(PyUnitTestCase):
def id(self):
"""
In Python 2.4, doctests have correct id() behaviour. In Python 2.3,
id() returns 'runit'.
Here we override id() so that at least it will always contain the
fully qualified Python name of the doctest.
"""
return self._test.shortDescription()
class TrialSuite(TestSuite):
"""
Suite to wrap around every single test in a C{trial} run. Used internally
by Trial to set up things necessary for Trial tests to work, regardless of
what context they are run in.
"""
def __init__(self, tests=()):
suite = LoggedSuite(tests)
super(TrialSuite, self).__init__([suite])
def _bail(self):
from twisted.internet import reactor
d = defer.Deferred()
reactor.addSystemEventTrigger('after', 'shutdown',
lambda: d.callback(None))
reactor.fireSystemEvent('shutdown') # radix's suggestion
treactor = interfaces.IReactorThreads(reactor, None)
if treactor is not None:
treactor.suggestThreadPoolSize(0)
# As long as TestCase does crap stuff with the reactor we need to
# manually shutdown the reactor here, and that requires util.wait
# :(
# so that the shutdown event completes
unittest.TestCase('mktemp')._wait(d)
def run(self, result):
try:
TestSuite.run(self, result)
finally:
self._bail()
def name(thing):
"""
@param thing: an object from modules (instance of PythonModule,
PythonAttribute), a TestCase subclass, or an instance of a TestCase.
"""
if isTestCase(thing):
# TestCase subclass
theName = reflect.qual(thing)
else:
# thing from trial, or thing from modules.
# this monstrosity exists so that modules' objects do not have to
# implement id(). -jml
try:
theName = thing.id()
except AttributeError:
theName = thing.name
return theName
def isTestCase(obj):
"""
Returns C{True} if C{obj} is a class that contains test cases, C{False}
otherwise. Used to find all the tests in a module.
"""
try:
return ITestCase.implementedBy(obj)
except TypeError:
return False
except AttributeError:
# Working around a bug in zope.interface 3.1.0; this isn't the user's
# fault, so we won't emit a warning.
# See http://www.zope.org/Collectors/Zope3-dev/470.
return False
class TestHolder(object):
"""
Placeholder for a L{TestCase} inside a reporter. As far as a L{TestResult}
is concerned, this looks exactly like a unit test.
"""
def __init__(self, description):
"""
@param description: A string to be displayed L{TestResult}.
"""
self.description = description
def id(self):
return self.description
def shortDescription(self):
return self.description
class ErrorHolder(TestHolder):
"""
Used to insert arbitrary errors into a test suite run. Provides enough
methods to look like a C{TestCase}, however, when it is run, it simply adds
an error to the C{TestResult}. The most common use-case is for when a
module fails to import.
"""
def __init__(self, description, error):
"""
@param description: A string used by C{TestResult}s to identify this
error. Generally, this is the name of a module that failed to import.
@param error: The error to be added to the result. Can be an exc_info
tuple or a L{twisted.python.failure.Failure}.
"""
super(ErrorHolder, self).__init__(description)
self.error = error
def __repr__(self):
return "<ErrorHolder description=%r error=%r>" % (self.description,
self.error)
def run(self, result):
result.addError(self, self.error)
def __call__(self, result):
return self.run(result)
def countTestCases(self):
return 0
def visit(self, visitor):
"""
See L{unittest.TestCase.visit}.
"""
visitor(self)
class TestLoader(object):
"""
I find tests inside function, modules, files -- whatever -- then return
them wrapped inside a Test (either a L{TestSuite} or a L{TestCase}).
@ivar methodPrefix: A string prefix. C{TestLoader} will assume that all the
methods in a class that begin with C{methodPrefix} are test cases.
@ivar modulePrefix: A string prefix. Every module in a package that begins
with C{modulePrefix} is considered a module full of tests.
@ivar forceGarbageCollection: A flag applied to each C{TestCase} loaded.
See L{unittest.TestCase} for more information.
@ivar sorter: A key function used to sort C{TestCase}s, test classes,
modules and packages.
@ivar suiteFactory: A callable which is passed a list of tests (which
themselves may be suites of tests). Must return a test suite.
"""
methodPrefix = 'test'
modulePrefix = 'test_'
def __init__(self):
self.suiteFactory = TestSuite
self.sorter = name
self._importErrors = []
self.forceGarbageCollection = False
def sort(self, xs):
"""
Sort the given things using L{sorter}.
@param xs: A list of test cases, class or modules.
"""
return dsu(xs, self.sorter)
def findTestClasses(self, module):
"""Given a module, return all Trial test classes"""
classes = []
for name, val in inspect.getmembers(module):
if isTestCase(val):
classes.append(val)
return self.sort(classes)
def findByName(self, name):
"""
Return a Python object given a string describing it.
@param name: a string which may be either a filename or a
fully-qualified Python name.
@return: If C{name} is a filename, return the module. If C{name} is a
fully-qualified Python name, return the object it refers to.
"""
if os.path.exists(name):
return filenameToModule(name)
return reflect.namedAny(name)
def loadModule(self, module):
"""
Return a test suite with all the tests from a module.
Included are TestCase subclasses and doctests listed in the module's
__doctests__ module. If that's not good for you, put a function named
either C{testSuite} or C{test_suite} in your module that returns a
TestSuite, and I'll use the results of that instead.
If C{testSuite} and C{test_suite} are both present, then I'll use
C{testSuite}.
"""
## XXX - should I add an optional parameter to disable the check for
## a custom suite.
## OR, should I add another method
if not isinstance(module, types.ModuleType):
raise TypeError("%r is not a module" % (module,))
if hasattr(module, 'testSuite'):
return module.testSuite()
elif hasattr(module, 'test_suite'):
return module.test_suite()
suite = self.suiteFactory()
for testClass in self.findTestClasses(module):
suite.addTest(self.loadClass(testClass))
if not hasattr(module, '__doctests__'):
return suite
docSuite = self.suiteFactory()
for doctest in module.__doctests__:
docSuite.addTest(self.loadDoctests(doctest))
return self.suiteFactory([suite, docSuite])
loadTestsFromModule = loadModule
def loadClass(self, klass):
"""
Given a class which contains test cases, return a sorted list of
C{TestCase} instances.
"""
if not (isinstance(klass, type) or isinstance(klass, types.ClassType)):
raise TypeError("%r is not a class" % (klass,))
if not isTestCase(klass):
raise ValueError("%r is not a test case" % (klass,))
names = self.getTestCaseNames(klass)
tests = self.sort([self._makeCase(klass, self.methodPrefix+name)
for name in names])
return self.suiteFactory(tests)
loadTestsFromTestCase = loadClass
def getTestCaseNames(self, klass):
"""
Given a class that contains C{TestCase}s, return a list of names of
methods that probably contain tests.
"""
return reflect.prefixedMethodNames(klass, self.methodPrefix)
def loadMethod(self, method):
"""
Given a method of a C{TestCase} that represents a test, return a
C{TestCase} instance for that test.
"""
if not isinstance(method, types.MethodType):
raise TypeError("%r not a method" % (method,))
return self._makeCase(method.im_class, method.__name__)
def _makeCase(self, klass, methodName):
test = klass(methodName)
test.forceGarbageCollection = self.forceGarbageCollection
return test
def loadPackage(self, package, recurse=False):
"""
Load tests from a module object representing a package, and return a
TestSuite containing those tests.
Tests are only loaded from modules whose name begins with 'test_'
(or whatever C{modulePrefix} is set to).
@param package: a types.ModuleType object (or reasonable facsimilie
obtained by importing) which may contain tests.
@param recurse: A boolean. If True, inspect modules within packages
within the given package (and so on), otherwise, only inspect modules
in the package itself.
@raise: TypeError if 'package' is not a package.
@return: a TestSuite created with my suiteFactory, containing all the
tests.
"""
if not isPackage(package):
raise TypeError("%r is not a package" % (package,))
pkgobj = modules.getModule(package.__name__)
if recurse:
discovery = pkgobj.walkModules()
else:
discovery = pkgobj.iterModules()
discovered = []
for disco in discovery:
if disco.name.split(".")[-1].startswith(self.modulePrefix):
discovered.append(disco)
suite = self.suiteFactory()
for modinfo in self.sort(discovered):
try:
module = modinfo.load()
except:
thingToAdd = ErrorHolder(modinfo.name, failure.Failure())
else:
thingToAdd = self.loadModule(module)
suite.addTest(thingToAdd)
return suite
def loadDoctests(self, module):
"""
Return a suite of tests for all the doctests defined in C{module}.
@param module: A module object or a module name.
"""
if isinstance(module, str):
try:
module = reflect.namedAny(module)
except:
return ErrorHolder(module, failure.Failure())
if not inspect.ismodule(module):
warnings.warn("trial only supports doctesting modules")
return
return DocTestSuite(module)
def loadAnything(self, thing, recurse=False):
"""
Given a Python object, return whatever tests that are in it. Whatever
'in' might mean.
@param thing: A Python object. A module, method, class or package.
@param recurse: Whether or not to look in subpackages of packages.
Defaults to False.
@return: A C{TestCase} or C{TestSuite}.
"""
if isinstance(thing, types.ModuleType):
if isPackage(thing):
return self.loadPackage(thing, recurse)
return self.loadModule(thing)
elif isinstance(thing, types.ClassType):
return self.loadClass(thing)
elif isinstance(thing, type):
return self.loadClass(thing)
elif isinstance(thing, types.MethodType):
return self.loadMethod(thing)
raise TypeError("No loader for %r. Unrecognized type" % (thing,))
def loadByName(self, name, recurse=False):
"""
Given a string representing a Python object, return whatever tests
are in that object.
If C{name} is somehow inaccessible (e.g. the module can't be imported,
there is no Python object with that name etc) then return an
L{ErrorHolder}.
@param name: The fully-qualified name of a Python object.
"""
try:
thing = self.findByName(name)
except:
return ErrorHolder(name, failure.Failure())
return self.loadAnything(thing, recurse)
loadTestsFromName = loadByName
def loadByNames(self, names, recurse=False):
"""
Construct a TestSuite containing all the tests found in 'names', where
names is a list of fully qualified python names and/or filenames. The
suite returned will have no duplicate tests, even if the same object
is named twice.
"""
things = []
errors = []
for name in names:
try:
things.append(self.findByName(name))
except:
errors.append(ErrorHolder(name, failure.Failure()))
suites = [self.loadAnything(thing, recurse)
for thing in sets.Set(things)]
suites.extend(errors)
return self.suiteFactory(suites)
class DryRunVisitor(object):
"""
A visitor that makes a reporter think that every test visited has run
successfully.
"""
def __init__(self, reporter):
"""
@param reporter: A C{TestResult} object.
"""
self.reporter = reporter
def markSuccessful(self, testCase):
"""
Convince the reporter that this test has been run successfully.
"""
self.reporter.startTest(testCase)
self.reporter.addSuccess(testCase)
self.reporter.stopTest(testCase)
class TrialRunner(object):
"""
A specialised runner that the trial front end uses.
"""
DEBUG = 'debug'
DRY_RUN = 'dry-run'
def _getDebugger(self):
dbg = pdb.Pdb()
try:
import readline
except ImportError:
print "readline module not available"
hasattr(sys, 'exc_clear') and sys.exc_clear()
for path in ('.pdbrc', 'pdbrc'):
if os.path.exists(path):
try:
rcFile = file(path, 'r')
except IOError:
hasattr(sys, 'exc_clear') and sys.exc_clear()
else:
dbg.rcLines.extend(rcFile.readlines())
return dbg
def _setUpTestdir(self):
self._tearDownLogFile()
currentDir = os.getcwd()
testdir = os.path.normpath(os.path.abspath(self.workingDirectory))
if os.path.exists(testdir):
try:
shutil.rmtree(testdir)
except OSError, e:
print ("could not remove %r, caught OSError [Errno %s]: %s"
% (testdir, e.errno,e.strerror))
try:
os.rename(testdir,
os.path.abspath("_trial_temp_old%s"
% random.randint(0, 99999999)))
except OSError, e:
print ("could not rename path, caught OSError [Errno %s]: %s"
% (e.errno,e.strerror))
raise
os.mkdir(testdir)
os.chdir(testdir)
return currentDir
def _makeResult(self):
return self.reporterFactory(self.stream, self.tbformat, self.rterrors)
def __init__(self, reporterFactory,
mode=None,
logfile='test.log',
stream=sys.stdout,
profile=False,
tracebackFormat='default',
realTimeErrors=False,
workingDirectory=None):
self.reporterFactory = reporterFactory
self.logfile = logfile
self.mode = mode
self.stream = stream
self.tbformat = tracebackFormat
self.rterrors = realTimeErrors
self._result = None
self.workingDirectory = workingDirectory or '_trial_temp'
self._logFileObserver = None
self._logFileObject = None
self._logWarnings = False
if profile:
self.run = util.profiled(self.run, 'profile.data')
def _setUpLogging(self):
self._setUpLogFile()
self._setUpLogWarnings()
def _tearDownLogFile(self):
if self._logFileObserver is not None:
log.removeObserver(self._logFileObserver.emit)
self._logFileObserver = None
if self._logFileObject is not None:
self._logFileObject.close()
self._logFileObject = None
def _setUpLogFile(self):
self._tearDownLogFile()
if self.logfile == '-':
logFile = sys.stdout
else:
logFile = file(self.logfile, 'a')
self._logFileObject = logFile
self._logFileObserver = log.FileLogObserver(logFile)
log.startLoggingWithObserver(self._logFileObserver.emit, 0)
def _setUpLogWarnings(self):
if self._logWarnings:
return
def seeWarnings(x):
if x.has_key('warning'):
print
print x['format'] % x
log.addObserver(seeWarnings)
self._logWarnings = True
def run(self, test):
"""
Run the test or suite and return a result object.
"""
result = self._makeResult()
# decorate the suite with reactor cleanup and log starting
# This should move out of the runner and be presumed to be
# present
suite = TrialSuite([test])
startTime = time.time()
result.write("Running %d tests.\n", suite.countTestCases())
if self.mode == self.DRY_RUN:
suite.visit(DryRunVisitor(result).markSuccessful)
elif self.mode == self.DEBUG:
# open question - should this be self.debug() instead.
debugger = self._getDebugger()
oldDir = self._setUpTestdir()
try:
self._setUpLogging()
debugger.runcall(suite.run, result)
finally:
os.chdir(oldDir)
else:
oldDir = self._setUpTestdir()
try:
self._setUpLogging()
suite.run(result)
finally:
os.chdir(oldDir)
endTime = time.time()
result.printErrors()
result.writeln(result.separator)
result.writeln('Ran %d tests in %.3fs', result.testsRun,
endTime - startTime)
result.write('\n')
result.printSummary()
return result
def runUntilFailure(self, test):
"""
Repeatedly run C{test} until it fails.
"""
count = 0
while True:
count += 1
self.stream.write("Test Pass %d\n" % (count,))
result = self.run(test)
if result.testsRun == 0:
break
if not result.wasSuccessful():
break
return result | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/trial/runner.py | runner.py |
import sys, os
from twisted.trial import unittest
testModule = """
from twisted.trial import unittest
class FooTest(unittest.TestCase):
def testFoo(self):
pass
"""
dosModule = testModule.replace('\n', '\r\n')
testSample = """
'''This module is used by test_loader to test the Trial test loading
functionality. Do NOT change the number of tests in this module.
Do NOT change the names the tests in this module.
'''
import unittest as pyunit
from twisted.trial import unittest
class FooTest(unittest.TestCase):
def test_foo(self):
pass
def test_bar(self):
pass
class PyunitTest(pyunit.TestCase):
def test_foo(self):
pass
def test_bar(self):
pass
class NotATest(object):
def test_foo(self):
pass
class AlphabetTest(unittest.TestCase):
def test_a(self):
pass
def test_b(self):
pass
def test_c(self):
pass
"""
class PackageTest(unittest.TestCase):
files = [
('badpackage/__init__.py', 'frotz\n'),
('badpackage/test_module.py', ''),
('package2/__init__.py', ''),
('package2/test_module.py', 'import frotz\n'),
('package/__init__.py', ''),
('package/frotz.py', 'frotz\n'),
('package/test_bad_module.py',
'raise ZeroDivisionError("fake error")'),
('package/test_dos_module.py', dosModule),
('package/test_import_module.py', 'import frotz'),
('package/test_module.py', testModule),
('goodpackage/__init__.py', ''),
('goodpackage/test_sample.py', testSample),
('goodpackage/sub/__init__.py', ''),
('goodpackage/sub/test_sample.py', testSample)
]
def _toModuleName(self, filename):
name = os.path.splitext(filename)[0]
segs = name.split('/')
if segs[-1] == '__init__':
segs = segs[:-1]
return '.'.join(segs)
def getModules(self):
return map(self._toModuleName, zip(*self.files)[0])
def cleanUpModules(self):
modules = self.getModules()
modules.sort()
modules.reverse()
for module in modules:
try:
del sys.modules[module]
except KeyError:
pass
def createFiles(self, files, parentDir='.'):
for filename, contents in self.files:
filename = os.path.join(parentDir, filename)
self._createDirectory(filename)
fd = open(filename, 'w')
fd.write(contents)
fd.close()
def _createDirectory(self, filename):
directory = os.path.dirname(filename)
if not os.path.exists(directory):
os.makedirs(directory)
def setUp(self, parentDir=None):
if parentDir is None:
parentDir = self.mktemp()
self.parent = parentDir
self.createFiles(self.files, parentDir)
def tearDown(self):
self.cleanUpModules()
class SysPathManglingTest(PackageTest):
def setUp(self, parent=None):
self.oldPath = sys.path[:]
self.newPath = sys.path[:]
if parent is None:
parent = self.mktemp()
PackageTest.setUp(self, parent)
self.newPath.append(self.parent)
self.mangleSysPath(self.newPath)
def tearDown(self):
PackageTest.tearDown(self)
self.mangleSysPath(self.oldPath)
def mangleSysPath(self, pathVar):
sys.path[:] = pathVar | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/trial/test/packages.py | packages.py |
from twisted.trial import unittest, util
from twisted.internet import reactor, protocol, defer
class FoolishError(Exception):
pass
class TestFailureInSetUp(unittest.TestCase):
def setUp(self):
raise FoolishError, "I am a broken setUp method"
def test_noop(self):
pass
class TestFailureInTearDown(unittest.TestCase):
def tearDown(self):
raise FoolishError, "I am a broken tearDown method"
def test_noop(self):
pass
class TestFailureInSetUpClass(unittest.TestCase):
def setUpClass(self):
raise FoolishError, "I am a broken setUpClass method"
def test_noop(self):
pass
class TestFailureInTearDownClass(unittest.TestCase):
def tearDownClass(self):
raise FoolishError, "I am a broken setUp method"
def test_noop(self):
pass
class TestRegularFail(unittest.TestCase):
def test_fail(self):
self.fail("I fail")
def test_subfail(self):
self.subroutine()
def subroutine(self):
self.fail("I fail inside")
class TestFailureInDeferredChain(unittest.TestCase):
def test_fail(self):
d = defer.Deferred()
d.addCallback(self._later)
reactor.callLater(0, d.callback, None)
return d
def _later(self, res):
self.fail("I fail later")
class TestSkipTestCase(unittest.TestCase):
pass
TestSkipTestCase.skip = "skipping this test"
class TestSkipTestCase2(unittest.TestCase):
def setUpClass(self):
raise unittest.SkipTest, "thi stest is fukct"
def test_thisTestWillBeSkipped(self):
pass
class DelayedCall(unittest.TestCase):
hiddenExceptionMsg = "something blew up"
def go(self):
raise RuntimeError(self.hiddenExceptionMsg)
def testHiddenException(self):
"""
What happens if an error is raised in a DelayedCall and an error is
also raised in the test?
L{test_reporter.TestErrorReporting.testHiddenException} checks that
both errors get reported.
Note that this behaviour is deprecated. A B{real} test would return a
Deferred that got triggered by the callLater. This would guarantee the
delayed call error gets reported.
"""
reactor.callLater(0, self.go)
reactor.iterate(0.01)
self.fail("Deliberate failure to mask the hidden exception")
testHiddenException.suppress = [util.suppress(
message=r'reactor\.iterate cannot be used.*',
category=DeprecationWarning)]
class ReactorCleanupTests(unittest.TestCase):
def test_leftoverPendingCalls(self):
def _():
print 'foo!'
reactor.callLater(10000.0, _)
class SocketOpenTest(unittest.TestCase):
def test_socketsLeftOpen(self):
f = protocol.Factory()
f.protocol = protocol.Protocol
reactor.listenTCP(0, f)
class TimingOutDeferred(unittest.TestCase):
def test_alpha(self):
pass
def test_deferredThatNeverFires(self):
self.methodCalled = True
d = defer.Deferred()
return d
def test_omega(self):
pass
def unexpectedException(self):
"""i will raise an unexpected exception...
... *CAUSE THAT'S THE KINDA GUY I AM*
>>> 1/0
""" | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/trial/test/erroneous.py | erroneous.py |
import socket
from twisted.names import dns
from twisted.internet import defer, error
from twisted.python import failure
EMPTY_RESULT = (), (), ()
class ResolverBase:
typeToMethod = None
def __init__(self):
self.typeToMethod = {}
for (k, v) in typeToMethod.items():
self.typeToMethod[k] = getattr(self, v)
def query(self, query, timeout = None):
try:
return self.typeToMethod[query.type](str(query.name), timeout)
except KeyError, e:
return defer.fail(failure.Failure(NotImplementedError(str(self.__class__) + " " + str(query.type))))
def _lookup(self, name, cls, type, timeout):
return defer.fail(NotImplementedError("ResolverBase._lookup"))
def lookupAddress(self, name, timeout = None):
"""
@see: twisted.names.client.lookupAddress
"""
return self._lookup(name, dns.IN, dns.A, timeout)
def lookupIPV6Address(self, name, timeout = None):
"""
@see: twisted.names.client.lookupIPV6Address
"""
return self._lookup(name, dns.IN, dns.AAAA, timeout)
def lookupAddress6(self, name, timeout = None):
"""
@see: twisted.names.client.lookupAddress6
"""
return self._lookup(name, dns.IN, dns.A6, timeout)
def lookupMailExchange(self, name, timeout = None):
"""
@see: twisted.names.client.lookupMailExchange
"""
return self._lookup(name, dns.IN, dns.MX, timeout)
def lookupNameservers(self, name, timeout = None):
"""
@see: twisted.names.client.lookupNameservers
"""
return self._lookup(name, dns.IN, dns.NS, timeout)
def lookupCanonicalName(self, name, timeout = None):
"""
@see: twisted.names.client.lookupCanonicalName
"""
return self._lookup(name, dns.IN, dns.CNAME, timeout)
def lookupMailBox(self, name, timeout = None):
"""
@see: twisted.names.client.lookupMailBox
"""
return self._lookup(name, dns.IN, dns.MB, timeout)
def lookupMailGroup(self, name, timeout = None):
"""
@see: twisted.names.client.lookupMailGroup
"""
return self._lookup(name, dns.IN, dns.MG, timeout)
def lookupMailRename(self, name, timeout = None):
"""
@see: twisted.names.client.lookupMailRename
"""
return self._lookup(name, dns.IN, dns.MR, timeout)
def lookupPointer(self, name, timeout = None):
"""
@see: twisted.names.client.lookupPointer
"""
return self._lookup(name, dns.IN, dns.PTR, timeout)
def lookupAuthority(self, name, timeout = None):
"""
@see: twisted.names.client.lookupAuthority
"""
return self._lookup(name, dns.IN, dns.SOA, timeout)
def lookupNull(self, name, timeout = None):
"""
@see: twisted.names.client.lookupNull
"""
return self._lookup(name, dns.IN, dns.NULL, timeout)
def lookupWellKnownServices(self, name, timeout = None):
"""
@see: twisted.names.client.lookupWellKnownServices
"""
return self._lookup(name, dns.IN, dns.WKS, timeout)
def lookupService(self, name, timeout = None):
"""
@see: twisted.names.client.lookupService
"""
return self._lookup(name, dns.IN, dns.SRV, timeout)
def lookupHostInfo(self, name, timeout = None):
"""
@see: twisted.names.client.lookupHostInfo
"""
return self._lookup(name, dns.IN, dns.HINFO, timeout)
def lookupMailboxInfo(self, name, timeout = None):
"""
@see: twisted.names.client.lookupMailboxInfo
"""
return self._lookup(name, dns.IN, dns.MINFO, timeout)
def lookupText(self, name, timeout = None):
"""
@see: twisted.names.client.lookupText
"""
return self._lookup(name, dns.IN, dns.TXT, timeout)
def lookupResponsibility(self, name, timeout = None):
"""
@see: twisted.names.client.lookupResponsibility
"""
return self._lookup(name, dns.IN, dns.RP, timeout)
def lookupAFSDatabase(self, name, timeout = None):
"""
@see: twisted.names.client.lookupAFSDatabase
"""
return self._lookup(name, dns.IN, dns.AFSDB, timeout)
def lookupZone(self, name, timeout = None):
"""
@see: twisted.names.client.lookupZone
"""
return self._lookup(name, dns.IN, dns.AXFR, timeout)
def lookupAllRecords(self, name, timeout = None):
"""
@see: twisted.names.client.lookupAllRecords
"""
return self._lookup(name, dns.IN, dns.ALL_RECORDS, timeout)
def getHostByName(self, name, timeout = None, effort = 10):
"""
@see: twisted.names.client.getHostByName
"""
# XXX - respect timeout
return self.lookupAllRecords(name, timeout
).addCallback(self._cbRecords, name, effort
)
def _cbRecords(self, (ans, auth, add), name, effort):
result = extractRecord(self, dns.Name(name), ans + auth + add, effort)
if not result:
raise error.DNSLookupError(name)
return result
def extractRecord(resolver, name, answers, level = 10):
if not level:
return None
if hasattr(socket, 'inet_ntop'):
for r in answers:
if r.name == name and r.type == dns.A6:
return socket.inet_ntop(socket.AF_INET6, r.payload.address)
for r in answers:
if r.name == name and r.type == dns.AAAA:
return socket.inet_ntop(socket.AF_INET6, r.payload.address)
for r in answers:
if r.name == name and r.type == dns.A:
return socket.inet_ntop(socket.AF_INET, r.payload.address)
for r in answers:
if r.name == name and r.type == dns.CNAME:
result = extractRecord(resolver, r.payload.name, answers, level - 1)
if not result:
return resolver.getHostByName(str(r.payload.name), effort=level-1)
return result
# No answers, but maybe there's a hint at who we should be asking about this
for r in answers:
if r.type == dns.NS:
from twisted.names import client
r = client.Resolver(servers=[(str(r.payload.name), dns.PORT)])
return r.lookupAddress(str(name)
).addCallback(lambda (ans, auth, add): extractRecord(r, name, ans + auth + add, level - 1)
).addBoth(lambda passthrough: (r.protocol.transport.stopListening(), passthrough)[1])
typeToMethod = {
dns.A: 'lookupAddress',
dns.AAAA: 'lookupIPV6Address',
dns.A6: 'lookupAddress6',
dns.NS: 'lookupNameservers',
dns.CNAME: 'lookupCanonicalName',
dns.SOA: 'lookupAuthority',
dns.MB: 'lookupMailBox',
dns.MG: 'lookupMailGroup',
dns.MR: 'lookupMailRename',
dns.NULL: 'lookupNull',
dns.WKS: 'lookupWellKnownServices',
dns.PTR: 'lookupPointer',
dns.HINFO: 'lookupHostInfo',
dns.MINFO: 'lookupMailboxInfo',
dns.MX: 'lookupMailExchange',
dns.TXT: 'lookupText',
dns.RP: 'lookupResponsibility',
dns.AFSDB: 'lookupAFSDatabase',
dns.SRV: 'lookupService',
dns.AXFR: 'lookupZone',
dns.ALL_RECORDS: 'lookupAllRecords',
} | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/names/common.py | common.py |
from __future__ import generators
import sys
from twisted.python import log
from twisted.internet import defer
from twisted.names import dns
from twisted.names import common
def retry(t, p, *args):
assert t, "Timeout is required"
t = list(t)
def errback(failure):
failure.trap(defer.TimeoutError)
if not t:
return failure
return p.query(timeout=t.pop(0), *args
).addErrback(errback
)
return p.query(timeout=t.pop(0), *args
).addErrback(errback
)
class _DummyController:
def messageReceived(self, *args):
pass
class Resolver(common.ResolverBase):
def __init__(self, hints):
common.ResolverBase.__init__(self)
self.hints = hints
def _lookup(self, name, cls, type, timeout):
d = discoverAuthority(name, self.hints
).addCallback(self.discoveredAuthority, name, cls, type, timeout
)
return d
def discoveredAuthority(self, auth, name, cls, type, timeout):
from twisted.names import client
q = dns.Query(name, type, cls)
r = client.Resolver(servers=[(auth, dns.PORT)])
d = r.queryUDP([q], timeout)
d.addCallback(r.filterAnswers)
return d
def lookupNameservers(host, atServer, p=None):
# print 'Nameserver lookup for', host, 'at', atServer, 'with', p
if p is None:
p = dns.DNSDatagramProtocol(_DummyController())
p.noisy = False
return retry(
(1, 3, 11, 45), # Timeouts
p, # Protocol instance
(atServer, dns.PORT), # Server to query
[dns.Query(host, dns.NS, dns.IN)] # Question to ask
)
def lookupAddress(host, atServer, p=None):
# print 'Address lookup for', host, 'at', atServer, 'with', p
if p is None:
p = dns.DNSDatagramProtocol(_DummyController())
p.noisy = False
return retry(
(1, 3, 11, 45), # Timeouts
p, # Protocol instance
(atServer, dns.PORT), # Server to query
[dns.Query(host, dns.A, dns.IN)] # Question to ask
)
def extractAuthority(msg, cache):
records = msg.answers + msg.authority + msg.additional
nameservers = [r for r in records if r.type == dns.NS]
# print 'Records for', soFar, ':', records
# print 'NS for', soFar, ':', nameservers
if not nameservers:
return None, nameservers
if not records:
raise IOError("No records")
for r in records:
if r.type == dns.A:
cache[str(r.name)] = r.payload.dottedQuad()
for r in records:
if r.type == dns.NS:
if str(r.payload.name) in cache:
return cache[str(r.payload.name)], nameservers
for addr in records:
if addr.type == dns.A and addr.name == r.name:
return addr.payload.dottedQuad(), nameservers
return None, nameservers
def discoverAuthority(host, roots, cache=None, p=None):
if cache is None:
cache = {}
rootAuths = list(roots)
parts = host.rstrip('.').split('.')
parts.reverse()
authority = rootAuths.pop()
soFar = ''
for part in parts:
soFar = part + '.' + soFar
# print '///////', soFar, authority, p
msg = defer.waitForDeferred(lookupNameservers(soFar, authority, p))
yield msg
msg = msg.getResult()
newAuth, nameservers = extractAuthority(msg, cache)
if newAuth is not None:
# print "newAuth is not None"
authority = newAuth
else:
if nameservers:
r = str(nameservers[0].payload.name)
# print 'Recursively discovering authority for', r
authority = defer.waitForDeferred(discoverAuthority(r, roots, cache, p))
yield authority
authority = authority.getResult()
# print 'Discovered to be', authority, 'for', r
## else:
## # print 'Doing address lookup for', soFar, 'at', authority
## msg = defer.waitForDeferred(lookupAddress(soFar, authority, p))
## yield msg
## msg = msg.getResult()
## records = msg.answers + msg.authority + msg.additional
## addresses = [r for r in records if r.type == dns.A]
## if addresses:
## authority = addresses[0].payload.dottedQuad()
## else:
## raise IOError("Resolution error")
# print "Yielding authority", authority
yield authority
discoverAuthority = defer.deferredGenerator(discoverAuthority)
def makePlaceholder(deferred, name):
def placeholder(*args, **kw):
deferred.addCallback(lambda r: getattr(r, name)(*args, **kw))
return deferred
return placeholder
class DeferredResolver:
def __init__(self, resolverDeferred):
self.waiting = []
resolverDeferred.addCallback(self.gotRealResolver)
def gotRealResolver(self, resolver):
w = self.waiting
self.__dict__ = resolver.__dict__
self.__class__ = resolver.__class__
for d in w:
d.callback(resolver)
def __getattr__(self, name):
if name.startswith('lookup') or name in ('getHostByName', 'query'):
self.waiting.append(defer.Deferred())
return makePlaceholder(self.waiting[-1], name)
raise AttributeError(name)
def bootstrap(resolver):
"""Lookup the root nameserver addresses using the given resolver
Return a Resolver which will eventually become a C{root.Resolver}
instance that has references to all the root servers that we were able
to look up.
"""
domains = [chr(ord('a') + i) for i in range(13)]
# f = lambda r: (log.msg('Root server address: ' + str(r)), r)[1]
f = lambda r: r
L = [resolver.getHostByName('%s.root-servers.net' % d).addCallback(f) for d in domains]
d = defer.DeferredList(L)
d.addCallback(lambda r: Resolver([e[1] for e in r if e[0]]))
return DeferredResolver(d)
if __name__ == '__main__':
if len(sys.argv) < 2:
print 'Specify a domain'
else:
log.startLogging(sys.stdout)
from twisted.names.client import ThreadedResolver
r = bootstrap(ThreadedResolver())
d = r.lookupAddress(sys.argv[1])
d.addCallbacks(log.msg, log.err).addBoth(lambda _: reactor.stop())
from twisted.internet import reactor
reactor.run() | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/names/root.py | root.py |
import time
from zope.interface import implements
from twisted.names import dns
from twisted.python import failure, log
from twisted.internet import interfaces, defer
import common
class CacheResolver(common.ResolverBase):
"""A resolver that serves records from a local, memory cache."""
implements(interfaces.IResolver)
cache = None
def __init__(self, cache = None, verbose = 0):
common.ResolverBase.__init__(self)
if cache is None:
cache = {}
self.cache = cache
self.verbose = verbose
self.cancel = {}
def __setstate__(self, state):
self.__dict__ = state
now = time.time()
for (k, (when, (ans, add, ns))) in self.cache.items():
diff = now - when
for rec in ans + add + ns:
if rec.ttl < diff:
del self.cache[k]
break
def __getstate__(self):
for c in self.cancel.values():
c.cancel()
self.cancel.clear()
return self.__dict__
def _lookup(self, name, cls, type, timeout):
now = time.time()
q = dns.Query(name, type, cls)
try:
when, (ans, auth, add) = self.cache[q]
except KeyError:
if self.verbose > 1:
log.msg('Cache miss for ' + repr(name))
return defer.fail(failure.Failure(dns.DomainError(name)))
else:
if self.verbose:
log.msg('Cache hit for ' + repr(name))
diff = now - when
return defer.succeed((
[dns.RRHeader(str(r.name), r.type, r.cls, r.ttl - diff, r.payload) for r in ans],
[dns.RRHeader(str(r.name), r.type, r.cls, r.ttl - diff, r.payload) for r in auth],
[dns.RRHeader(str(r.name), r.type, r.cls, r.ttl - diff, r.payload) for r in add]
))
def lookupAllRecords(self, name, timeout = None):
return defer.fail(failure.Failure(dns.DomainError(name)))
def cacheResult(self, query, payload):
if self.verbose > 1:
log.msg('Adding %r to cache' % query)
self.cache[query] = (time.time(), payload)
if self.cancel.has_key(query):
self.cancel[query].cancel()
s = list(payload[0]) + list(payload[1]) + list(payload[2])
m = s[0].ttl
for r in s:
m = min(m, r.ttl)
from twisted.internet import reactor
self.cancel[query] = reactor.callLater(m, self.clearEntry, query)
def clearEntry(self, query):
del self.cache[query]
del self.cancel[query] | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/names/cache.py | cache.py |
# System imports
import warnings
import struct, random, types, socket
try:
import cStringIO as StringIO
except ImportError:
import StringIO
AF_INET6 = socket.AF_INET6
try:
from Crypto.Util import randpool
except ImportError:
for randSource in ('urandom',):
try:
f = file('/dev/' + randSource)
f.read(2)
f.close()
except:
pass
else:
def randomSource(r = file('/dev/' + randSource, 'rb').read):
return struct.unpack('H', r(2))[0]
break
else:
warnings.warn(
"PyCrypto not available - proceeding with non-cryptographically "
"secure random source",
RuntimeWarning,
1
)
def randomSource():
return random.randint(0, 65535)
else:
def randomSource(r = randpool.RandomPool().get_bytes):
return struct.unpack('H', r(2))[0]
from zope.interface import implements, Interface
# Twisted imports
from twisted.internet import protocol, defer
from twisted.python import log, failure
from twisted.python import util as tputil
PORT = 53
(A, NS, MD, MF, CNAME, SOA, MB, MG, MR, NULL, WKS, PTR, HINFO, MINFO, MX, TXT,
RP, AFSDB) = range(1, 19)
AAAA = 28
SRV = 33
A6 = 38
DNAME = 39
QUERY_TYPES = {
A: 'A',
NS: 'NS',
MD: 'MD',
MF: 'MF',
CNAME: 'CNAME',
SOA: 'SOA',
MB: 'MB',
MG: 'MG',
MR: 'MR',
NULL: 'NULL',
WKS: 'WKS',
PTR: 'PTR',
HINFO: 'HINFO',
MINFO: 'MINFO',
MX: 'MX',
TXT: 'TXT',
RP: 'RP',
AFSDB: 'AFSDB',
# 19 through 27? Eh, I'll get to 'em.
AAAA: 'AAAA',
SRV: 'SRV',
A6: 'A6',
DNAME: 'DNAME'
}
IXFR, AXFR, MAILB, MAILA, ALL_RECORDS = range(251, 256)
# "Extended" queries (Hey, half of these are deprecated, good job)
EXT_QUERIES = {
IXFR: 'IXFR',
AXFR: 'AXFR',
MAILB: 'MAILB',
MAILA: 'MAILA',
ALL_RECORDS: 'ALL_RECORDS'
}
REV_TYPES = dict([
(v, k) for (k, v) in QUERY_TYPES.items() + EXT_QUERIES.items()
])
IN, CS, CH, HS = range(1, 5)
ANY = 255
QUERY_CLASSES = {
IN: 'IN',
CS: 'CS',
CH: 'CH',
HS: 'HS',
ANY: 'ANY'
}
REV_CLASSES = dict([
(v, k) for (k, v) in QUERY_CLASSES.items()
])
# Opcodes
OP_QUERY, OP_INVERSE, OP_STATUS, OP_NOTIFY = range(4)
# Response Codes
OK, EFORMAT, ESERVER, ENAME, ENOTIMP, EREFUSED = range(6)
class IRecord(Interface):
"""An single entry in a zone of authority.
@cvar TYPE: An indicator of what kind of record this is.
"""
# Backwards compatibility aliases - these should be deprecated or something I
# suppose. -exarkun
from twisted.names.error import DomainError, AuthoritativeDomainError
from twisted.names.error import DNSQueryTimeoutError
def str2time(s):
suffixes = (
('S', 1), ('M', 60), ('H', 60 * 60), ('D', 60 * 60 * 24),
('W', 60 * 60 * 24 * 7), ('Y', 60 * 60 * 24 * 365)
)
if isinstance(s, types.StringType):
s = s.upper().strip()
for (suff, mult) in suffixes:
if s.endswith(suff):
return int(float(s[:-1]) * mult)
try:
s = int(s)
except ValueError:
raise ValueError, "Invalid time interval specifier: " + s
return s
def readPrecisely(file, l):
buff = file.read(l)
if len(buff) < l:
raise EOFError
return buff
class IEncodable(Interface):
"""
Interface for something which can be encoded to and decoded
from a file object.
"""
def encode(strio, compDict = None):
"""
Write a representation of this object to the given
file object.
@type strio: File-like object
@param strio: The stream to which to write bytes
@type compDict: C{dict} or C{None}
@param compDict: A dictionary of backreference addresses that have
have already been written to this stream and that may be used for
compression.
"""
def decode(strio, length = None):
"""
Reconstruct an object from data read from the given
file object.
@type strio: File-like object
@param strio: The stream from which bytes may be read
@type length: C{int} or C{None}
@param length: The number of bytes in this RDATA field. Most
implementations can ignore this value. Only in the case of
records similar to TXT where the total length is in no way
encoded in the data is it necessary.
"""
class Name:
implements(IEncodable)
def __init__(self, name=''):
assert isinstance(name, types.StringTypes), "%r is not a string" % (name,)
self.name = name
def encode(self, strio, compDict=None):
"""
Encode this Name into the appropriate byte format.
@type strio: file
@param strio: The byte representation of this Name will be written to
this file.
@type compDict: dict
@param compDict: dictionary of Names that have already been encoded
and whose addresses may be backreferenced by this Name (for the purpose
of reducing the message size).
"""
name = self.name
while name:
if compDict is not None:
if compDict.has_key(name):
strio.write(
struct.pack("!H", 0xc000 | compDict[name]))
return
else:
compDict[name] = strio.tell() + Message.headerSize
ind = name.find('.')
if ind > 0:
label, name = name[:ind], name[ind + 1:]
else:
label, name = name, ''
ind = len(label)
strio.write(chr(ind))
strio.write(label)
strio.write(chr(0))
def decode(self, strio, length = None):
"""
Decode a byte string into this Name.
@type strio: file
@param strio: Bytes will be read from this file until the full Name
is decoded.
@raise EOFError: Raised when there are not enough bytes available
from C{strio}.
"""
self.name = ''
off = 0
while 1:
l = ord(readPrecisely(strio, 1))
if l == 0:
if off > 0:
strio.seek(off)
return
if (l >> 6) == 3:
new_off = ((l&63) << 8
| ord(readPrecisely(strio, 1)))
if off == 0:
off = strio.tell()
strio.seek(new_off)
continue
label = readPrecisely(strio, l)
if self.name == '':
self.name = label
else:
self.name = self.name + '.' + label
def __eq__(self, other):
if isinstance(other, Name):
return str(self) == str(other)
return 0
def __hash__(self):
return hash(str(self))
def __str__(self):
return self.name
class Query:
"""
Represent a single DNS query.
@ivar name: The name about which this query is requesting information.
@ivar type: The query type.
@ivar cls: The query class.
"""
implements(IEncodable)
name = None
type = None
cls = None
def __init__(self, name='', type=A, cls=IN):
"""
@type name: C{str}
@param name: The name about which to request information.
@type type: C{int}
@param type: The query type.
@type cls: C{int}
@param cls: The query class.
"""
self.name = Name(name)
self.type = type
self.cls = cls
def encode(self, strio, compDict=None):
self.name.encode(strio, compDict)
strio.write(struct.pack("!HH", self.type, self.cls))
def decode(self, strio, length = None):
self.name.decode(strio)
buff = readPrecisely(strio, 4)
self.type, self.cls = struct.unpack("!HH", buff)
def __hash__(self):
return hash((str(self.name).lower(), self.type, self.cls))
def __cmp__(self, other):
return isinstance(other, Query) and cmp(
(str(self.name).lower(), self.type, self.cls),
(str(other.name).lower(), other.type, other.cls)
) or cmp(self.__class__, other.__class__)
def __str__(self):
t = QUERY_TYPES.get(self.type, EXT_QUERIES.get(self.type, 'UNKNOWN (%d)' % self.type))
c = QUERY_CLASSES.get(self.cls, 'UNKNOWN (%d)' % self.cls)
return '<Query %s %s %s>' % (self.name, t, c)
def __repr__(self):
return 'Query(%r, %r, %r)' % (str(self.name), self.type, self.cls)
class RRHeader:
"""
A resource record header.
@cvar fmt: C{str} specifying the byte format of an RR.
@ivar name: The name about which this reply contains information.
@ivar type: The query type of the original request.
@ivar cls: The query class of the original request.
@ivar ttl: The time-to-live for this record.
@ivar payload: An object that implements the IEncodable interface
@ivar auth: Whether this header is authoritative or not.
"""
implements(IEncodable)
fmt = "!HHIH"
name = None
type = None
cls = None
ttl = None
payload = None
rdlength = None
cachedResponse = None
def __init__(self, name='', type=A, cls=IN, ttl=0, payload=None, auth=False):
"""
@type name: C{str}
@param name: The name about which this reply contains information.
@type type: C{int}
@param type: The query type.
@type cls: C{int}
@param cls: The query class.
@type ttl: C{int}
@param ttl: Time to live for this record.
@type payload: An object implementing C{IEncodable}
@param payload: A Query Type specific data object.
"""
assert (payload is None) or (payload.TYPE == type)
self.name = Name(name)
self.type = type
self.cls = cls
self.ttl = ttl
self.payload = payload
self.auth = auth
def encode(self, strio, compDict=None):
self.name.encode(strio, compDict)
strio.write(struct.pack(self.fmt, self.type, self.cls, self.ttl, 0))
if self.payload:
prefix = strio.tell()
self.payload.encode(strio, compDict)
aft = strio.tell()
strio.seek(prefix - 2, 0)
strio.write(struct.pack('!H', aft - prefix))
strio.seek(aft, 0)
def decode(self, strio, length = None):
self.name.decode(strio)
l = struct.calcsize(self.fmt)
buff = readPrecisely(strio, l)
r = struct.unpack(self.fmt, buff)
self.type, self.cls, self.ttl, self.rdlength = r
def isAuthoritative(self):
return self.auth
def __str__(self):
t = QUERY_TYPES.get(self.type, EXT_QUERIES.get(self.type, 'UNKNOWN (%d)' % self.type))
c = QUERY_CLASSES.get(self.cls, 'UNKNOWN (%d)' % self.cls)
return '<RR name=%s type=%s class=%s ttl=%ds auth=%s>' % (self.name, t, c, self.ttl, self.auth and 'True' or 'False')
__repr__ = __str__
class SimpleRecord(tputil.FancyStrMixin, tputil.FancyEqMixin):
"""
A Resource Record which consists of a single RFC 1035 domain-name.
"""
TYPE = None
implements(IEncodable, IRecord)
name = None
showAttributes = (('name', 'name', '%s'), 'ttl')
compareAttributes = ('name', 'ttl')
def __init__(self, name='', ttl=None):
self.name = Name(name)
self.ttl = str2time(ttl)
def encode(self, strio, compDict = None):
self.name.encode(strio, compDict)
def decode(self, strio, length = None):
self.name = Name()
self.name.decode(strio)
def __hash__(self):
return hash(self.name)
# Kinds of RRs - oh my!
class Record_NS(SimpleRecord):
TYPE = NS
class Record_MD(SimpleRecord): # OBSOLETE
TYPE = MD
class Record_MF(SimpleRecord): # OBSOLETE
TYPE = MF
class Record_CNAME(SimpleRecord):
TYPE = CNAME
class Record_MB(SimpleRecord): # EXPERIMENTAL
TYPE = MB
class Record_MG(SimpleRecord): # EXPERIMENTAL
TYPE = MG
class Record_MR(SimpleRecord): # EXPERIMENTAL
TYPE = MR
class Record_PTR(SimpleRecord):
TYPE = PTR
class Record_DNAME(SimpleRecord):
TYPE = DNAME
class Record_A(tputil.FancyEqMixin):
implements(IEncodable, IRecord)
TYPE = A
address = None
compareAttributes = ('address', 'ttl')
def __init__(self, address='0.0.0.0', ttl=None):
address = socket.inet_aton(address)
self.address = address
self.ttl = str2time(ttl)
def encode(self, strio, compDict = None):
strio.write(self.address)
def decode(self, strio, length = None):
self.address = readPrecisely(strio, 4)
def __hash__(self):
return hash(self.address)
def __str__(self):
return '<A %s ttl=%s>' % (self.dottedQuad(), self.ttl)
def dottedQuad(self):
return socket.inet_ntoa(self.address)
class Record_SOA(tputil.FancyEqMixin, tputil.FancyStrMixin):
implements(IEncodable, IRecord)
compareAttributes = ('serial', 'mname', 'rname', 'refresh', 'expire', 'retry', 'ttl')
showAttributes = (('mname', 'mname', '%s'), ('rname', 'rname', '%s'), 'serial', 'refresh', 'retry', 'expire', 'minimum', 'ttl')
TYPE = SOA
def __init__(self, mname='', rname='', serial=0, refresh=0, retry=0, expire=0, minimum=0, ttl=None):
self.mname, self.rname = Name(mname), Name(rname)
self.serial, self.refresh = str2time(serial), str2time(refresh)
self.minimum, self.expire = str2time(minimum), str2time(expire)
self.retry = str2time(retry)
self.ttl = str2time(ttl)
def encode(self, strio, compDict = None):
self.mname.encode(strio, compDict)
self.rname.encode(strio, compDict)
strio.write(
struct.pack(
'!LlllL',
self.serial, self.refresh, self.retry, self.expire,
self.minimum
)
)
def decode(self, strio, length = None):
self.mname, self.rname = Name(), Name()
self.mname.decode(strio)
self.rname.decode(strio)
r = struct.unpack('!LlllL', readPrecisely(strio, 20))
self.serial, self.refresh, self.retry, self.expire, self.minimum = r
def __hash__(self):
return hash((
self.serial, self.mname, self.rname,
self.refresh, self.expire, self.retry
))
class Record_NULL: # EXPERIMENTAL
implements(IEncodable, IRecord)
TYPE = NULL
def __init__(self, payload=None, ttl=None):
self.payload = payload
self.ttl = str2time(ttl)
def encode(self, strio, compDict = None):
strio.write(self.payload)
def decode(self, strio, length = None):
self.payload = readPrecisely(strio, length)
def __hash__(self):
return hash(self.payload)
class Record_WKS(tputil.FancyEqMixin, tputil.FancyStrMixin): # OBSOLETE
implements(IEncodable, IRecord)
TYPE = WKS
compareAttributes = ('address', 'protocol', 'map', 'ttl')
showAttributes = ('address', 'protocol', 'ttl')
def __init__(self, address='0.0.0.0', protocol=0, map='', ttl=None):
self.address = socket.inet_aton(address)
self.protocol, self.map = protocol, map
self.ttl = str2time(ttl)
def encode(self, strio, compDict = None):
strio.write(self.address)
strio.write(struct.pack('!B', self.protocol))
strio.write(self.map)
def decode(self, strio, length = None):
self.address = readPrecisely(strio, 4)
self.protocol = struct.unpack('!B', readPrecisely(strio, 1))[0]
self.map = readPrecisely(strio, length - 5)
def __hash__(self):
return hash((self.address, self.protocol, self.map))
class Record_AAAA(tputil.FancyEqMixin): # OBSOLETE (or headed there)
implements(IEncodable, IRecord)
TYPE = AAAA
compareAttributes = ('address', 'ttl')
def __init__(self, address = '::', ttl=None):
self.address = socket.inet_pton(AF_INET6, address)
self.ttl = str2time(ttl)
def encode(self, strio, compDict = None):
strio.write(self.address)
def decode(self, strio, length = None):
self.address = readPrecisely(strio, 16)
def __hash__(self):
return hash(self.address)
def __str__(self):
return '<AAAA %s ttl=%s>' % (socket.inet_ntop(AF_INET6, self.address), self.ttl)
class Record_A6:
implements(IEncodable, IRecord)
TYPE = A6
def __init__(self, prefixLen=0, suffix='::', prefix='', ttl=None):
self.prefixLen = prefixLen
self.suffix = socket.inet_pton(AF_INET6, suffix)
self.prefix = Name(prefix)
self.bytes = int((128 - self.prefixLen) / 8.0)
self.ttl = str2time(ttl)
def encode(self, strio, compDict = None):
strio.write(struct.pack('!B', self.prefixLen))
if self.bytes:
strio.write(self.suffix[-self.bytes:])
if self.prefixLen:
# This may not be compressed
self.prefix.encode(strio, None)
def decode(self, strio, length = None):
self.prefixLen = struct.unpack('!B', readPrecisely(strio, 1))[0]
self.bytes = int((128 - self.prefixLen) / 8.0)
if self.bytes:
self.suffix = '\x00' * (16 - self.bytes) + readPrecisely(strio, self.bytes)
if self.prefixLen:
self.prefix.decode(strio)
def __eq__(self, other):
if isinstance(other, Record_A6):
return (self.prefixLen == other.prefixLen and
self.suffix[-self.bytes:] == other.suffix[-self.bytes:] and
self.prefix == other.prefix and
self.ttl == other.ttl)
return 0
def __hash__(self):
return hash((self.prefixLen, self.suffix[-self.bytes:], self.prefix))
def __str__(self):
return '<A6 %s %s (%d) ttl=%s>' % (
self.prefix,
socket.inet_ntop(AF_INET6, self.suffix),
self.prefixLen, self.ttl
)
class Record_SRV(tputil.FancyEqMixin, tputil.FancyStrMixin): # EXPERIMENTAL
implements(IEncodable, IRecord)
TYPE = SRV
compareAttributes = ('priority', 'weight', 'target', 'port', 'ttl')
showAttributes = ('priority', 'weight', ('target', 'target', '%s'), 'port', 'ttl')
def __init__(self, priority=0, weight=0, port=0, target='', ttl=None):
self.priority = int(priority)
self.weight = int(weight)
self.port = int(port)
self.target = Name(target)
self.ttl = str2time(ttl)
def encode(self, strio, compDict = None):
strio.write(struct.pack('!HHH', self.priority, self.weight, self.port))
# This can't be compressed
self.target.encode(strio, None)
def decode(self, strio, length = None):
r = struct.unpack('!HHH', readPrecisely(strio, struct.calcsize('!HHH')))
self.priority, self.weight, self.port = r
self.target = Name()
self.target.decode(strio)
def __hash__(self):
return hash((self.priority, self.weight, self.port, self.target))
class Record_AFSDB(tputil.FancyStrMixin, tputil.FancyEqMixin):
implements(IEncodable, IRecord)
TYPE = AFSDB
compareAttributes = ('subtype', 'hostname', 'ttl')
showAttributes = ('subtype', ('hostname', 'hostname', '%s'), 'ttl')
def __init__(self, subtype=0, hostname='', ttl=None):
self.subtype = int(subtype)
self.hostname = Name(hostname)
self.ttl = str2time(ttl)
def encode(self, strio, compDict = None):
strio.write(struct.pack('!H', self.subtype))
self.hostname.encode(strio, compDict)
def decode(self, strio, length = None):
r = struct.unpack('!H', readPrecisely(strio, struct.calcsize('!H')))
self.subtype, = r
self.hostname.decode(strio)
def __hash__(self):
return hash((self.subtype, self.hostname))
class Record_RP(tputil.FancyEqMixin, tputil.FancyStrMixin):
implements(IEncodable, IRecord)
TYPE = RP
compareAttributes = ('mbox', 'txt', 'ttl')
showAttributes = (('mbox', 'mbox', '%s'), ('txt', 'txt', '%s'), 'ttl')
def __init__(self, mbox='', txt='', ttl=None):
self.mbox = Name(mbox)
self.txt = Name(txt)
self.ttl = str2time(ttl)
def encode(self, strio, compDict = None):
self.mbox.encode(strio, compDict)
self.txt.encode(strio, compDict)
def decode(self, strio, length = None):
self.mbox = Name()
self.txt = Name()
self.mbox.decode(strio)
self.txt.decode(strio)
def __hash__(self):
return hash((self.mbox, self.txt))
class Record_HINFO(tputil.FancyStrMixin):
implements(IEncodable, IRecord)
TYPE = HINFO
showAttributes = ('cpu', 'os', 'ttl')
def __init__(self, cpu='', os='', ttl=None):
self.cpu, self.os = cpu, os
self.ttl = str2time(ttl)
def encode(self, strio, compDict = None):
strio.write(struct.pack('!B', len(self.cpu)) + self.cpu)
strio.write(struct.pack('!B', len(self.os)) + self.os)
def decode(self, strio, length = None):
cpu = struct.unpack('!B', readPrecisely(strio, 1))[0]
self.cpu = readPrecisely(strio, cpu)
os = struct.unpack('!B', readPrecisely(strio, 1))[0]
self.os = readPrecisely(strio, os)
def __eq__(self, other):
if isinstance(other, Record_HINFO):
return (self.os.lower() == other.os.lower() and
self.cpu.lower() == other.cpu.lower() and
self.ttl == other.ttl)
return 0
def __hash__(self):
return hash((self.os.lower(), self.cpu.lower()))
class Record_MINFO(tputil.FancyEqMixin, tputil.FancyStrMixin): # EXPERIMENTAL
implements(IEncodable, IRecord)
TYPE = MINFO
rmailbx = None
emailbx = None
compareAttributes = ('rmailbx', 'emailbx', 'ttl')
showAttributes = (('rmailbx', 'responsibility', '%s'),
('emailbx', 'errors', '%s'),
'ttl')
def __init__(self, rmailbx='', emailbx='', ttl=None):
self.rmailbx, self.emailbx = Name(rmailbx), Name(emailbx)
self.ttl = str2time(ttl)
def encode(self, strio, compDict = None):
self.rmailbx.encode(strio, compDict)
self.emailbx.encode(strio, compDict)
def decode(self, strio, length = None):
self.rmailbx, self.emailbx = Name(), Name()
self.rmailbx.decode(strio)
self.emailbx.decode(strio)
def __hash__(self):
return hash((self.rmailbx, self.emailbx))
class Record_MX(tputil.FancyStrMixin, tputil.FancyEqMixin):
implements(IEncodable, IRecord)
TYPE = MX
compareAttributes = ('preference', 'name', 'ttl')
showAttributes = ('preference', ('name', 'name', '%s'), 'ttl')
def __init__(self, preference=0, name='', ttl=None, **kwargs):
self.preference, self.name = int(preference), Name(kwargs.get('exchange', name))
self.ttl = str2time(ttl)
def encode(self, strio, compDict = None):
strio.write(struct.pack('!H', self.preference))
self.name.encode(strio, compDict)
def decode(self, strio, length = None):
self.preference = struct.unpack('!H', readPrecisely(strio, 2))[0]
self.name = Name()
self.name.decode(strio)
def exchange(self):
warnings.warn("use Record_MX.name instead", DeprecationWarning, stacklevel=2)
return self.name
exchange = property(exchange)
def __hash__(self):
return hash((self.preference, self.name))
# Oh god, Record_TXT how I hate thee.
class Record_TXT(tputil.FancyEqMixin, tputil.FancyStrMixin):
implements(IEncodable, IRecord)
TYPE = TXT
showAttributes = compareAttributes = ('data', 'ttl')
def __init__(self, *data, **kw):
self.data = list(data)
# arg man python sucks so bad
self.ttl = str2time(kw.get('ttl', None))
def encode(self, strio, compDict = None):
for d in self.data:
strio.write(struct.pack('!B', len(d)) + d)
def decode(self, strio, length = None):
soFar = 0
self.data = []
while soFar < length:
L = struct.unpack('!B', readPrecisely(strio, 1))[0]
self.data.append(readPrecisely(strio, L))
soFar += L + 1
if soFar != length:
log.msg(
"Decoded %d bytes in TXT record, but rdlength is %d" % (
soFar, length
)
)
def __hash__(self):
return hash(tuple(self.data))
class Message:
headerFmt = "!H2B4H"
headerSize = struct.calcsize( headerFmt )
# Question, answer, additional, and nameserver lists
queries = answers = add = ns = None
def __init__(self, id=0, answer=0, opCode=0, recDes=0, recAv=0,
auth=0, rCode=OK, trunc=0, maxSize=512):
self.maxSize = maxSize
self.id = id
self.answer = answer
self.opCode = opCode
self.auth = auth
self.trunc = trunc
self.recDes = recDes
self.recAv = recAv
self.rCode = rCode
self.queries = []
self.answers = []
self.authority = []
self.additional = []
def addQuery(self, name, type=ALL_RECORDS, cls=IN):
"""
Add another query to this Message.
@type name: C{str}
@param name: The name to query.
@type type: C{int}
@param type: Query type
@type cls: C{int}
@param cls: Query class
"""
self.queries.append(Query(name, type, cls))
def encode(self, strio):
compDict = {}
body_tmp = StringIO.StringIO()
for q in self.queries:
q.encode(body_tmp, compDict)
for q in self.answers:
q.encode(body_tmp, compDict)
for q in self.authority:
q.encode(body_tmp, compDict)
for q in self.additional:
q.encode(body_tmp, compDict)
body = body_tmp.getvalue()
size = len(body) + self.headerSize
if self.maxSize and size > self.maxSize:
self.trunc = 1
body = body[:self.maxSize - self.headerSize]
byte3 = (( ( self.answer & 1 ) << 7 )
| ((self.opCode & 0xf ) << 3 )
| ((self.auth & 1 ) << 2 )
| ((self.trunc & 1 ) << 1 )
| ( self.recDes & 1 ) )
byte4 = ( ( (self.recAv & 1 ) << 7 )
| (self.rCode & 0xf ) )
strio.write(struct.pack(self.headerFmt, self.id, byte3, byte4,
len(self.queries), len(self.answers),
len(self.authority), len(self.additional)))
strio.write(body)
def decode(self, strio, length = None):
self.maxSize = 0
header = readPrecisely(strio, self.headerSize)
r = struct.unpack(self.headerFmt, header)
self.id, byte3, byte4, nqueries, nans, nns, nadd = r
self.answer = ( byte3 >> 7 ) & 1
self.opCode = ( byte3 >> 3 ) & 0xf
self.auth = ( byte3 >> 2 ) & 1
self.trunc = ( byte3 >> 1 ) & 1
self.recDes = byte3 & 1
self.recAv = ( byte4 >> 7 ) & 1
self.rCode = byte4 & 0xf
self.queries = []
for i in range(nqueries):
q = Query()
try:
q.decode(strio)
except EOFError:
return
self.queries.append(q)
items = ((self.answers, nans), (self.authority, nns), (self.additional, nadd))
for (l, n) in items:
self.parseRecords(l, n, strio)
def parseRecords(self, list, num, strio):
for i in range(num):
header = RRHeader()
try:
header.decode(strio)
except EOFError:
return
t = self.lookupRecordType(header.type)
if not t:
continue
header.payload = t(ttl=header.ttl)
try:
header.payload.decode(strio, header.rdlength)
except EOFError:
return
list.append(header)
def lookupRecordType(self, type):
return globals().get('Record_' + QUERY_TYPES.get(type, ''), None)
def toStr(self):
strio = StringIO.StringIO()
self.encode(strio)
return strio.getvalue()
def fromStr(self, str):
strio = StringIO.StringIO(str)
self.decode(strio)
class DNSDatagramProtocol(protocol.DatagramProtocol):
id = None
liveMessages = None
resends = None
timeout = 10
reissue = 2
def __init__(self, controller):
self.controller = controller
self.id = random.randrange(2 ** 10, 2 ** 15)
def pickID(self):
while 1:
self.id += randomSource() % (2 ** 10)
self.id %= 2 ** 16
if self.id not in self.liveMessages:
break
return self.id
def stopProtocol(self):
self.liveMessages = {}
self.resends = {}
self.transport = None
def startProtocol(self):
self.liveMessages = {}
self.resends = {}
def writeMessage(self, message, address):
self.transport.write(message.toStr(), address)
def startListening(self):
from twisted.internet import reactor
reactor.listenUDP(0, self, maxPacketSize=512)
def datagramReceived(self, data, addr):
m = Message()
try:
m.fromStr(data)
except EOFError:
log.msg("Truncated packet (%d bytes) from %s" % (len(data), addr))
return
except:
# Nothing should trigger this, but since we're potentially
# invoking a lot of different decoding methods, we might as well
# be extra cautious. Anything that triggers this is itself
# buggy.
log.err(failure.Failure(), "Unexpected decoding error")
return
if m.id in self.liveMessages:
d, canceller = self.liveMessages[m.id]
del self.liveMessages[m.id]
canceller.cancel()
# XXX we shouldn't need this hack of catching exceptioon on callback()
try:
d.callback(m)
except:
log.err()
else:
if m.id not in self.resends:
self.controller.messageReceived(m, self, addr)
def removeResend(self, id):
"""Mark message ID as no longer having duplication suppression."""
try:
del self.resends[id]
except:
pass
def query(self, address, queries, timeout = 10, id = None):
"""
Send out a message with the given queries.
@type address: C{tuple} of C{str} and C{int}
@param address: The address to which to send the query
@type queries: C{list} of C{Query} instances
@param queries: The queries to transmit
@rtype: C{Deferred}
"""
from twisted.internet import reactor
if not self.transport:
# XXX transport might not get created automatically, use callLater?
self.startListening()
if id is None:
id = self.pickID()
else:
self.resends[id] = 1
m = Message(id, recDes=1)
m.queries = queries
resultDeferred = defer.Deferred()
cancelCall = reactor.callLater(timeout, self._clearFailed, resultDeferred, id)
self.liveMessages[id] = (resultDeferred, cancelCall)
self.writeMessage(m, address)
return resultDeferred
def _clearFailed(self, deferred, id):
try:
del self.liveMessages[id]
except:
pass
deferred.errback(failure.Failure(DNSQueryTimeoutError(id)))
class DNSProtocol(protocol.Protocol):
id = None
liveMessages = None
length = None
buffer = ''
d = None
def __init__(self, controller):
self.controller = controller
self.liveMessages = {}
self.id = random.randrange(2 ** 10, 2 ** 15)
def pickID(self):
while 1:
self.id += randomSource() % (2 ** 10)
self.id %= 2 ** 16
if not self.liveMessages.has_key(self.id):
break
return self.id
def writeMessage(self, message):
s = message.toStr()
self.transport.write(struct.pack('!H', len(s)) + s)
def connectionMade(self):
self.controller.connectionMade(self)
def dataReceived(self, data):
self.buffer = self.buffer + data
while self.buffer:
if self.length is None and len(self.buffer) >= 2:
self.length = struct.unpack('!H', self.buffer[:2])[0]
self.buffer = self.buffer[2:]
if len(self.buffer) >= self.length:
myChunk = self.buffer[:self.length]
m = Message()
m.fromStr(myChunk)
try:
d = self.liveMessages[m.id]
except KeyError:
self.controller.messageReceived(m, self)
else:
del self.liveMessages[m.id]
try:
d.callback(m)
except:
log.err()
self.buffer = self.buffer[self.length:]
self.length = None
else:
break
def query(self, queries, timeout = None):
"""
Send out a message with the given queries.
@type queries: C{list} of C{Query} instances
@param queries: The queries to transmit
@rtype: C{Deferred}
"""
id = self.pickID()
d = self.liveMessages[id] = defer.Deferred()
if timeout is not None:
d.setTimeout(timeout)
m = Message(id, recDes=1)
m.queries = queries
self.writeMessage(m)
return d | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/names/dns.py | dns.py |
from __future__ import nested_scopes
import os
import errno
from zope.interface import implements
# Twisted imports
from twisted.python.runtime import platform
from twisted.internet import error, defer, protocol, interfaces
from twisted.python import log, failure
from twisted.names import dns, common
from twisted.names.error import DNSFormatError, DNSServerError, DNSNameError
from twisted.names.error import DNSNotImplementedError, DNSQueryRefusedError
from twisted.names.error import DNSUnknownError
class Resolver(common.ResolverBase):
implements(interfaces.IResolver)
index = 0
timeout = None
factory = None
servers = None
dynServers = ()
pending = None
protocol = None
connections = None
resolv = None
_lastResolvTime = None
_resolvReadInterval = 60
_errormap = {
dns.EFORMAT: DNSFormatError,
dns.ESERVER: DNSServerError,
dns.ENAME: DNSNameError,
dns.ENOTIMP: DNSNotImplementedError,
dns.EREFUSED: DNSQueryRefusedError}
def __init__(self, resolv = None, servers = None, timeout = (1, 3, 11, 45)):
"""
Construct a resolver which will query domain name servers listed in
the C{resolv.conf(5)}-format file given by C{resolv} as well as
those in the given C{servers} list. Servers are queried in a
round-robin fashion. If given, C{resolv} is periodically checked
for modification and re-parsed if it is noticed to have changed.
@type servers: C{list} of C{(str, int)} or C{None}
@param servers: If not C{None}, interpreted as a list of addresses of
domain name servers to attempt to use for this lookup. Addresses
should be in dotted-quad form. If specified, overrides C{resolv}.
@type resolv: C{str}
@param resolv: Filename to read and parse as a resolver(5)
configuration file.
@type timeout: Sequence of C{int}
@param timeout: Default number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@raise ValueError: Raised if no nameserver addresses can be found.
"""
common.ResolverBase.__init__(self)
self.timeout = timeout
if servers is None:
self.servers = []
else:
self.servers = servers
self.resolv = resolv
if not len(self.servers) and not resolv:
raise ValueError, "No nameservers specified"
self.factory = DNSClientFactory(self, timeout)
self.factory.noisy = 0 # Be quiet by default
self.protocol = dns.DNSDatagramProtocol(self)
self.protocol.noisy = 0 # You too
self.connections = []
self.pending = []
self.maybeParseConfig()
def __getstate__(self):
d = self.__dict__.copy()
d['connections'] = []
d['_parseCall'] = None
return d
def __setstate__(self, state):
self.__dict__.update(state)
self.maybeParseConfig()
def maybeParseConfig(self):
if self.resolv is None:
# Don't try to parse it, don't set up a call loop
return
try:
resolvConf = file(self.resolv)
except IOError, e:
if e.errno == errno.ENOENT:
# Missing resolv.conf is treated the same as an empty resolv.conf
self.parseConfig(())
else:
raise
else:
mtime = os.fstat(resolvConf.fileno()).st_mtime
if mtime != self._lastResolvTime:
log.msg('%s changed, reparsing' % (self.resolv,))
self._lastResolvTime = mtime
self.parseConfig(resolvConf)
# Check again in a little while
from twisted.internet import reactor
self._parseCall = reactor.callLater(self._resolvReadInterval, self.maybeParseConfig)
def parseConfig(self, resolvConf):
servers = []
for L in resolvConf:
L = L.strip()
if L.startswith('nameserver'):
resolver = (L.split()[1], dns.PORT)
servers.append(resolver)
log.msg("Resolver added %r to server list" % (resolver,))
elif L.startswith('domain'):
try:
self.domain = L.split()[1]
except IndexError:
self.domain = ''
self.search = None
elif L.startswith('search'):
try:
self.search = L.split()[1:]
except IndexError:
self.search = ''
self.domain = None
if not servers:
servers.append(('127.0.0.1', dns.PORT))
self.dynServers = servers
def pickServer(self):
"""
Return the address of a nameserver.
TODO: Weight servers for response time so faster ones can be
preferred.
"""
if not self.servers and not self.dynServers:
return None
serverL = len(self.servers)
dynL = len(self.dynServers)
self.index += 1
self.index %= (serverL + dynL)
if self.index < serverL:
return self.servers[self.index]
else:
return self.dynServers[self.index - serverL]
def connectionMade(self, protocol):
self.connections.append(protocol)
for (d, q, t) in self.pending:
self.queryTCP(q, t).chainDeferred(d)
del self.pending[:]
def messageReceived(self, message, protocol, address = None):
log.msg("Unexpected message (%d) received from %r" % (message.id, address))
def queryUDP(self, queries, timeout = None):
"""
Make a number of DNS queries via UDP.
@type queries: A C{list} of C{dns.Query} instances
@param queries: The queries to make.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: C{Deferred}
@raise C{twisted.internet.defer.TimeoutError}: When the query times
out.
"""
if timeout is None:
timeout = self.timeout
addresses = self.servers + list(self.dynServers)
if not addresses:
return defer.fail(IOError("No domain name servers available"))
used = addresses.pop()
return self.protocol.query(used, queries, timeout[0]
).addErrback(self._reissue, addresses, [used], queries, timeout
)
def _reissue(self, reason, addressesLeft, addressesUsed, query, timeout):
reason.trap(dns.DNSQueryTimeoutError)
# If there are no servers left to be tried, adjust the timeout
# to the next longest timeout period and move all the
# "used" addresses back to the list of addresses to try.
if not addressesLeft:
addressesLeft = addressesUsed
addressesLeft.reverse()
addressesUsed = []
timeout = timeout[1:]
# If all timeout values have been used, or the protocol has no
# transport, this query has failed. Tell the protocol we're
# giving up on it and return a terminal timeout failure to our
# caller.
if not timeout or self.protocol.transport is None:
self.protocol.removeResend(reason.value.id)
return failure.Failure(defer.TimeoutError(query))
# Get an address to try. Take it out of the list of addresses
# to try and put it ino the list of already tried addresses.
address = addressesLeft.pop()
addressesUsed.append(address)
# Issue a query to a server. Use the current timeout. Add this
# function as a timeout errback in case another retry is required.
d = self.protocol.query(address, query, timeout[0], reason.value.id)
d.addErrback(self._reissue, addressesLeft, addressesUsed, query, timeout)
return d
def queryTCP(self, queries, timeout = 10):
"""
Make a number of DNS queries via TCP.
@type queries: Any non-zero number of C{dns.Query} instances
@param queries: The queries to make.
@type timeout: C{int}
@param timeout: The number of seconds after which to fail.
@rtype: C{Deferred}
"""
if not len(self.connections):
address = self.pickServer()
if address is None:
return defer.fail(IOError("No domain name servers available"))
host, port = address
from twisted.internet import reactor
reactor.connectTCP(host, port, self.factory)
self.pending.append((defer.Deferred(), queries, timeout))
return self.pending[-1][0]
else:
return self.connections[0].query(queries, timeout)
def filterAnswers(self, message):
"""
Extract results from the given message.
If the message was truncated, re-attempt the query over TCP and return
a Deferred which will fire with the results of that query.
If the message's result code is not L{dns.OK}, return a Failure
indicating the type of error which occurred.
Otherwise, return a three-tuple of lists containing the results from
the answers section, the authority section, and the additional section.
"""
if message.trunc:
return self.queryTCP(message.queries).addCallback(self.filterAnswers)
if message.rCode != dns.OK:
return failure.Failure(self._errormap.get(message.rCode, DNSUnknownError)(message))
return (message.answers, message.authority, message.additional)
def _lookup(self, name, cls, type, timeout):
return self.queryUDP(
[dns.Query(name, type, cls)], timeout
).addCallback(self.filterAnswers)
# This one doesn't ever belong on UDP
def lookupZone(self, name, timeout = 10):
"""
Perform an AXFR request. This is quite different from usual
DNS requests. See http://cr.yp.to/djbdns/axfr-notes.html for
more information.
"""
address = self.pickServer()
if address is None:
return defer.fail(IOError('No domain name servers available'))
host, port = address
d = defer.Deferred()
controller = AXFRController(name, d)
factory = DNSClientFactory(controller, timeout)
factory.noisy = False #stfu
from twisted.internet import reactor
connector = reactor.connectTCP(host, port, factory)
controller.timeoutCall = reactor.callLater(timeout or 10,
self._timeoutZone,
d, controller,
connector,
timeout or 10)
return d.addCallback(self._cbLookupZone, connector)
def _timeoutZone(self, d, controller, connector, seconds):
connector.disconnect()
controller.timeoutCall = None
controller.deferred = None
d.errback(error.TimeoutError("Zone lookup timed out after %d seconds" % (seconds,)))
def _cbLookupZone(self, result, connector):
connector.disconnect()
return (result, [], [])
class AXFRController:
timeoutCall = None
def __init__(self, name, deferred):
self.name = name
self.deferred = deferred
self.soa = None
self.records = []
def connectionMade(self, protocol):
# dig saids recursion-desired to 0, so I will too
message = dns.Message(protocol.pickID(), recDes=0)
message.queries = [dns.Query(self.name, dns.AXFR, dns.IN)]
protocol.writeMessage(message)
def messageReceived(self, message, protocol):
# Caveat: We have to handle two cases: All records are in 1
# message, or all records are in N messages.
# According to http://cr.yp.to/djbdns/axfr-notes.html,
# 'authority' and 'additional' are always empty, and only
# 'answers' is present.
self.records.extend(message.answers)
if not self.records:
return
if not self.soa:
if self.records[0].type == dns.SOA:
#print "first SOA!"
self.soa = self.records[0]
if len(self.records) > 1 and self.records[-1].type == dns.SOA:
#print "It's the second SOA! We're done."
if self.timeoutCall is not None:
self.timeoutCall.cancel()
self.timeoutCall = None
if self.deferred is not None:
self.deferred.callback(self.records)
self.deferred = None
from twisted.internet.base import ThreadedResolver as _ThreadedResolverImpl
class ThreadedResolver(_ThreadedResolverImpl):
def __init__(self, reactor=None):
if reactor is None:
from twisted.internet import reactor
_ThreadedResolverImpl.__init__(self, reactor)
# warnings.warn("twisted.names.client.ThreadedResolver is deprecated, use XXX instead.")
class DNSClientFactory(protocol.ClientFactory):
def __init__(self, controller, timeout = 10):
self.controller = controller
self.timeout = timeout
def clientConnectionLost(self, connector, reason):
pass
def buildProtocol(self, addr):
p = dns.DNSProtocol(self.controller)
p.factory = self
return p
def createResolver(servers=None, resolvconf=None, hosts=None):
"""
Create and return a Resolver.
@type servers: C{list} of C{(str, int)} or C{None}
@param servers: If not C{None}, interpreted as a list of addresses of
domain name servers to attempt to use. Addresses should be in dotted-quad
form.
@type resolvconf: C{str} or C{None}
@param resolvconf: If not C{None}, on posix systems will be interpreted as
an alternate resolv.conf to use. Will do nothing on windows systems. If
C{None}, /etc/resolv.conf will be used.
@type hosts: C{str} or C{None}
@param hosts: If not C{None}, an alternate hosts file to use. If C{None}
on posix systems, /etc/hosts will be used. On windows, C:\windows\hosts
will be used.
@rtype: C{IResolver}
"""
from twisted.names import resolve, cache, root, hosts as hostsModule
if platform.getType() == 'posix':
if resolvconf is None:
resolvconf = '/etc/resolv.conf'
if hosts is None:
hosts = '/etc/hosts'
theResolver = Resolver(resolvconf, servers)
hostResolver = hostsModule.Resolver(hosts)
else:
if hosts is None:
hosts = r'c:\windows\hosts'
from twisted.internet import reactor
bootstrap = _ThreadedResolverImpl(reactor)
hostResolver = hostsModule.Resolver(hosts)
theResolver = root.bootstrap(bootstrap)
L = [hostResolver, cache.CacheResolver(), theResolver]
return resolve.ResolverChain(L)
theResolver = None
def getResolver():
"""
Get a Resolver instance.
Create twisted.names.client.theResolver if it is C{None}, and then return
that value.
@rtype: C{IResolver}
"""
global theResolver
if theResolver is None:
try:
theResolver = createResolver()
except ValueError:
theResolver = createResolver(servers=[('127.0.0.1', 53)])
return theResolver
def getHostByName(name, timeout=None, effort=10):
"""
Resolve a name to a valid ipv4 or ipv6 address.
Will errback with C{DNSQueryTimeoutError} on a timeout, C{DomainError} or
C{AuthoritativeDomainError} (or subclasses) on other errors.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@type effort: C{int}
@param effort: How many times CNAME and NS records to follow while
resolving this name.
@rtype: C{Deferred}
"""
return getResolver().getHostByName(name, timeout, effort)
def lookupAddress(name, timeout=None):
"""
Perform an A record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: C{Deferred}
"""
return getResolver().lookupAddress(name, timeout)
def lookupIPV6Address(name, timeout=None):
"""
Perform an AAAA record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: C{Deferred}
"""
return getResolver().lookupIPV6Address(name, timeout)
def lookupAddress6(name, timeout=None):
"""
Perform an A6 record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: C{Deferred}
"""
return getResolver().lookupAddress6(name, timeout)
def lookupMailExchange(name, timeout=None):
"""
Perform an MX record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: C{Deferred}
"""
return getResolver().lookupMailExchange(name, timeout)
def lookupNameservers(name, timeout=None):
"""
Perform an NS record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: C{Deferred}
"""
return getResolver().lookupNameservers(name, timeout)
def lookupCanonicalName(name, timeout=None):
"""
Perform a CNAME record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: C{Deferred}
"""
return getResolver().lookupCanonicalName(name, timeout)
def lookupMailBox(name, timeout=None):
"""
Perform an MB record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: C{Deferred}
"""
return getResolver().lookupMailBox(name, timeout)
def lookupMailGroup(name, timeout=None):
"""
Perform an MG record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: C{Deferred}
"""
return getResolver().lookupMailGroup(name, timeout)
def lookupMailRename(name, timeout=None):
"""
Perform an MR record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: C{Deferred}
"""
return getResolver().lookupMailRename(name, timeout)
def lookupPointer(name, timeout=None):
"""
Perform a PTR record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: C{Deferred}
"""
return getResolver().lookupPointer(name, timeout)
def lookupAuthority(name, timeout=None):
"""
Perform an SOA record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: C{Deferred}
"""
return getResolver().lookupAuthority(name, timeout)
def lookupNull(name, timeout=None):
"""
Perform a NULL record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: C{Deferred}
"""
return getResolver().lookupNull(name, timeout)
def lookupWellKnownServices(name, timeout=None):
"""
Perform a WKS record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: C{Deferred}
"""
return getResolver().lookupWellKnownServices(name, timeout)
def lookupService(name, timeout=None):
"""
Perform an SRV record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: C{Deferred}
"""
return getResolver().lookupService(name, timeout)
def lookupHostInfo(name, timeout=None):
"""
Perform a HINFO record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: C{Deferred}
"""
return getResolver().lookupHostInfo(name, timeout)
def lookupMailboxInfo(name, timeout=None):
"""
Perform an MINFO record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: C{Deferred}
"""
return getResolver().lookupMailboxInfo(name, timeout)
def lookupText(name, timeout=None):
"""
Perform a TXT record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: C{Deferred}
"""
return getResolver().lookupText(name, timeout)
def lookupResponsibility(name, timeout=None):
"""
Perform an RP record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: C{Deferred}
"""
return getResolver().lookupResponsibility(name, timeout)
def lookupAFSDatabase(name, timeout=None):
"""
Perform an AFSDB record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: C{Deferred}
"""
return getResolver().lookupAFSDatabase(name, timeout)
def lookupZone(name, timeout=None):
"""
Perform an AXFR record lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: C{int}
@param timeout: When this timeout expires, the query is considered failed.
@rtype: C{Deferred}
"""
# XXX: timeout here is not a list of ints, it is a single int.
return getResolver().lookupZone(name, timeout)
def lookupAllRecords(name, timeout=None):
"""
ALL_RECORD lookup.
@type name: C{str}
@param name: DNS name to resolve.
@type timeout: Sequence of C{int}
@param timeout: Number of seconds after which to reissue the query.
When the last timeout expires, the query is considered failed.
@rtype: C{Deferred}
"""
return getResolver().lookupAllRecords(name, timeout) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/names/client.py | client.py |
from __future__ import nested_scopes
import os
import time
from twisted.names import dns
from twisted.internet import defer
from twisted.python import failure
import common
def getSerial(filename = '/tmp/twisted-names.serial'):
"""Return a monotonically increasing (across program runs) integer.
State is stored in the given file. If it does not exist, it is
created with rw-/---/--- permissions.
"""
serial = time.strftime('%Y%m%d')
o = os.umask(0177)
try:
if not os.path.exists(filename):
f = file(filename, 'w')
f.write(serial + ' 0')
f.close()
finally:
os.umask(o)
serialFile = file(filename, 'r')
lastSerial, ID = serialFile.readline().split()
ID = (lastSerial == serial) and (int(ID) + 1) or 0
serialFile.close()
serialFile = file(filename, 'w')
serialFile.write('%s %d' % (serial, ID))
serialFile.close()
serial = serial + ('%02d' % (ID,))
return serial
#class LookupCacherMixin(object):
# _cache = None
#
# def _lookup(self, name, cls, type, timeout = 10):
# if not self._cache:
# self._cache = {}
# self._meth = super(LookupCacherMixin, self)._lookup
#
# if self._cache.has_key((name, cls, type)):
# return self._cache[(name, cls, type)]
# else:
# r = self._meth(name, cls, type, timeout)
# self._cache[(name, cls, type)] = r
# return r
class FileAuthority(common.ResolverBase):
"""An Authority that is loaded from a file."""
soa = None
records = None
def __init__(self, filename):
common.ResolverBase.__init__(self)
self.loadFile(filename)
self._cache = {}
def __setstate__(self, state):
self.__dict__ = state
# print 'setstate ', self.soa
def _lookup(self, name, cls, type, timeout = None):
cnames = []
results = []
authority = []
additional = []
default_ttl = max(self.soa[1].minimum, self.soa[1].expire)
domain_records = self.records.get(name.lower())
if domain_records:
for record in domain_records:
if record.ttl is not None:
ttl = record.ttl
else:
ttl = default_ttl
if record.TYPE == type or type == dns.ALL_RECORDS:
results.append(
dns.RRHeader(name, record.TYPE, dns.IN, ttl, record, auth=True)
)
elif record.TYPE == dns.NS and type != dns.ALL_RECORDS:
authority.append(
dns.RRHeader(name, record.TYPE, dns.IN, ttl, record, auth=True)
)
if record.TYPE == dns.CNAME:
cnames.append(
dns.RRHeader(name, record.TYPE, dns.IN, ttl, record, auth=True)
)
if not results:
results = cnames
for record in results + authority:
section = {dns.NS: additional, dns.CNAME: results, dns.MX: additional}.get(record.type)
if section is not None:
n = str(record.payload.name)
for rec in self.records.get(n.lower(), ()):
if rec.TYPE == dns.A:
section.append(
dns.RRHeader(n, dns.A, dns.IN, rec.ttl or default_ttl, rec, auth=True)
)
return defer.succeed((results, authority, additional))
else:
if name.lower().endswith(self.soa[0].lower()):
# We are the authority and we didn't find it. Goodbye.
return defer.fail(failure.Failure(dns.AuthoritativeDomainError(name)))
return defer.fail(failure.Failure(dns.DomainError(name)))
def lookupZone(self, name, timeout = 10):
if self.soa[0].lower() == name.lower():
# Wee hee hee hooo yea
default_ttl = max(self.soa[1].minimum, self.soa[1].expire)
if self.soa[1].ttl is not None:
soa_ttl = self.soa[1].ttl
else:
soa_ttl = default_ttl
results = [dns.RRHeader(self.soa[0], dns.SOA, dns.IN, soa_ttl, self.soa[1], auth=True)]
for (k, r) in self.records.items():
for rec in r:
if rec.ttl is not None:
ttl = rec.ttl
else:
ttl = default_ttl
if rec.TYPE != dns.SOA:
results.append(dns.RRHeader(k, rec.TYPE, dns.IN, ttl, rec, auth=True))
results.append(results[0])
return defer.succeed((results, (), ()))
return defer.fail(failure.Failure(dns.DomainError(name)))
def _cbAllRecords(self, results):
ans, auth, add = [], [], []
for res in results:
if res[0]:
ans.extend(res[1][0])
auth.extend(res[1][1])
add.extend(res[1][2])
return ans, auth, add
class PySourceAuthority(FileAuthority):
"""A FileAuthority that is built up from Python source code."""
def loadFile(self, filename):
g, l = self.setupConfigNamespace(), {}
execfile(filename, g, l)
if not l.has_key('zone'):
raise ValueError, "No zone defined in " + filename
self.records = {}
for rr in l['zone']:
if isinstance(rr[1], dns.Record_SOA):
self.soa = rr
self.records.setdefault(rr[0].lower(), []).append(rr[1])
def wrapRecord(self, type):
return lambda name, *arg, **kw: (name, type(*arg, **kw))
def setupConfigNamespace(self):
r = {}
items = dns.__dict__.iterkeys()
for record in [x for x in items if x.startswith('Record_')]:
type = getattr(dns, record)
f = self.wrapRecord(type)
r[record[len('Record_'):]] = f
return r
class BindAuthority(FileAuthority):
"""An Authority that loads BIND configuration files"""
def loadFile(self, filename):
self.origin = os.path.basename(filename) + '.' # XXX - this might suck
lines = open(filename).readlines()
lines = self.stripComments(lines)
lines = self.collapseContinuations(lines)
self.parseLines(lines)
def stripComments(self, lines):
return [
a.find(';') == -1 and a or a[:a.find(';')] for a in [
b.strip() for b in lines
]
]
def collapseContinuations(self, lines):
L = []
state = 0
for line in lines:
if state == 0:
if line.find('(') == -1:
L.append(line)
else:
L.append(line[:line.find('(')])
state = 1
else:
if line.find(')') != -1:
L[-1] += ' ' + line[:line.find(')')]
state = 0
else:
L[-1] += ' ' + line
lines = L
L = []
for line in lines:
L.append(line.split())
return filter(None, L)
def parseLines(self, lines):
TTL = 60 * 60 * 3
ORIGIN = self.origin
self.records = {}
for (line, index) in zip(lines, range(len(lines))):
if line[0] == '$TTL':
TTL = dns.str2time(line[1])
elif line[0] == '$ORIGIN':
ORIGIN = line[1]
elif line[0] == '$INCLUDE': # XXX - oh, fuck me
raise NotImplementedError('$INCLUDE directive not implemented')
elif line[0] == '$GENERATE':
raise NotImplementedError('$GENERATE directive not implemented')
else:
self.parseRecordLine(ORIGIN, TTL, line)
def addRecord(self, owner, ttl, type, domain, cls, rdata):
if not domain.endswith('.'):
domain = domain + '.' + owner
else:
domain = domain[:-1]
f = getattr(self, 'class_%s' % cls, None)
if f:
f(ttl, type, domain, rdata)
else:
raise NotImplementedError, "Record class %r not supported" % cls
def class_IN(self, ttl, type, domain, rdata):
record = getattr(dns, 'Record_%s' % type, None)
if record:
r = record(*rdata)
r.ttl = ttl
self.records.setdefault(domain.lower(), []).append(r)
print 'Adding IN Record', domain, ttl, r
if type == 'SOA':
self.soa = (domain, r)
else:
raise NotImplementedError, "Record type %r not supported" % type
#
# This file ends here. Read no further.
#
def parseRecordLine(self, origin, ttl, line):
MARKERS = dns.QUERY_CLASSES.values() + dns.QUERY_TYPES.values()
cls = 'IN'
owner = origin
if line[0] == '@':
line = line[1:]
owner = origin
# print 'default owner'
elif not line[0].isdigit() and line[0] not in MARKERS:
owner = line[0]
line = line[1:]
# print 'owner is ', owner
if line[0].isdigit() or line[0] in MARKERS:
domain = owner
owner = origin
# print 'woops, owner is ', owner, ' domain is ', domain
else:
domain = line[0]
line = line[1:]
# print 'domain is ', domain
if line[0] in dns.QUERY_CLASSES.values():
cls = line[0]
line = line[1:]
# print 'cls is ', cls
if line[0].isdigit():
ttl = int(line[0])
line = line[1:]
# print 'ttl is ', ttl
elif line[0].isdigit():
ttl = int(line[0])
line = line[1:]
# print 'ttl is ', ttl
if line[0] in dns.QUERY_CLASSES.values():
cls = line[0]
line = line[1:]
# print 'cls is ', cls
type = line[0]
# print 'type is ', type
rdata = line[1:]
# print 'rdata is ', rdata
self.addRecord(owner, ttl, type, domain, cls, rdata) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/names/authority.py | authority.py |
import random
from zope.interface import implements
from twisted.internet import error, interfaces
from twisted.names import client
class _SRVConnector_ClientFactoryWrapper:
def __init__(self, connector, wrappedFactory):
self.__connector = connector
self.__wrappedFactory = wrappedFactory
def startedConnecting(self, connector):
self.__wrappedFactory.startedConnecting(self.__connector)
def clientConnectionFailed(self, connector, reason):
self.__connector.connectionFailed(reason)
def clientConnectionLost(self, connector, reason):
self.__connector.connectionLost(reason)
def __getattr__(self, key):
return getattr(self.__wrappedFactory, key)
class SRVConnector:
"""A connector that looks up DNS SRV records. See RFC2782."""
implements(interfaces.IConnector)
stopAfterDNS=0
def __init__(self, reactor, service, domain, factory,
protocol='tcp', connectFuncName='connectTCP',
connectFuncArgs=(),
connectFuncKwArgs={},
):
self.reactor = reactor
self.service = service
self.domain = domain
self.factory = factory
self.protocol = protocol
self.connectFuncName = connectFuncName
self.connectFuncArgs = connectFuncArgs
self.connectFuncKwArgs = connectFuncKwArgs
self.connector = None
self.servers = None
self.orderedServers = None # list of servers already used in this round
def connect(self):
"""Start connection to remote server."""
self.factory.doStart()
self.factory.startedConnecting(self)
if not self.servers:
if self.domain is None:
self.connectionFailed(error.DNSLookupError("Domain is not defined."))
return
d = client.lookupService('_%s._%s.%s' % (self.service,
self.protocol,
self.domain))
d.addCallback(self._cbGotServers)
d.addCallback(lambda x, self=self: self._reallyConnect())
d.addErrback(self.connectionFailed)
elif self.connector is None:
self._reallyConnect()
else:
self.connector.connect()
def _cbGotServers(self, (answers, auth, add)):
if len(answers)==1 and answers[0].payload.target=='.':
# decidedly not available
raise error.DNSLookupError("Service %s not available for domain %s."
% (repr(self.service), repr(self.domain)))
self.servers = []
self.orderedServers = []
for a in answers:
self.orderedServers.append((a.payload.priority, a.payload.weight,
str(a.payload.target), a.payload.port))
def _serverCmp(self, a, b):
if a[0]!=b[0]:
return cmp(a[0], b[0])
else:
return cmp(a[1], b[1])
def pickServer(self):
assert self.servers is not None
assert self.orderedServers is not None
if not self.servers and not self.orderedServers:
# no SRV record, fall back..
return self.domain, self.service
if not self.servers and self.orderedServers:
# start new round
self.servers = self.orderedServers
self.orderedServers = []
assert self.servers
self.servers.sort(self._serverCmp)
minPriority=self.servers[0][0]
weightIndex = zip(xrange(len(self.servers)), [x[1] for x in self.servers
if x[0]==minPriority])
weightSum = reduce(lambda x, y: (None, x[1]+y[1]), weightIndex, (None, 0))[1]
rand = random.randint(0, weightSum)
for index, weight in weightIndex:
weightSum -= weight
if weightSum <= 0:
chosen = self.servers[index]
del self.servers[index]
self.orderedServers.append(chosen)
p, w, host, port = chosen
return host, port
raise RuntimeError, 'Impossible %s pickServer result.' % self.__class__.__name__
def _reallyConnect(self):
if self.stopAfterDNS:
self.stopAfterDNS=0
return
self.host, self.port = self.pickServer()
assert self.host is not None, 'Must have a host to connect to.'
assert self.port is not None, 'Must have a port to connect to.'
connectFunc = getattr(self.reactor, self.connectFuncName)
self.connector=connectFunc(
self.host, self.port,
_SRVConnector_ClientFactoryWrapper(self, self.factory),
*self.connectFuncArgs, **self.connectFuncKwArgs)
def stopConnecting(self):
"""Stop attempting to connect."""
if self.connector:
self.connector.stopConnecting()
else:
self.stopAfterDNS=1
def disconnect(self):
"""Disconnect whatever our are state is."""
if self.connector is not None:
self.connector.disconnect()
else:
self.stopConnecting()
def getDestination(self):
assert self.connector
return self.connector.getDestination()
def connectionFailed(self, reason):
self.factory.clientConnectionFailed(self, reason)
self.factory.doStop()
def connectionLost(self, reason):
self.factory.clientConnectionLost(self, reason)
self.factory.doStop() | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/names/srvconnect.py | srvconnect.py |
import os, traceback
from twisted.python import usage
from twisted.names import dns
from twisted.application import internet, service
from twisted.names import server
from twisted.names import authority
from twisted.names import secondary
class Options(usage.Options):
optParameters = [
["interface", "i", "", "The interface to which to bind"],
["port", "p", "53", "The port on which to listen"],
["resolv-conf", None, None,
"Override location of resolv.conf (implies --recursive)"],
["hosts-file", None, None, "Perform lookups with a hosts file"],
]
optFlags = [
["cache", "c", "Enable record caching"],
["recursive", "r", "Perform recursive lookups"],
["verbose", "v", "Log verbosely"],
]
zones = None
zonefiles = None
def __init__(self):
usage.Options.__init__(self)
self['verbose'] = 0
self.bindfiles = []
self.zonefiles = []
self.secondaries = []
def opt_pyzone(self, filename):
"""Specify the filename of a Python syntax zone definition"""
if not os.path.exists(filename):
raise usage.UsageError(filename + ": No such file")
self.zonefiles.append(filename)
def opt_bindzone(self, filename):
"""Specify the filename of a BIND9 syntax zone definition"""
if not os.path.exists(filename):
raise usage.UsageError(filename + ": No such file")
self.bindfiles.append(filename)
def opt_secondary(self, ip_domain):
"""Act as secondary for the specified domain, performing
zone transfers from the specified IP (IP/domain)
"""
args = ip_domain.split('/', 1)
if len(args) != 2:
raise usage.UsageError("Argument must be of the form IP/domain")
self.secondaries.append((args[0], [args[1]]))
def opt_verbose(self):
"""Increment verbosity level"""
self['verbose'] += 1
def postOptions(self):
if self['resolv-conf']:
self['recursive'] = True
self.svcs = []
self.zones = []
for f in self.zonefiles:
try:
self.zones.append(authority.PySourceAuthority(f))
except Exception, e:
traceback.print_exc()
raise usage.UsageError("Invalid syntax in " + f)
for f in self.bindfiles:
try:
self.zones.append(authority.BindAuthority(f))
except Exception, e:
traceback.print_exc()
raise usage.UsageError("Invalid syntax in " + f)
for f in self.secondaries:
self.svcs.append(secondary.SecondaryAuthorityService(*f))
self.zones.append(self.svcs[-1].getAuthority())
try:
self['port'] = int(self['port'])
except ValueError:
raise usage.UsageError("Invalid port: %r" % (self['port'],))
def makeService(config):
import client, cache, hosts
ca, cl = [], []
if config['cache']:
ca.append(cache.CacheResolver(verbose=config['verbose']))
if config['recursive']:
cl.append(client.createResolver(resolvconf=config['resolv-conf']))
if config['hosts-file']:
cl.append(hosts.Resolver(file=config['hosts-file']))
f = server.DNSServerFactory(config.zones, ca, cl, config['verbose'])
p = dns.DNSDatagramProtocol(f)
f.noisy = 0
ret = service.MultiService()
for (klass, arg) in [(internet.TCPServer, f), (internet.UDPServer, p)]:
s = klass(config['port'], arg, interface=config['interface'])
s.setServiceParent(ret)
for svc in config.svcs:
svc.setServiceParent(ret)
return ret | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/names/tap.py | tap.py |
from __future__ import nested_scopes
import time
# Twisted imports
from twisted.internet import protocol
from twisted.names import dns
from twisted.python import log
import resolve
class DNSServerFactory(protocol.ServerFactory):
protocol = dns.DNSProtocol
cache = None
def __init__(self, authorities = None, caches = None, clients = None, verbose = 0):
resolvers = []
if authorities is not None:
resolvers.extend(authorities)
if caches is not None:
resolvers.extend(caches)
if clients is not None:
resolvers.extend(clients)
self.canRecurse = not not clients
self.resolver = resolve.ResolverChain(resolvers)
self.verbose = verbose
if caches:
self.cache = caches[-1]
def buildProtocol(self, addr):
p = self.protocol(self)
p.factory = self
return p
def connectionMade(self, protocol):
pass
def sendReply(self, protocol, message, address):
if self.verbose > 1:
s = ' '.join([str(a.payload) for a in message.answers])
auth = ' '.join([str(a.payload) for a in message.authority])
add = ' '.join([str(a.payload) for a in message.additional])
if not s:
log.msg("Replying with no answers")
else:
log.msg("Answers are " + s)
log.msg("Authority is " + auth)
log.msg("Additional is " + add)
if address is None:
protocol.writeMessage(message)
else:
protocol.writeMessage(message, address)
if self.verbose > 1:
log.msg("Processed query in %0.3f seconds" % (time.time() - message.timeReceived))
def gotResolverResponse(self, (ans, auth, add), protocol, message, address):
message.rCode = dns.OK
message.answers = ans
for x in ans:
if x.isAuthoritative():
message.auth = 1
break
message.authority = auth
message.additional = add
self.sendReply(protocol, message, address)
l = len(ans) + len(auth) + len(add)
if self.verbose:
log.msg("Lookup found %d record%s" % (l, l != 1 and "s" or ""))
if self.cache and l:
self.cache.cacheResult(
message.queries[0], (ans, auth, add)
)
def gotResolverError(self, failure, protocol, message, address):
if failure.check(dns.DomainError, dns.AuthoritativeDomainError):
message.rCode = dns.ENAME
else:
message.rCode = dns.ESERVER
log.err(failure)
self.sendReply(protocol, message, address)
if self.verbose:
log.msg("Lookup failed")
def handleQuery(self, message, protocol, address):
# Discard all but the first query! HOO-AAH HOOOOO-AAAAH
# (no other servers implement multi-query messages, so we won't either)
query = message.queries[0]
return self.resolver.query(query).addCallback(
self.gotResolverResponse, protocol, message, address
).addErrback(
self.gotResolverError, protocol, message, address
)
def handleInverseQuery(self, message, protocol, address):
message.rCode = dns.ENOTIMP
self.sendReply(protocol, message, address)
if self.verbose:
log.msg("Inverse query from %r" % (address,))
def handleStatus(self, message, protocol, address):
message.rCode = dns.ENOTIMP
self.sendReply(protocol, message, address)
if self.verbose:
log.msg("Status request from %r" % (address,))
def handleNotify(self, message, protocol, address):
message.rCode = dns.ENOTIMP
self.sendReply(protocol, message, address)
if self.verbose:
log.msg("Notify message from %r" % (address,))
def handleOther(self, message, protocol, address):
message.rCode = dns.ENOTIMP
self.sendReply(protocol, message, address)
if self.verbose:
log.msg("Unknown op code (%d) from %r" % (message.opCode, address))
def messageReceived(self, message, proto, address = None):
message.timeReceived = time.time()
if self.verbose:
if self.verbose > 1:
s = ' '.join([str(q) for q in message.queries])
elif self.verbose > 0:
s = ' '.join([dns.QUERY_TYPES.get(q.type, 'UNKNOWN') for q in message.queries])
if not len(s):
log.msg("Empty query from %r" % ((address or proto.transport.getPeer()),))
else:
log.msg("%s query from %r" % (s, address or proto.transport.getPeer()))
message.recAv = self.canRecurse
message.answer = 1
if not self.allowQuery(message, proto, address):
message.rCode = dns.EREFUSED
self.sendReply(proto, message, address)
elif message.opCode == dns.OP_QUERY:
self.handleQuery(message, proto, address)
elif message.opCode == dns.OP_INVERSE:
self.handleInverseQuery(message, proto, address)
elif message.opCode == dns.OP_STATUS:
self.handleStatus(message, proto, address)
elif message.opCode == dns.OP_NOTIFY:
self.handleNotify(message, proto, address)
else:
self.handleOther(message, proto, address)
def allowQuery(self, message, protocol, address):
# Allow anything but empty queries
return len(message.queries) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/names/server.py | server.py |
from twisted.internet import task, defer
from twisted.names import dns
from twisted.names import common
from twisted.names import client
from twisted.names import resolve
from twisted.python import log, failure
from twisted.application import service
class SecondaryAuthorityService(service.Service):
calls = None
def __init__(self, primary, domains):
"""
@param primary: The IP address of the server from which to perform
zone transfers.
@param domains: A sequence of domain names for which to perform
zone transfers.
"""
self.primary = primary
self.domains = [SecondaryAuthority(primary, d) for d in domains]
def getAuthority(self):
return resolve.ResolverChain(self.domains)
def startService(self):
service.Service.startService(self)
self.calls = [task.LoopingCall(d.transfer) for d in self.domains]
i = 0
from twisted.internet import reactor
for c in self.calls:
# XXX Add errbacks, respect proper timeouts
reactor.callLater(i, c.start, 60 * 60)
i += 1
def stopService(self):
service.Service.stopService(self)
for c in self.calls:
c.stop()
from twisted.names.authority import FileAuthority
class SecondaryAuthority(common.ResolverBase):
"""An Authority that keeps itself updated by performing zone transfers"""
transferring = False
soa = records = None
def __init__(self, primaryIP, domain):
common.ResolverBase.__init__(self)
self.primary = primaryIP
self.domain = domain
def transfer(self):
if self.transferring:
return
self.transfering = True
return client.Resolver(servers=[(self.primary, dns.PORT)]
).lookupZone(self.domain
).addCallback(self._cbZone
).addErrback(self._ebZone
)
def _lookup(self, name, cls, type, timeout=None):
if not self.soa or not self.records:
return defer.fail(failure.Failure(dns.DomainError(name)))
return FileAuthority.__dict__['_lookup'](self, name, cls, type, timeout)
#shouldn't we just subclass? :P
lookupZone = FileAuthority.__dict__['lookupZone']
def _cbZone(self, zone):
ans, _, _ = zone
self.records = r = {}
for rec in ans:
if not self.soa and rec.type == dns.SOA:
self.soa = (str(rec.name).lower(), rec.payload)
else:
r.setdefault(str(rec.name).lower(), []).append(rec.payload)
def _ebZone(self, failure):
log.msg("Updating %s from %s failed during zone transfer" % (self.domain, self.primary))
log.err(failure)
def update(self):
self.transfer().addCallbacks(self._cbTransferred, self._ebTransferred)
def _cbTransferred(self, result):
self.transferring = False
def _ebTransferred(self, failure):
self.transferred = False
log.msg("Transferring %s from %s failed after zone transfer" % (self.domain, self.primary))
log.err(failure) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/names/secondary.py | secondary.py |
Twisted 2.5.0
Quote of the Release:
<jml> Give me enough bandwidth and a place to sit
<jml> and I will move the world.
For information on what's new in Twisted 2.5.0, see the ChangeLog
file that comes with the distribution.
What is this?
=============
Twisted is an event-based framework for internet applications which
works on Python 2.3.x and 2.4.x. The following are the (important)
modules included with Twisted::
- twisted.application
A "Service" system that allows you to organize your application in
hierarchies with well-defined startup and dependency semantics,
- twisted.cred
A general credentials and authentication system that facilitates
pluggable authentication backends,
- twisted.enterprise
Asynchronous database access, compatible with any Python DBAPI2.0
modules,
- twisted.internet
Low-level asynchronous networking APIs that allow you to define
your own protocols that run over certain transports,
- twisted.manhole
A tool for remote debugging of your services which gives you a
Python interactive interpreter,
- twisted.protocols
Basic protocol implementations and helpers for your own protocol
implementations,
- twisted.python
A large set of utilities for Python tricks, reflection, text
processing, and anything else,
- twisted.spread
A secure, fast remote object system,
- twisted.trial
A unit testing framework that integrates well with Twisted-based code.
Twisted supports integration of the Tk, GTK+, GTK+ 2, Qt, Mac OS X,
or wxPython event loop with its main event loop. The Win32 event
loop is also supported.
For more information, visit http://www.twistedmatrix.com, or join the list
at http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python
There are many official Twisted subprojects, including clients and
servers for web, mail, DNS, and more. You can find out more about
these projects at http://twistedmatrix.com/projects/
Installing
==========
Instructions for installing this software are in INSTALL.
Unit Tests
==========
See our unit tests run proving that the software is BugFree(TM)::
% trial -R twisted
Some of these tests may fail if you
* don't have the dependancies required for a particular
subsystem installed,
* have a firewall blocking some ports (or things like
Multicast, which Linux NAT has shown itself to do), or
* run them as root.
Documentation and Support
=========================
Examples on how to use Twisted APIs are located in doc/examples;
this might ease the learning curve a little bit, since all these
files are kept as short as possible. The file doc/howto/index.xhtml
contains an index of all the HOWTOs: this should be your starting
point when looking for documentation.
Help is available on the Twisted mailing list::
http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python
There is also a very lively IRC channel, #twisted, on
irc.freenode.net.
Copyright
=========
All of the code in this distribution is Copyright (c) 2001-2004
Twisted Matrix Laboratories.
Twisted is made available under the MIT license. The included
LICENSE file describes this in detail.
Warranty
========
THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE USE OF THIS SOFTWARE IS WITH YOU.
IN NO EVENT WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY, BE LIABLE TO YOU FOR ANY DAMAGES, EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
Again, see the included LICENSE file for specific legal details. | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/topfiles/README | README |
# TODO: need to implement log-file rotation
import sys, os, shutil, time, glob
from twisted.python import usage
from twisted.scripts import tap2deb
#################################
# data that goes in /etc/inittab
initFileData = '''\
#!/bin/sh
#
# Startup script for a Twisted service.
#
# chkconfig: - 85 15
# description: Start-up script for the Twisted service "%(tap_file)s".
PATH=/usr/bin:/bin:/usr/sbin:/sbin
pidfile=/var/run/%(rpm_file)s.pid
rundir=/var/lib/twisted-taps/%(rpm_file)s/
file=/etc/twisted-taps/%(tap_file)s
logfile=/var/log/%(rpm_file)s.log
# load init function library
. /etc/init.d/functions
[ -r /etc/default/%(rpm_file)s ] && . /etc/default/%(rpm_file)s
# check for required files
if [ ! -x /usr/bin/twistd ]
then
echo "$0: Aborting, no /usr/bin/twistd found"
exit 0
fi
if [ ! -r "$file" ]
then
echo "$0: Aborting, no file $file found."
exit 0
fi
# set up run directory if necessary
if [ ! -d "${rundir}" ]
then
mkdir -p "${rundir}"
fi
case "$1" in
start)
echo -n "Starting %(rpm_file)s: twistd"
daemon twistd \\
--pidfile=$pidfile \\
--rundir=$rundir \\
--%(twistd_option)s=$file \\
--logfile=$logfile
status %(rpm_file)s
;;
stop)
echo -n "Stopping %(rpm_file)s: twistd"
kill `cat "${pidfile}"`
status %(rpm_file)s
;;
restart)
"${0}" stop
"${0}" start
;;
*)
echo "Usage: ${0} {start|stop|restart|}" >&2
exit 1
;;
esac
exit 0
'''
#######################################
# the data for creating the spec file
specFileData = '''\
Summary: %(description)s
Name: %(rpm_file)s
Version: %(version)s
Release: 1
Copyright: Unknown
Group: Networking/Daemons
Source: %(tarfile_basename)s
BuildRoot: /var/tmp/%%{name}-%%{version}-root
Requires: /usr/bin/twistd
BuildArch: noarch
%%description
%(long_description)s
%%prep
%%setup
%%build
%%install
[ ! -z "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != '/' ] \
&& rm -rf "$RPM_BUILD_ROOT"
mkdir -p "$RPM_BUILD_ROOT"/etc/twisted-taps
mkdir -p "$RPM_BUILD_ROOT"/etc/init.d
mkdir -p "$RPM_BUILD_ROOT"/var/lib/twisted-taps
cp "%(tap_file)s" "$RPM_BUILD_ROOT"/etc/twisted-taps/
cp "%(rpm_file)s.init" "$RPM_BUILD_ROOT"/etc/init.d/"%(rpm_file)s"
%%clean
[ ! -z "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != '/' ] \
&& rm -rf "$RPM_BUILD_ROOT"
%%post
/sbin/chkconfig --add %(rpm_file)s
/sbin/chkconfig --level 35 %(rpm_file)s
/etc/init.d/%(rpm_file)s start
%%preun
/etc/init.d/%(rpm_file)s stop
/sbin/chkconfig --del %(rpm_file)s
%%files
%%defattr(-,root,root)
%%attr(0755,root,root) /etc/init.d/%(rpm_file)s
%%attr(0660,root,root) /etc/twisted-taps/%(tap_file)s
%%changelog
* %(date)s %(maintainer)s
- Created by tap2rpm: %(rpm_file)s (%(version)s)
'''
###############################
class MyOptions(usage.Options):
optFlags = [["unsigned", "u"]]
optParameters = [
["tapfile", "t", "twistd.tap"],
["maintainer", "m", ""],
["protocol", "p", ""],
["description", "e", ""],
["long_description", "l", ""],
["set-version", "V", "1.0"],
["rpmfile", "r", None],
["type", "y", "tap", "type of configuration: 'tap', 'xml, "
"'source' or 'python'"],
]
#zsh_altArgDescr = {"foo":"use this description for foo instead"}
#zsh_multiUse = ["foo", "bar"]
#zsh_mutuallyExclusive = [("foo", "bar"), ("bar", "baz")]
zsh_actions = {"type":"(tap xml source python)",
"rpmfile":'_files -g "*.rpm"'}
#zsh_actionDescr = {"logfile":"log file name", "random":"random seed"}
type_dict = {
'tap': 'file',
'python': 'python',
'source': 'source',
'xml': 'xml',
}
##########################
def makeBuildDir(baseDir):
'''Set up the temporary directory for building RPMs.
Returns: Tuple: ( buildDir, rpmrcFile )
'''
import random, string
# make top directory
oldMask = os.umask(0077)
while 1:
tmpDir = os.path.join(baseDir, 'tap2rpm-%s-%s' % ( os.getpid(),
random.randint(0, 999999999) ))
if not os.path.exists(tmpDir):
os.makedirs(tmpDir)
break
os.umask(oldMask)
# set up initial directory contents
os.makedirs(os.path.join(tmpDir, 'RPMS', 'noarch'))
os.makedirs(os.path.join(tmpDir, 'SPECS'))
os.makedirs(os.path.join(tmpDir, 'BUILD'))
os.makedirs(os.path.join(tmpDir, 'SOURCES'))
os.makedirs(os.path.join(tmpDir, 'SRPMS'))
# set up rpmmacros file
macroFile = os.path.join(tmpDir, 'rpmmacros')
rcFile = os.path.join(tmpDir, 'rpmrc')
rpmrcData = open('/usr/lib/rpm/rpmrc', 'r').read()
rpmrcData = string.replace(rpmrcData, '~/.rpmmacros', macroFile)
fp = open(macroFile, 'w')
fp.write('%%_topdir %s\n' % tmpDir)
fp.close()
# set up the rpmrc file
fp = open(rcFile, 'w')
fp.write(rpmrcData)
fp.close()
return(( tmpDir, rcFile ))
##########
def run():
# parse options
try:
config = MyOptions()
config.parseOptions()
except usage.error, ue:
sys.exit("%s: %s" % (sys.argv[0], ue))
# set up some useful local variables
tap_file = config['tapfile']
base_tap_file = os.path.basename(config['tapfile'])
protocol = (config['protocol'] or os.path.splitext(base_tap_file)[0])
rpm_file = config['rpmfile'] or 'twisted-'+protocol
version = config['set-version']
maintainer = config['maintainer']
description = config['description'] or ('A TCP server for %(protocol)s' %
vars())
long_description = (config['long_description']
or 'Automatically created by tap2deb')
twistd_option = type_dict[config['type']]
date = time.strftime('%a %b %d %Y', time.localtime(time.time()))
directory = rpm_file + '-' + version
python_version = '%s.%s' % sys.version_info[:2]
# set up a blank maintainer if not present
if not maintainer:
maintainer = 'tap2rpm'
# create source archive directory
tmp_dir, rpmrc_file = makeBuildDir('/var/tmp')
source_dir = os.path.join(tmp_dir, directory)
os.makedirs(source_dir)
# populate source directory
tarfile_name = source_dir + '.tar.gz'
tarfile_basename = os.path.basename(tarfile_name)
tap2deb.save_to_file(os.path.join(source_dir, '%s.spec' % rpm_file),
specFileData % vars())
tap2deb.save_to_file(os.path.join(source_dir, '%s.init' % rpm_file),
initFileData % vars())
shutil.copy(tap_file, source_dir)
# create source tar
os.system('cd "%(tmp_dir)s"; tar cfz "%(tarfile_name)s" "%(directory)s"'
% vars())
# build rpm
print 'Starting build...'
print '=' * 70
sys.stdout.flush()
os.system('rpmbuild -ta --rcfile "%s" %s' % ( rpmrc_file, tarfile_name ))
print 'Done with build...'
print '=' * 70
# copy the RPMs to the local directory
rpm_path = glob.glob(os.path.join(tmp_dir, 'RPMS', 'noarch', '*'))[0]
srpm_path = glob.glob(os.path.join(tmp_dir, 'SRPMS', '*'))[0]
print 'Writing "%s"...' % os.path.basename(rpm_path)
shutil.copy(rpm_path, '.')
print 'Writing "%s"...' % os.path.basename(srpm_path)
shutil.copy(srpm_path, '.')
# remove the build directory
shutil.rmtree(tmp_dir) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/scripts/tap2rpm.py | tap2rpm.py |
import sys
from twisted.python import usage
# Prefer gtk2 because it is the way of the future!
toolkitPreference = ('gtk2', 'gtk1')
class NoToolkitError(usage.UsageError):
wantToolkits = toolkitPreference
def __str__(self):
return (
"I couldn't find any of these toolkits installed, and I need "
"one of them to run: %s" % (', '.join(self.wantToolkits),))
def bestToolkit():
"""The most-preferred available toolkit.
@returntype: string
"""
avail = getAvailableToolkits()
for v in toolkitPreference:
if v in avail:
return v
else:
raise NoToolkitError
_availableToolkits = None
def getAvailableToolkits():
"""Autodetect available toolkits.
@returns: A list of usable toolkits.
@returntype: list of strings
"""
global _availableToolkits
# use cached result
if _availableToolkits is not None:
return _availableToolkits
avail = []
# Recent GTK.
try:
import pygtk
except:
pass
else:
gtkvers = pygtk._get_available_versions().keys()
for v in gtkvers:
frontend = {'1.2': 'gtk1',
'2.0': 'gtk2'}.get(v)
if frontend is not None:
avail.append(frontend)
if not avail:
# Older GTK
try:
# WARNING: It's entirely possible that this does something crappy,
# such as running gtk_init, which may have undesirable side
# effects if that's not the toolkit we end up using.
import gtk
except:
pass
else:
avail.append('gtk1')
# There may be some "middle gtk" that got left out -- that is, a
# version of pygtk 1.99.x that happened before the pygtk module
# with its _get_available_versions was introduced. Chances are
# that the gtk2 front-end wouldn't work with it anyway, but it may
# get mis-identified it as gtk1. :(
_availableToolkits = avail
return avail
def run():
config = MyOptions()
try:
config.parseOptions()
except usage.UsageError, e:
print str(e)
print str(config)
sys.exit(1)
try:
run = getattr(sys.modules[__name__], 'run_' + config.opts['toolkit'])
except AttributeError:
print "Sorry, no support for toolkit %r." % (config.opts['toolkit'],)
sys.exit(1)
run(config)
from twisted.internet import reactor
reactor.run()
def run_gtk1(config):
# Put these off until after we parse options, so we know what reactor
# to install.
from twisted.internet import gtkreactor
gtkreactor.install()
from twisted.spread.ui import gtkutil
# Put this off until after we parse options, or else gnome eats them.
# (http://www.daa.com.au/pipermail/pygtk/2002-December/004051.html)
sys.argv[:] = ['manhole']
from twisted.manhole.ui import gtkmanhole
i = gtkmanhole.Interaction()
lw = gtkutil.Login(i.connected,
i.client,
initialUser=config.opts['user'],
initialPassword=config.opts['password'],
initialService=config.opts['service'],
initialHostname=config.opts['host'],
initialPortno=config.opts['port'],
initialPerspective=config.opts['perspective'])
i.loginWindow = lw
lw.show_all()
def run_gtk2(config):
# Put these off until after we parse options, so we know what reactor
# to load.
from twisted.internet import gtk2reactor
gtk2reactor.install()
from twisted.spread.ui import gtk2util
# Put this off until after we parse options, or else gnome eats them.
sys.argv[:] = ['manhole']
from twisted.manhole.ui import gtk2manhole
o = config.opts
defaults = {
'host': o['host'],
'port': o['port'],
'identityName': o['user'],
'password': o['password'],
'serviceName': o['service'],
'perspectiveName': o['perspective']
}
w = gtk2manhole.ManholeWindow()
w.setDefaults(defaults)
w.login()
# from twisted.spread import pb
# can't do that, it installs a reactor. grr.
pbportno = 8787
class MyOptions(usage.Options):
optParameters=[("user", "u", "guest", "username"),
("password", "w", "guest"),
("service", "s", "twisted.manhole", "PB Service"),
("host", "h", "localhost"),
("port", "p", str(pbportno)),
("perspective", "P", "",
"PB Perspective to ask for "
"(if different than username)"),
("toolkit", "t", bestToolkit(),
"Front-end to use; one of %s"
% (' '.join(getAvailableToolkits()),)),
]
#zsh_altArgDescr = {"foo":"use this description for foo instead"}
#zsh_multiUse = ["foo", "bar"]
#zsh_mutuallyExclusive = [("foo", "bar"), ("bar", "baz")]
zsh_actions = {"host":"_hosts",
"toolkit":"(gtk1 gtk2)"}
#zsh_actionDescr = {"logfile":"log file name", "random":"random seed"}
if __name__ == '__main__':
run() | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/scripts/manhole.py | manhole.py |
from twisted.python import log, syslog
from twisted.python.util import switchUID
from twisted.application import app, service
from twisted.scripts import mktap
from twisted import copyright
import os, errno, sys
class ServerOptions(app.ServerOptions):
synopsis = "Usage: twistd [options]"
optFlags = [['nodaemon','n', "don't daemonize"],
['quiet', 'q', "No-op for backwards compatability."],
['originalname', None, "Don't try to change the process name"],
['syslog', None, "Log to syslog, not to file"],
['euid', '',
"Set only effective user-id rather than real user-id. "
"(This option has no effect unless the server is running as "
"root, in which case it means not to shed all privileges "
"after binding ports, retaining the option to regain "
"privileges in cases such as spawning processes. "
"Use with caution.)"],
]
optParameters = [
['prefix', None,'twisted',
"use the given prefix when syslogging"],
['pidfile','','twistd.pid',
"Name of the pidfile"],
['chroot', None, None,
'Chroot to a supplied directory before running'],
['uid', 'u', None, "The uid to run as."],
['gid', 'g', None, "The gid to run as."],
]
zsh_altArgDescr = {"prefix":"Use the given prefix when syslogging (default: twisted)",
"pidfile":"Name of the pidfile (default: twistd.pid)",}
#zsh_multiUse = ["foo", "bar"]
#zsh_mutuallyExclusive = [("foo", "bar"), ("bar", "baz")]
zsh_actions = {"pidfile":'_files -g "*.pid"', "chroot":'_dirs'}
zsh_actionDescr = {"chroot":"chroot directory"}
def opt_version(self):
"""Print version information and exit.
"""
print 'twistd (the Twisted daemon) %s' % copyright.version
print copyright.copyright
sys.exit()
def postOptions(self):
app.ServerOptions.postOptions(self)
if self['pidfile']:
self['pidfile'] = os.path.abspath(self['pidfile'])
def checkPID(pidfile):
if not pidfile:
return
if os.path.exists(pidfile):
try:
pid = int(open(pidfile).read())
except ValueError:
sys.exit('Pidfile %s contains non-numeric value' % pidfile)
try:
os.kill(pid, 0)
except OSError, why:
if why[0] == errno.ESRCH:
# The pid doesnt exists.
log.msg('Removing stale pidfile %s' % pidfile, isError=True)
os.remove(pidfile)
else:
sys.exit("Can't check status of PID %s from pidfile %s: %s" %
(pid, pidfile, why[1]))
else:
sys.exit("""\
Another twistd server is running, PID %s\n
This could either be a previously started instance of your application or a
different application entirely. To start a new one, either run it in some other
directory, or use the --pidfile and --logfile parameters to avoid clashes.
""" % pid)
def removePID(pidfile):
if not pidfile:
return
try:
os.unlink(pidfile)
except OSError, e:
if e.errno == errno.EACCES or e.errno == errno.EPERM:
log.msg("Warning: No permission to delete pid file")
else:
log.msg("Failed to unlink PID file:")
log.deferr()
except:
log.msg("Failed to unlink PID file:")
log.deferr()
def startLogging(logfilename, sysLog, prefix, nodaemon):
if logfilename == '-':
if not nodaemon:
print 'daemons cannot log to stdout'
os._exit(1)
logFile = sys.stdout
elif sysLog:
syslog.startLogging(prefix)
elif nodaemon and not logfilename:
logFile = sys.stdout
else:
logFile = app.getLogFile(logfilename or 'twistd.log')
try:
import signal
except ImportError:
pass
else:
def rotateLog(signal, frame):
from twisted.internet import reactor
reactor.callFromThread(logFile.rotate)
signal.signal(signal.SIGUSR1, rotateLog)
if not sysLog:
log.startLogging(logFile)
sys.stdout.flush()
def daemonize():
# See http://www.erlenstar.demon.co.uk/unix/faq_toc.html#TOC16
if os.fork(): # launch child and...
os._exit(0) # kill off parent
os.setsid()
if os.fork(): # launch child and...
os._exit(0) # kill off parent again.
os.umask(077)
null=os.open('/dev/null', os.O_RDWR)
for i in range(3):
try:
os.dup2(null, i)
except OSError, e:
if e.errno != errno.EBADF:
raise
os.close(null)
def shedPrivileges(euid, uid, gid):
if uid is not None or gid is not None:
switchUID(uid, gid, euid)
extra = euid and 'e' or ''
log.msg('set %suid/%sgid %s/%s' % (extra, extra, uid, gid))
def launchWithName(name):
if name and name != sys.argv[0]:
exe = os.path.realpath(sys.executable)
log.msg('Changing process name to ' + name)
os.execv(exe, [name, sys.argv[0], '--originalname']+sys.argv[1:])
def setupEnvironment(config):
if config['chroot'] is not None:
os.chroot(config['chroot'])
if config['rundir'] == '.':
config['rundir'] = '/'
os.chdir(config['rundir'])
if not config['nodaemon']:
daemonize()
if config['pidfile']:
open(config['pidfile'],'wb').write(str(os.getpid()))
def startApplication(config, application):
process = service.IProcess(application, None)
if not config['originalname']:
launchWithName(process.processName)
setupEnvironment(config)
service.IService(application).privilegedStartService()
uid, gid = mktap.getid(config['uid'], config['gid'])
if uid is None:
uid = process.uid
if gid is None:
gid = process.gid
shedPrivileges(config['euid'], uid, gid)
app.startApplication(application, not config['no_save'])
class UnixApplicationRunner(app.ApplicationRunner):
"""
An ApplicationRunner which does Unix-specific things, like fork,
shed privileges, and maintain a PID file.
"""
def preApplication(self):
"""
Do pre-application-creation setup.
"""
checkPID(self.config['pidfile'])
self.config['nodaemon'] = (self.config['nodaemon']
or self.config['debug'])
self.oldstdout = sys.stdout
self.oldstderr = sys.stderr
startLogging(self.config['logfile'], self.config['syslog'],
self.config['prefix'], self.config['nodaemon'])
app.initialLog()
def postApplication(self):
"""
To be called after the application is created: start the
application and run the reactor. After the reactor stops,
clean up PID files and such.
"""
startApplication(self.config, self.application)
app.runReactorWithLogging(self.config, self.oldstdout, self.oldstderr)
removePID(self.config['pidfile'])
app.reportProfile(self.config['report-profile'],
service.IProcess(self.application).processName)
log.msg("Server Shut Down.") | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/scripts/_twistd_unix.py | _twistd_unix.py |
from twisted.python import usage
from twisted.application import app
from twisted.persisted import sob
import sys, getpass
class ConvertOptions(usage.Options):
synopsis = "Usage: tapconvert [options]"
optParameters = [
['in', 'i', None, "The filename of the tap to read from"],
['out', 'o', None, "A filename to write the tap to"],
['typein', 'f', 'guess',
"The format to use; this can be 'guess', 'python', "
"'pickle', 'xml', or 'source'."],
['typeout', 't', 'source',
"The output format to use; this can be 'pickle', 'xml', or 'source'."],
]
optFlags = [
['decrypt', 'd', "The specified tap/aos/xml file is encrypted."],
['encrypt', 'e', "Encrypt file before writing"]
]
#zsh_altArgDescr = {"foo":"use this description for foo instead"}
#zsh_multiUse = ["foo", "bar"]
#zsh_mutuallyExclusive = [("foo", "bar"), ("bar", "baz")]
zsh_actions = {"typein":"(guess python pickle xml source)",
"typeout":"(pickle xml source)"}
zsh_actionDescr = {"in":"tap file to read from",
"out":"tap file to write to"}
def postOptions(self):
if self['in'] is None:
raise usage.UsageError("%s\nYou must specify the input filename."
% self)
if self["typein"] == "guess":
try:
self["typein"] = sob.guessType(self["in"])
except KeyError:
raise usage.UsageError("Could not guess type for '%s'" %
self["typein"])
def run():
options = ConvertOptions()
try:
options.parseOptions(sys.argv[1:])
except usage.UsageError, e:
print e
else:
app.convertStyle(options["in"], options["typein"],
options.opts['decrypt'] or getpass.getpass('Passphrase: '),
options["out"], options['typeout'], options["encrypt"]) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/scripts/tapconvert.py | tapconvert.py |
import sys, os
from zope.interface import implements
from twisted.application import service, app
from twisted.persisted import sob
from twisted.python import usage, util, plugin as oldplugin
from twisted import plugin as newplugin
# API COMPATIBILITY
IServiceMaker = service.IServiceMaker
import warnings
warnings.warn(
"mktap is obsolete as of Twisted 2.5, and will be officially deprecated "
"in Twisted 2.6. Use Twisted Application Plugins with the "
"'twistd' command directly, as described in "
"'Writing a Twisted Application Plugin for twistd' chapter of the "
"Developer Guide.", PendingDeprecationWarning)
try:
import pwd, grp
except ImportError:
def getid(uid, gid):
if uid is not None:
uid = int(uid)
if gid is not None:
gid = int(gid)
return uid, gid
else:
def getid(uid, gid):
if uid is not None:
try:
uid = int(uid)
except ValueError:
uid = pwd.getpwnam(uid)[2]
if gid is not None:
try:
gid = int(gid)
except ValueError:
gid = grp.getgrnam(gid)[2]
return uid, gid
def loadPlugins(debug = None, progress = None):
tapLookup = {}
plugins = oldplugin._getPlugIns("tap", debug, progress)
for plug in plugins:
if hasattr(plug, 'tapname'):
shortTapName = plug.tapname
else:
shortTapName = plug.module.split('.')[-1]
tapLookup[shortTapName] = plug
plugins = newplugin.getPlugins(IServiceMaker)
for plug in plugins:
tapLookup[plug.tapname] = plug
return tapLookup
def addToApplication(ser, name, append, procname, type, encrypted, uid, gid):
if append and os.path.exists(append):
a = service.loadApplication(append, 'pickle', None)
else:
a = service.Application(name, uid, gid)
if procname:
service.IProcess(a).processName = procname
ser.setServiceParent(service.IServiceCollection(a))
sob.IPersistable(a).setStyle(type)
passphrase = app.getSavePassphrase(encrypted)
if passphrase:
append = None
sob.IPersistable(a).save(filename=append, passphrase=passphrase)
class FirstPassOptions(usage.Options):
synopsis = """Usage: mktap [options] <command> [command options] """
recursing = 0
params = ()
optParameters = [
['uid', 'u', None, "The uid to run as."],
['gid', 'g', None, "The gid to run as."],
['append', 'a', None,
"An existing .tap file to append the plugin to, rather than "
"creating a new one."],
['type', 't', 'pickle',
"The output format to use; this can be 'pickle', 'xml', "
"or 'source'."],
['appname', 'n', None, "The process name to use for this application."]
]
optFlags = [
['encrypted', 'e', "Encrypt file before writing "
"(will make the extension of the resultant "
"file begin with 'e')"],
['debug', 'd', "Show debug information for plugin loading"],
['progress', 'p', "Show progress information for plugin loading"],
['help', 'h', "Display this message"],
]
#zsh_altArgDescr = {"foo":"use this description for foo instead"}
#zsh_multiUse = ["foo", "bar"]
#zsh_mutuallyExclusive = [("foo", "bar"), ("bar", "baz")]
zsh_actions = {"append":'_files -g "*.tap"',
"type":"(pickle xml source)"}
zsh_actionDescr = {"append":"tap file to append to", "uid":"uid to run as",
"gid":"gid to run as", "type":"output format"}
def init(self, tapLookup):
sc = []
for (name, module) in tapLookup.iteritems():
if IServiceMaker.providedBy(module):
sc.append((
name, None, lambda m=module: m.options(), module.description))
else:
sc.append((
name, None, lambda obj=module: obj.load().Options(),
getattr(module, 'description', '')))
sc.sort()
self.subCommands = sc
def parseArgs(self, *rest):
self.params += rest
def _reportDebug(self, info):
print 'Debug: ', info
def _reportProgress(self, info):
s = self.pb(info)
if s:
print '\rProgress: ', s,
if info == 1.0:
print '\r' + (' ' * 79) + '\r',
def postOptions(self):
if self.recursing:
return
debug = progress = None
if self['debug']:
debug = self._reportDebug
if self['progress']:
progress = self._reportProgress
self.pb = util.makeStatBar(60, 1.0)
try:
self.tapLookup = loadPlugins(debug, progress)
except IOError:
raise usage.UsageError("Couldn't load the plugins file!")
self.init(self.tapLookup)
self.recursing = 1
self.parseOptions(self.params)
if not hasattr(self, 'subOptions') or self['help']:
raise usage.UsageError(str(self))
if hasattr(self, 'subOptions') and self.subOptions.get('help'):
raise usage.UsageError(str(self.subOptions))
if not self.tapLookup.has_key(self.subCommand):
raise usage.UsageError("Please select one of: "+
' '.join(self.tapLookup))
def run():
options = FirstPassOptions()
try:
options.parseOptions(sys.argv[1:])
except usage.UsageError, e:
print e
sys.exit(2)
except KeyboardInterrupt:
sys.exit(1)
plg = options.tapLookup[options.subCommand]
if not IServiceMaker.providedBy(plg):
plg = plg.load()
ser = plg.makeService(options.subOptions)
addToApplication(ser,
options.subCommand, options['append'], options['appname'],
options['type'], options['encrypted'],
*getid(options['uid'], options['gid']))
from twisted.python.reflect import namedAny
from twisted.plugin import IPlugin
class _tapHelper(object):
"""
Internal utility class to simplify the definition of \"new-style\"
mktap plugins based on existing, \"classic\" mktap plugins.
"""
implements(IPlugin, IServiceMaker)
def __init__(self, name, module, description, tapname):
self.name = name
self.module = module
self.description = description
self.tapname = tapname
def options():
def get(self):
return namedAny(self.module).Options
return get,
options = property(*options())
def makeService():
def get(self):
return namedAny(self.module).makeService
return get,
makeService = property(*makeService()) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/scripts/mktap.py | mktap.py |
import sys, os, string, shutil
from twisted.python import usage
class MyOptions(usage.Options):
optFlags = [["unsigned", "u"]]
optParameters = [["tapfile", "t", "twistd.tap"],
["maintainer", "m", "", "The maintainer's name and email in a specific format: "
"'John Doe <[email protected]>'"],
["protocol", "p", ""],
["description", "e", ""],
["long_description", "l", ""],
["set-version", "V", "1.0"],
["debfile", "d", None],
["type", "y", "tap", "type of configuration: 'tap', 'xml, 'source' or 'python' for .tac files"]]
#zsh_altArgDescr = {"foo":"use this description for foo instead"}
#zsh_multiUse = ["foo", "bar"]
#zsh_mutuallyExclusive = [("foo", "bar"), ("bar", "baz")]
zsh_actions = {"type":"(tap xml source python)"}
#zsh_actionDescr = {"logfile":"log file name", "random":"random seed"}
def postOptions(self):
if not self["maintainer"]:
raise usage.UsageError, "maintainer must be specified."
type_dict = {
'tap': 'file',
'python': 'python',
'source': 'source',
'xml': 'xml',
}
def save_to_file(file, text):
open(file, 'w').write(text)
def run():
try:
config = MyOptions()
config.parseOptions()
except usage.error, ue:
sys.exit("%s: %s" % (sys.argv[0], ue))
tap_file = config['tapfile']
base_tap_file = os.path.basename(config['tapfile'])
protocol = (config['protocol'] or os.path.splitext(base_tap_file)[0])
deb_file = config['debfile'] or 'twisted-'+protocol
version = config['set-version']
maintainer = config['maintainer']
description = config['description'] or ('A Twisted-based server for %(protocol)s' %
vars())
long_description = config['long_description'] or 'Automatically created by tap2deb'
twistd_option = type_dict[config['type']]
date = string.strip(os.popen('822-date').read())
directory = deb_file + '-' + version
python_version = '%s.%s' % sys.version_info[:2]
if os.path.exists(os.path.join('.build', directory)):
os.system('rm -rf %s' % os.path.join('.build', directory))
os.makedirs(os.path.join('.build', directory, 'debian'))
shutil.copy(tap_file, os.path.join('.build', directory))
save_to_file(os.path.join('.build', directory, 'debian', 'README.Debian'),
'''This package was auto-generated by tap2deb\n''')
save_to_file(os.path.join('.build', directory, 'debian', 'conffiles'),
'''\
/etc/init.d/%(deb_file)s
/etc/default/%(deb_file)s
/etc/%(base_tap_file)s
''' % vars())
save_to_file(os.path.join('.build', directory, 'debian', 'default'),
'''\
pidfile=/var/run/%(deb_file)s.pid
rundir=/var/lib/%(deb_file)s/
file=/etc/%(tap_file)s
logfile=/var/log/%(deb_file)s.log
''' % vars())
save_to_file(os.path.join('.build', directory, 'debian', 'init.d'),
'''\
#!/bin/sh
PATH=/sbin:/bin:/usr/sbin:/usr/bin
pidfile=/var/run/%(deb_file)s.pid \
rundir=/var/lib/%(deb_file)s/ \
file=/etc/%(tap_file)s \
logfile=/var/log/%(deb_file)s.log
[ -r /etc/default/%(deb_file)s ] && . /etc/default/%(deb_file)s
test -x /usr/bin/twistd%(python_version)s || exit 0
test -r $file || exit 0
test -r /usr/share/%(deb_file)s/package-installed || exit 0
case "$1" in
start)
echo -n "Starting %(deb_file)s: twistd"
start-stop-daemon --start --quiet --exec /usr/bin/twistd%(python_version)s -- \
--pidfile=$pidfile \
--rundir=$rundir \
--%(twistd_option)s=$file \
--logfile=$logfile
echo "."
;;
stop)
echo -n "Stopping %(deb_file)s: twistd"
start-stop-daemon --stop --quiet \
--pidfile $pidfile
echo "."
;;
restart)
$0 stop
$0 start
;;
force-reload)
$0 restart
;;
*)
echo "Usage: /etc/init.d/%(deb_file)s {start|stop|restart|force-reload}" >&2
exit 1
;;
esac
exit 0
''' % vars())
os.chmod(os.path.join('.build', directory, 'debian', 'init.d'), 0755)
save_to_file(os.path.join('.build', directory, 'debian', 'postinst'),
'''\
#!/bin/sh
update-rc.d %(deb_file)s defaults >/dev/null
invoke-rc.d %(deb_file)s start
''' % vars())
save_to_file(os.path.join('.build', directory, 'debian', 'prerm'),
'''\
#!/bin/sh
invoke-rc.d %(deb_file)s stop
''' % vars())
save_to_file(os.path.join('.build', directory, 'debian', 'postrm'),
'''\
#!/bin/sh
if [ "$1" = purge ]; then
update-rc.d %(deb_file)s remove >/dev/null
fi
''' % vars())
save_to_file(os.path.join('.build', directory, 'debian', 'changelog'),
'''\
%(deb_file)s (%(version)s) unstable; urgency=low
* Created by tap2deb
-- %(maintainer)s %(date)s
''' % vars())
save_to_file(os.path.join('.build', directory, 'debian', 'control'),
'''\
Source: %(deb_file)s
Section: net
Priority: extra
Maintainer: %(maintainer)s
Build-Depends-Indep: debhelper
Standards-Version: 3.5.6
Package: %(deb_file)s
Architecture: all
Depends: python%(python_version)s-twisted
Description: %(description)s
%(long_description)s
''' % vars())
save_to_file(os.path.join('.build', directory, 'debian', 'copyright'),
'''\
This package was auto-debianized by %(maintainer)s on
%(date)s
It was auto-generated by tap2deb
Upstream Author(s):
Moshe Zadka <[email protected]> -- tap2deb author
Copyright:
Insert copyright here.
''' % vars())
save_to_file(os.path.join('.build', directory, 'debian', 'dirs'),
'''\
etc/init.d
etc/default
var/lib/%(deb_file)s
usr/share/doc/%(deb_file)s
usr/share/%(deb_file)s
''' % vars())
save_to_file(os.path.join('.build', directory, 'debian', 'rules'),
'''\
#!/usr/bin/make -f
export DH_COMPAT=1
build: build-stamp
build-stamp:
dh_testdir
touch build-stamp
clean:
dh_testdir
dh_testroot
rm -f build-stamp install-stamp
dh_clean
install: install-stamp
install-stamp: build-stamp
dh_testdir
dh_testroot
dh_clean -k
dh_installdirs
# Add here commands to install the package into debian/tmp.
cp %(base_tap_file)s debian/tmp/etc/
cp debian/init.d debian/tmp/etc/init.d/%(deb_file)s
cp debian/default debian/tmp/etc/default/%(deb_file)s
cp debian/copyright debian/tmp/usr/share/doc/%(deb_file)s/
cp debian/README.Debian debian/tmp/usr/share/doc/%(deb_file)s/
touch debian/tmp/usr/share/%(deb_file)s/package-installed
touch install-stamp
binary-arch: build install
binary-indep: build install
dh_testdir
dh_testroot
dh_strip
dh_compress
dh_installchangelogs
dh_fixperms
dh_installdeb
dh_shlibdeps
dh_gencontrol
dh_md5sums
dh_builddeb
source diff:
@echo >&2 'source and diff are obsolete - use dpkg-source -b'; false
binary: binary-indep binary-arch
.PHONY: build clean binary-indep binary-arch binary install
''' % vars())
os.chmod(os.path.join('.build', directory, 'debian', 'rules'), 0755)
os.chdir('.build/%(directory)s' % vars())
os.system('dpkg-buildpackage -rfakeroot'+ ['', ' -uc -us'][config['unsigned']])
if __name__ == '__main__':
run() | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/scripts/tap2deb.py | tap2deb.py |
from __future__ import generators
import sys
import zipfile
import py_compile
# we're going to ignore failures to import tkinter and fall back
# to using the console if the required dll is not found
# Scary kludge to work around tk84.dll bug:
# https://sourceforge.net/tracker/index.php?func=detail&aid=814654&group_id=5470&atid=105470
# Without which(): you get a windows missing-dll popup message
from twisted.python.procutils import which
tkdll='tk84.dll'
if which(tkdll) or which('DLLs/%s' % tkdll):
try:
import Tkinter
from Tkinter import *
from twisted.internet import tksupport
except ImportError:
pass
# twisted
from twisted.internet import reactor, defer
from twisted.python import failure, log, zipstream, util, usage, log
# local
import os.path
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="Arial",
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 pack(self, *args, **kwargs):
self.frame.pack(*args, **kwargs)
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 Progressor:
"""A base class to make it simple to hook a progress bar up to a process.
"""
def __init__(self, title, *args, **kwargs):
self.title=title
self.stopping=0
self.bar=None
self.iterator=None
self.remaining=1000
def setBar(self, bar, max):
self.bar=bar
bar.updateProgress(0, max)
return self
def setIterator(self, iterator):
self.iterator=iterator
return self
def updateBar(self, deferred):
b=self.bar
try:
b.updateProgress(b.max - self.remaining)
except TclError:
self.stopping=1
except:
deferred.errback(failure.Failure())
def processAll(self, root):
assert self.bar and self.iterator, "must setBar and setIterator"
self.root=root
root.title(self.title)
d=defer.Deferred()
d.addErrback(log.err)
reactor.callLater(0.1, self.processOne, d)
return d
def processOne(self, deferred):
if self.stopping:
deferred.callback(self.root)
return
try:
self.remaining=self.iterator.next()
except StopIteration:
self.stopping=1
except:
deferred.errback(failure.Failure())
if self.remaining%10==0:
reactor.callLater(0, self.updateBar, deferred)
if self.remaining%100==0:
log.msg(self.remaining)
reactor.callLater(0, self.processOne, deferred)
def compiler(path):
"""A generator for compiling files to .pyc"""
def justlist(arg, directory, names):
pynames=[os.path.join(directory, n) for n in names
if n.endswith('.py')]
arg.extend(pynames)
all=[]
os.path.walk(path, justlist, all)
remaining=len(all)
i=zip(all, range(remaining-1, -1, -1))
for f, remaining in i:
py_compile.compile(f)
yield remaining
class TkunzipOptions(usage.Options):
optParameters=[["zipfile", "z", "", "a zipfile"],
["ziptargetdir", "t", ".", "where to extract zipfile"],
["compiledir", "c", "", "a directory to compile"],
]
optFlags=[["use-console", "C", "show in the console, not graphically"],
["shell-exec", "x", """\
spawn a new console to show output (implies -C)"""],
]
def countPys(countl, directory, names):
sofar=countl[0]
sofar=sofar+len([f for f in names if f.endswith('.py')])
countl[0]=sofar
return sofar
def countPysRecursive(path):
countl=[0]
os.path.walk(path, countPys, countl)
return countl[0]
def run(argv=sys.argv):
log.startLogging(file('tkunzip.log', 'w'))
opt=TkunzipOptions()
try:
opt.parseOptions(argv[1:])
except usage.UsageError, e:
print str(opt)
print str(e)
sys.exit(1)
if opt['use-console']:
# this should come before shell-exec to prevent infinite loop
return doItConsolicious(opt)
if opt['shell-exec'] or not 'Tkinter' in sys.modules:
from distutils import sysconfig
from twisted.scripts import tkunzip
myfile=tkunzip.__file__
exe=os.path.join(sysconfig.get_config_var('prefix'), 'python.exe')
return os.system('%s %s --use-console %s' % (exe, myfile,
' '.join(argv[1:])))
return doItTkinterly(opt)
def doItConsolicious(opt):
# reclaim stdout/stderr from log
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
if opt['zipfile']:
print 'Unpacking documentation...'
for n in zipstream.unzipIter(opt['zipfile'], opt['ziptargetdir']):
if n % 100 == 0:
print n,
if n % 1000 == 0:
print
print 'Done unpacking.'
if opt['compiledir']:
print 'Compiling to pyc...'
import compileall
compileall.compile_dir(opt["compiledir"])
print 'Done compiling.'
def doItTkinterly(opt):
root=Tkinter.Tk()
root.withdraw()
root.title('One Moment.')
root.protocol('WM_DELETE_WINDOW', reactor.stop)
tksupport.install(root)
prog=ProgressBar(root, value=0, labelColor="black", width=200)
prog.pack()
# callback immediately
d=defer.succeed(root).addErrback(log.err)
def deiconify(root):
root.deiconify()
return root
d.addCallback(deiconify)
if opt['zipfile']:
uz=Progressor('Unpacking documentation...')
max=zipstream.countZipFileChunks(opt['zipfile'], 4096)
uz.setBar(prog, max)
uz.setIterator(zipstream.unzipIterChunky(opt['zipfile'],
opt['ziptargetdir']))
d.addCallback(uz.processAll)
if opt['compiledir']:
comp=Progressor('Compiling to pyc...')
comp.setBar(prog, countPysRecursive(opt['compiledir']))
comp.setIterator(compiler(opt['compiledir']))
d.addCallback(comp.processAll)
def stop(ignore):
reactor.stop()
root.destroy()
d.addCallback(stop)
reactor.run()
if __name__=='__main__':
run() | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/scripts/tkunzip.py | tkunzip.py |
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
import sys, os, random, gc, time, sets
from twisted.internet import defer
from twisted.application import app
from twisted.python import usage, reflect, failure
from twisted import plugin
from twisted.python.util import spewer
from twisted.trial import runner, itrial, reporter
# Yea, this is stupid. Leave it for for command-line compatibility for a
# while, though.
TBFORMAT_MAP = {
'plain': 'default',
'default': 'default',
'emacs': 'brief',
'brief': 'brief',
'cgitb': 'verbose',
'verbose': 'verbose'
}
def _parseLocalVariables(line):
"""Accepts a single line in Emacs local variable declaration format and
returns a dict of all the variables {name: value}.
Raises ValueError if 'line' is in the wrong format.
See http://www.gnu.org/software/emacs/manual/html_node/File-Variables.html
"""
paren = '-*-'
start = line.find(paren) + len(paren)
end = line.rfind(paren)
if start == -1 or end == -1:
raise ValueError("%r not a valid local variable declaration" % (line,))
items = line[start:end].split(';')
localVars = {}
for item in items:
if len(item.strip()) == 0:
continue
split = item.split(':')
if len(split) != 2:
raise ValueError("%r contains invalid declaration %r"
% (line, item))
localVars[split[0].strip()] = split[1].strip()
return localVars
def loadLocalVariables(filename):
"""Accepts a filename and attempts to load the Emacs variable declarations
from that file, simulating what Emacs does.
See http://www.gnu.org/software/emacs/manual/html_node/File-Variables.html
"""
f = file(filename, "r")
lines = [f.readline(), f.readline()]
f.close()
for line in lines:
try:
return _parseLocalVariables(line)
except ValueError:
pass
return {}
def getTestModules(filename):
testCaseVar = loadLocalVariables(filename).get('test-case-name', None)
if testCaseVar is None:
return []
return testCaseVar.split(',')
def isTestFile(filename):
"""Returns true if 'filename' looks like a file containing unit tests.
False otherwise. Doesn't care whether filename exists.
"""
basename = os.path.basename(filename)
return (basename.startswith('test_')
and os.path.splitext(basename)[1] == ('.py'))
def _zshReporterAction():
return "(%s)" % (" ".join([p.longOpt for p in plugin.getPlugins(itrial.IReporter)]),)
class Options(usage.Options, app.ReactorSelectionMixin):
synopsis = """%s [options] [[file|package|module|TestCase|testmethod]...]
""" % (os.path.basename(sys.argv[0]),)
optFlags = [["help", "h"],
["rterrors", "e", "realtime errors, print out tracebacks as "
"soon as they occur"],
["debug", "b", "Run tests in the Python debugger. Will load "
"'.pdbrc' from current directory if it exists."],
["debug-stacktraces", "B", "Report Deferred creation and "
"callback stack traces"],
["nopm", None, "don't automatically jump into debugger for "
"postmorteming of exceptions"],
["dry-run", 'n', "do everything but run the tests"],
["force-gc", None, "Have Trial run gc.collect() before and "
"after each test case."],
["profile", None, "Run tests under the Python profiler"],
["until-failure", "u", "Repeat test until it fails"],
["no-recurse", "N", "Don't recurse into packages"],
['help-reporters', None,
"Help on available output plugins (reporters)"]
]
optParameters = [
["logfile", "l", "test.log", "log file name"],
["random", "z", None,
"Run tests in random order using the specified seed"],
['temp-directory', None, '_trial_temp',
'Path to use as working directory for tests.'],
['reporter', None, 'verbose',
'The reporter to use for this test run. See --help-reporters for '
'more info.']]
zsh_actions = {"tbformat":"(plain emacs cgitb)",
"reporter":_zshReporterAction}
zsh_actionDescr = {"logfile":"log file name",
"random":"random seed"}
zsh_extras = ["*:file|module|package|TestCase|testMethod:_files -g '*.py'"]
fallbackReporter = reporter.TreeReporter
extra = None
tracer = None
def __init__(self):
self['tests'] = sets.Set()
usage.Options.__init__(self)
def opt_coverage(self):
"""
Generate coverage information in the _trial_temp/coverage. Requires
Python 2.3.3.
"""
coverdir = 'coverage'
print "Setting coverage directory to %s." % (coverdir,)
import trace
# begin monkey patch ---------------------------
# Before Python 2.4, this function asserted that 'filename' had
# to end with '.py' This is wrong for at least two reasons:
# 1. We might be wanting to find executable line nos in a script
# 2. The implementation should use os.splitext
# This monkey patch is the same function as in the stdlib (v2.3)
# but with the assertion removed.
def find_executable_linenos(filename):
"""Return dict where keys are line numbers in the line number
table.
"""
#assert filename.endswith('.py') # YOU BASTARDS
try:
prog = open(filename).read()
prog = '\n'.join(prog.splitlines()) + '\n'
except IOError, err:
sys.stderr.write("Not printing coverage data for %r: %s\n"
% (filename, err))
sys.stderr.flush()
return {}
code = compile(prog, filename, "exec")
strs = trace.find_strings(filename)
return trace.find_lines(code, strs)
trace.find_executable_linenos = find_executable_linenos
# end monkey patch ------------------------------
self.coverdir = os.path.abspath(os.path.join(self['temp-directory'], coverdir))
self.tracer = trace.Trace(count=1, trace=0)
sys.settrace(self.tracer.globaltrace)
def opt_testmodule(self, filename):
"Filename to grep for test cases (-*- test-case-name)"
# If the filename passed to this parameter looks like a test module
# we just add that to the test suite.
#
# If not, we inspect it for an Emacs buffer local variable called
# 'test-case-name'. If that variable is declared, we try to add its
# value to the test suite as a module.
#
# This parameter allows automated processes (like Buildbot) to pass
# a list of files to Trial with the general expectation of "these files,
# whatever they are, will get tested"
if not os.path.isfile(filename):
sys.stderr.write("File %r doesn't exist\n" % (filename,))
return
filename = os.path.abspath(filename)
if isTestFile(filename):
self['tests'].add(filename)
else:
self['tests'].update(getTestModules(filename))
def opt_spew(self):
"""Print an insanely verbose log of everything that happens. Useful
when debugging freezes or locks in complex code."""
sys.settrace(spewer)
def opt_help_reporters(self):
synopsis = ("Trial's output can be customized using plugins called "
"Reporters. You can\nselect any of the following "
"reporters using --reporter=<foo>\n")
print synopsis
for p in plugin.getPlugins(itrial.IReporter):
print ' ', p.longOpt, '\t', p.description
print
sys.exit(0)
def opt_disablegc(self):
"""Disable the garbage collector"""
gc.disable()
def opt_tbformat(self, opt):
"""Specify the format to display tracebacks with. Valid formats are
'plain', 'emacs', and 'cgitb' which uses the nicely verbose stdlib
cgitb.text function"""
try:
self['tbformat'] = TBFORMAT_MAP[opt]
except KeyError:
raise usage.UsageError(
"tbformat must be 'plain', 'emacs', or 'cgitb'.")
def opt_extra(self, arg):
"""
Add an extra argument. (This is a hack necessary for interfacing with
emacs's `gud'.)
"""
if self.extra is None:
self.extra = []
self.extra.append(arg)
opt_x = opt_extra
def opt_recursionlimit(self, arg):
"""see sys.setrecursionlimit()"""
try:
sys.setrecursionlimit(int(arg))
except (TypeError, ValueError):
raise usage.UsageError(
"argument to recursionlimit must be an integer")
def opt_random(self, option):
try:
self['random'] = long(option)
except ValueError:
raise usage.UsageError(
"Argument to --random must be a positive integer")
else:
if self['random'] < 0:
raise usage.UsageError(
"Argument to --random must be a positive integer")
elif self['random'] == 0:
self['random'] = long(time.time() * 100)
def parseArgs(self, *args):
self['tests'].update(args)
if self.extra is not None:
self['tests'].update(self.extra)
def _loadReporterByName(self, name):
for p in plugin.getPlugins(itrial.IReporter):
qual = "%s.%s" % (p.module, p.klass)
if p.longOpt == name:
return reflect.namedAny(qual)
raise usage.UsageError("Only pass names of Reporter plugins to "
"--reporter. See --help-reporters for "
"more info.")
def postOptions(self):
# Only load reporters now, as opposed to any earlier, to avoid letting
# application-defined plugins muck up reactor selecting by importing
# t.i.reactor and causing the default to be installed.
self['reporter'] = self._loadReporterByName(self['reporter'])
if not self.has_key('tbformat'):
self['tbformat'] = 'default'
if self['nopm']:
if not self['debug']:
raise usage.UsageError("you must specify --debug when using "
"--nopm ")
failure.DO_POST_MORTEM = False
def _initialDebugSetup(config):
# do this part of debug setup first for easy debugging of import failures
if config['debug']:
failure.startDebugMode()
if config['debug'] or config['debug-stacktraces']:
defer.setDebugging(True)
def _getSuite(config):
loader = _getLoader(config)
recurse = not config['no-recurse']
return loader.loadByNames(config['tests'], recurse)
def _getLoader(config):
loader = runner.TestLoader()
if config['random']:
randomer = random.Random()
randomer.seed(config['random'])
loader.sorter = lambda x : randomer.random()
print 'Running tests shuffled with seed %d\n' % config['random']
if config['force-gc']:
loader.forceGarbageCollection = True
return loader
def _makeRunner(config):
mode = None
if config['debug']:
mode = runner.TrialRunner.DEBUG
if config['dry-run']:
mode = runner.TrialRunner.DRY_RUN
return runner.TrialRunner(config['reporter'],
mode=mode,
profile=config['profile'],
logfile=config['logfile'],
tracebackFormat=config['tbformat'],
realTimeErrors=config['rterrors'],
workingDirectory=config['temp-directory'])
def run():
if len(sys.argv) == 1:
sys.argv.append("--help")
config = Options()
try:
config.parseOptions()
except usage.error, ue:
raise SystemExit, "%s: %s" % (sys.argv[0], ue)
_initialDebugSetup(config)
trialRunner = _makeRunner(config)
suite = _getSuite(config)
if config['until-failure']:
test_result = trialRunner.runUntilFailure(suite)
else:
test_result = trialRunner.run(suite)
if config.tracer:
sys.settrace(None)
results = config.tracer.results()
results.write_results(show_missing=1, summary=False,
coverdir=config.coverdir)
sys.exit(not test_result.wasSuccessful()) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/scripts/trial.py | trial.py |
#
"""man2lore: Converts man page source (i.e. groff) into lore-compatible html.
This is nasty and hackish (and doesn't support lots of real groff), but is good
enough for converting fairly simple man pages.
"""
from __future__ import nested_scopes
import re, os
quoteRE = re.compile('"(.*?)"')
def escape(text):
text = text.replace('<', '<').replace('>', '>')
text = quoteRE.sub('<q>\\1</q>', text)
return text
def stripQuotes(s):
if s[0] == s[-1] == '"':
s = s[1:-1]
return s
class ManConverter:
state = 'regular'
name = None
tp = 0
dl = 0
para = 0
def convert(self, inf, outf):
self.write = outf.write
longline = ''
for line in inf.readlines():
if line.rstrip() and line.rstrip()[-1] == '\\':
longline += line.rstrip()[:-1] + ' '
continue
if longline:
line = longline + line
longline = ''
self.lineReceived(line)
self.closeTags()
self.write('</body>\n</html>\n')
def lineReceived(self, line):
if line[0] == '.':
f = getattr(self, 'macro_' + line[1:3].rstrip().upper(), None)
if f:
f(line[3:].strip())
else:
self.text(line)
def continueReceived(self, cont):
if not cont:
return
if cont[0].isupper():
f = getattr(self, 'macro_' + cont[:2].rstrip().upper(), None)
if f:
f(cont[2:].strip())
else:
self.text(cont)
def closeTags(self):
if self.state != 'regular':
self.write('</%s>' % self.state)
if self.tp == 3:
self.write('</dd>\n\n')
self.tp = 0
if self.dl:
self.write('</dl>\n\n')
self.dl = 0
if self.para:
self.write('</p>\n\n')
self.para = 0
def paraCheck(self):
if not self.tp and not self.para:
self.write('<p>')
self.para = 1
def macro_TH(self, line):
self.write('<html><head>\n')
parts = [stripQuotes(x) for x in line.split(' ', 2)] + ['', '']
title, manSection = parts[:2]
self.write('<title>%s.%s</title>' % (title, manSection))
self.write('</head>\n<body>\n\n')
self.write('<h1>%s.%s</h1>\n\n' % (title, manSection))
macro_DT = macro_TH
def macro_SH(self, line):
self.closeTags()
self.write('<h2>')
self.para = 1
self.text(stripQuotes(line))
self.para = 0
self.closeTags()
self.write('</h2>\n\n')
def macro_B(self, line):
words = line.split()
words[0] = '\\fB' + words[0] + '\\fR '
self.text(' '.join(words))
def macro_NM(self, line):
if not self.name:
self.name = line
self.text(self.name + ' ')
def macro_NS(self, line):
parts = line.split(' Ns ')
i = 0
for l in parts:
i = not i
if i:
self.text(l)
else:
self.continueReceived(l)
def macro_OO(self, line):
self.text('[')
self.continueReceived(line)
def macro_OC(self, line):
self.text(']')
self.continueReceived(line)
def macro_OP(self, line):
self.text('[')
self.continueReceived(line)
self.text(']')
def macro_FL(self, line):
parts = line.split()
self.text('\\fB-%s\\fR' % parts[0])
self.continueReceived(' '.join(parts[1:]))
def macro_AR(self, line):
parts = line.split()
self.text('\\fI %s\\fR' % parts[0])
self.continueReceived(' '.join(parts[1:]))
def macro_PP(self, line):
self.closeTags()
def macro_TP(self, line):
if self.tp == 3:
self.write('</dd>\n\n')
self.tp = 1
def macro_BL(self, line):
#assert self.tp == 0, self.tp
self.write('<dl>')
self.tp = 1
def macro_EL(self, line):
if self.tp == 3:
self.write('</dd>')
self.tp = 1
#assert self.tp == 1, self.tp
self.write('</dl>\n\n')
self.tp = 0
def macro_IT(self, line):
if self.tp == 3:
self.write('</dd>')
self.tp = 1
#assert self.tp == 1, (self.tp, line)
self.write('\n<dt>')
self.continueReceived(line)
self.write('</dt>')
self.tp = 2
def text(self, line):
if self.tp == 2:
self.write('<dd>')
self.paraCheck()
bits = line.split('\\')
self.write(escape(bits[0]))
for bit in bits[1:]:
if bit[:2] == 'fI':
self.write('<em>' + escape(bit[2:]))
self.state = 'em'
elif bit[:2] == 'fB':
self.write('<strong>' + escape(bit[2:]))
self.state = 'strong'
elif bit[:2] == 'fR':
self.write('</%s>' % self.state)
self.write(escape(bit[2:]))
self.state = 'regular'
elif bit[:3] == '(co':
self.write('©' + escape(bit[3:]))
else:
self.write(escape(bit))
if self.tp == 2:
self.tp = 3
class ProcessingFunctionFactory:
def generate_lore(self, d, filenameGenerator=None):
ext = d.get('ext', '.html')
return lambda file,_: ManConverter().convert(open(file),
open(os.path.splitext(file)[0]+ext, 'w'))
factory = ProcessingFunctionFactory()
if __name__ == '__main__':
import sys
mc = ManConverter().convert(open(sys.argv[1]), sys.stdout) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/lore/man2lore.py | man2lore.py |
#
from cStringIO import StringIO
import os, re, cgi
from twisted.python import text
from twisted.web import domhelpers, microdom
import latex, tree
class DocbookSpitter(latex.BaseLatexSpitter):
currentLevel = 1
def writeNodeData(self, node):
self.writer(node.data)
def visitNode_body(self, node):
self.visitNodeDefault(node)
self.writer('</section>'*self.currentLevel)
def visitNodeHeader(self, node):
level = int(node.tagName[1])
difference, self.currentLevel = level-self.currentLevel, level
self.writer('<section>'*difference+'</section>'*-difference)
if difference<=0:
self.writer('</section>\n<section>')
self.writer('<title>')
self.visitNodeDefault(node)
def visitNode_a_listing(self, node):
fileName = os.path.join(self.currDir, node.getAttribute('href'))
self.writer('<programlisting>\n')
self.writer(cgi.escape(open(fileName).read()))
self.writer('</programlisting>\n')
def visitNode_a_href(self, node):
self.visitNodeDefault(node)
def visitNode_a_name(self, node):
self.visitNodeDefault(node)
def visitNode_li(self, node):
for child in node.childNodes:
if getattr(child, 'tagName', None) != 'p':
new = microdom.Element('p')
new.childNodes = [child]
node.replaceChild(new, child)
self.visitNodeDefault(node)
visitNode_h2 = visitNode_h3 = visitNode_h4 = visitNodeHeader
end_h2 = end_h3 = end_h4 = '</title><para />'
start_title, end_title = '<section><title>', '</title><para />'
start_p, end_p = '<para>', '</para>'
start_strong, end_strong = start_em, end_em = '<emphasis>', '</emphasis>'
start_span_footnote, end_span_footnote = '<footnote><para>', '</para></footnote>'
start_q = end_q = '"'
start_pre, end_pre = '<programlisting>', '</programlisting>'
start_div_note, end_div_note = '<note>', '</note>'
start_li, end_li = '<listitem>', '</listitem>'
start_ul, end_ul = '<itemizedlist>', '</itemizedlist>'
start_ol, end_ol = '<orderedlist>', '</orderedlist>'
start_dl, end_dl = '<variablelist>', '</variablelist>'
start_dt, end_dt = '<varlistentry><term>', '</term>'
start_dd, end_dd = '<listitem><para>', '</para></listitem></varlistentry>' | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/lore/docbook.py | docbook.py |
#
from twisted.web import microdom, domhelpers
from twisted.python import text, procutils
import os, os.path, re, string
from cStringIO import StringIO
import urlparse
import tree
escapingRE = re.compile(r'([\[\]#$%&_{}^~\\])')
lowerUpperRE = re.compile(r'([a-z])([A-Z])')
def _escapeMatch(match):
c = match.group()
if c == '\\':
return '$\\backslash$'
elif c == '~':
return '\\~{}'
elif c == '^':
return '\\^{}'
elif c in '[]':
return '{'+c+'}'
else:
return '\\' + c
def latexEscape(text):
text = escapingRE.sub(_escapeMatch, text)
return text.replace('\n', ' ')
entities = {'amp': '\&', 'gt': '>', 'lt': '<', 'quot': '"',
'copy': '\\copyright', 'mdash': '---', 'rdquo': '``',
'ldquo': "''"}
def realpath(path):
# Normalise path
cwd = os.getcwd()
path = os.path.normpath(os.path.join(cwd, path))
if path.startswith(cwd + '/'):
path = path[len(cwd)+1:]
return path.replace('\\', '/') # windows slashes make LaTeX blow up
def getLatexText(node, writer, filter=lambda x:x, entities=entities):
if hasattr(node, 'eref'):
return writer(entities.get(node.eref, ''))
if hasattr(node, 'data'):
return writer(filter(node.data))
for child in node.childNodes:
getLatexText(child, writer, filter, entities)
class BaseLatexSpitter:
def __init__(self, writer, currDir='.', filename=''):
self.writer = writer
self.currDir = currDir
self.filename = filename
def visitNode(self, node):
if isinstance(node, microdom.Comment):
return
if not hasattr(node, 'tagName'):
self.writeNodeData(node)
return
getattr(self, 'visitNode_'+node.tagName, self.visitNodeDefault)(node)
def visitNodeDefault(self, node):
self.writer(getattr(self, 'start_'+node.tagName, ''))
for child in node.childNodes:
self.visitNode(child)
self.writer(getattr(self, 'end_'+node.tagName, ''))
def visitNode_a(self, node):
if node.hasAttribute('class'):
if node.getAttribute('class').endswith('listing'):
return self.visitNode_a_listing(node)
if node.hasAttribute('href'):
return self.visitNode_a_href(node)
if node.hasAttribute('name'):
return self.visitNode_a_name(node)
self.visitNodeDefault(node)
def visitNode_span(self, node):
if not node.hasAttribute('class'):
return self.visitNodeDefault(node)
node.tagName += '_'+node.getAttribute('class')
self.visitNode(node)
visitNode_div = visitNode_span
def visitNode_h1(self, node):
pass
def visitNode_style(self, node):
pass
class LatexSpitter(BaseLatexSpitter):
baseLevel = 0
diaHack = bool(procutils.which("dia"))
def writeNodeData(self, node):
buf = StringIO()
getLatexText(node, buf.write, latexEscape)
self.writer(buf.getvalue().replace('<', '$<$').replace('>', '$>$'))
def visitNode_head(self, node):
authorNodes = domhelpers.findElementsWithAttribute(node, 'rel', 'author')
authorNodes = [n for n in authorNodes if n.tagName == 'link']
if authorNodes:
self.writer('\\author{')
authors = []
for aNode in authorNodes:
name = aNode.getAttribute('title', '')
href = aNode.getAttribute('href', '')
if href.startswith('mailto:'):
href = href[7:]
if href:
if name:
name += ' '
name += '$<$' + href + '$>$'
if name:
authors.append(name)
self.writer(' \\and '.join(authors))
self.writer('}')
self.visitNodeDefault(node)
def visitNode_pre(self, node):
self.writer('\\begin{verbatim}\n')
buf = StringIO()
getLatexText(node, buf.write)
self.writer(text.removeLeadingTrailingBlanks(buf.getvalue()))
self.writer('\\end{verbatim}\n')
def visitNode_code(self, node):
fout = StringIO()
getLatexText(node, fout.write, latexEscape)
data = lowerUpperRE.sub(r'\1\\linebreak[1]\2', fout.getvalue())
data = data[:1] + data[1:].replace('.', '.\\linebreak[1]')
self.writer('\\texttt{'+data+'}')
def visitNode_img(self, node):
fileName = os.path.join(self.currDir, node.getAttribute('src'))
target, ext = os.path.splitext(fileName)
if self.diaHack and os.access(target + '.dia', os.R_OK):
ext = '.dia'
fileName = target + ext
f = getattr(self, 'convert_'+ext[1:], None)
if not f:
return
target = os.path.join(self.currDir, os.path.basename(target)+'.eps')
f(fileName, target)
target = os.path.basename(target)
self._write_img(target)
def _write_img(self, target):
"""Write LaTeX for image."""
self.writer('\\begin{center}\\includegraphics[%%\n'
'width=1.0\n'
'\\textwidth,height=1.0\\textheight,\nkeepaspectratio]'
'{%s}\\end{center}\n' % target)
def convert_png(self, src, target):
# XXX there's a *reason* Python comes with the pipes module -
# someone fix this to use it.
r = os.system('pngtopnm "%s" | pnmtops -noturn > "%s"' % (src, target))
if r != 0:
raise OSError(r)
def convert_dia(self, src, target):
# EVIL DISGUSTING HACK
data = os.popen("gunzip -dc %s" % (src)).read()
pre = '<dia:attribute name="scaling">\n <dia:real val="1"/>'
post = '<dia:attribute name="scaling">\n <dia:real val="0.5"/>'
open('%s_hacked.dia' % (src), 'wb').write(data.replace(pre, post))
os.system('gzip %s_hacked.dia' % (src,))
os.system('mv %s_hacked.dia.gz %s_hacked.dia' % (src,src))
# Let's pretend we never saw that.
# Silly dia needs an X server, even though it doesn't display anything.
# If this is a problem for you, try using Xvfb.
os.system("dia %s_hacked.dia -n -e %s" % (src, target))
def visitNodeHeader(self, node):
level = (int(node.tagName[1])-2)+self.baseLevel
self.writer('\n\n\\'+level*'sub'+'section{')
spitter = HeadingLatexSpitter(self.writer, self.currDir, self.filename)
spitter.visitNodeDefault(node)
self.writer('}\n')
def visitNode_a_listing(self, node):
fileName = os.path.join(self.currDir, node.getAttribute('href'))
self.writer('\\begin{verbatim}\n')
lines = map(string.rstrip, open(fileName).readlines())
lines = lines[int(node.getAttribute('skipLines', 0)):]
self.writer(text.removeLeadingTrailingBlanks('\n'.join(lines)))
self.writer('\\end{verbatim}')
# Write a caption for this source listing
fileName = os.path.basename(fileName)
caption = domhelpers.getNodeText(node)
if caption == fileName:
caption = 'Source listing'
self.writer('\parbox[b]{\linewidth}{\\begin{center}%s --- '
'\\begin{em}%s\\end{em}\\end{center}}'
% (latexEscape(caption), latexEscape(fileName)))
def visitNode_a_href(self, node):
supported_schemes=['http', 'https', 'ftp', 'mailto']
href = node.getAttribute('href')
if urlparse.urlparse(href)[0] in supported_schemes:
text = domhelpers.getNodeText(node)
self.visitNodeDefault(node)
if text != href:
self.writer('\\footnote{%s}' % latexEscape(href))
else:
path, fragid = (href.split('#', 1) + [None])[:2]
if path == '':
path = self.filename
else:
path = os.path.join(os.path.dirname(self.filename), path)
#if path == '':
#path = os.path.basename(self.filename)
#else:
# # Hack for linking to man pages from howtos, i.e.
# # ../doc/foo-man.html -> foo-man.html
# path = os.path.basename(path)
path = realpath(path)
if fragid:
ref = path + 'HASH' + fragid
else:
ref = path
self.writer('\\textit{')
self.visitNodeDefault(node)
self.writer('}')
self.writer('\\loreref{%s}' % ref)
def visitNode_a_name(self, node):
#self.writer('\\label{%sHASH%s}' % (os.path.basename(self.filename),
# node.getAttribute('name')))
self.writer('\\label{%sHASH%s}' % (realpath(self.filename),
node.getAttribute('name')))
self.visitNodeDefault(node)
def visitNode_table(self, node):
rows = [[col for col in row.childNodes
if getattr(col, 'tagName', None) in ('th', 'td')]
for row in node.childNodes if getattr(row, 'tagName', None)=='tr']
numCols = 1+max([len(row) for row in rows])
self.writer('\\begin{table}[ht]\\begin{center}')
self.writer('\\begin{tabular}{@{}'+'l'*numCols+'@{}}')
for row in rows:
th = 0
for col in row:
self.visitNode(col)
self.writer('&')
if col.tagName == 'th':
th = 1
self.writer('\\\\\n') #\\ ends lines
if th:
self.writer('\\hline\n')
self.writer('\\end{tabular}\n')
if node.hasAttribute('title'):
self.writer('\\caption{%s}'
% latexEscape(node.getAttribute('title')))
self.writer('\\end{center}\\end{table}\n')
def visitNode_span_footnote(self, node):
self.writer('\\footnote{')
spitter = FootnoteLatexSpitter(self.writer, self.currDir, self.filename)
spitter.visitNodeDefault(node)
self.writer('}')
def visitNode_span_index(self, node):
self.writer('\\index{%s}\n' % node.getAttribute('value'))
self.visitNodeDefault(node)
visitNode_h2 = visitNode_h3 = visitNode_h4 = visitNodeHeader
start_title = '\\title{'
end_title = '}\n'
start_sub = '$_{'
end_sub = '}$'
start_sup = '$^{'
end_sup = '}$'
start_html = '''\\documentclass{article}
\\newcommand{\\loreref}[1]{%
\\ifthenelse{\\value{page}=\\pageref{#1}}%
{ (this page)}%
{ (page \\pageref{#1})}%
}'''
start_body = '\\begin{document}\n\\maketitle\n'
end_body = '\\end{document}'
start_dl = '\\begin{description}\n'
end_dl = '\\end{description}\n'
start_ul = '\\begin{itemize}\n'
end_ul = '\\end{itemize}\n'
start_ol = '\\begin{enumerate}\n'
end_ol = '\\end{enumerate}\n'
start_li = '\\item '
end_li = '\n'
start_dt = '\\item['
end_dt = ']'
end_dd = '\n'
start_p = '\n\n'
start_strong = start_em = '\\begin{em}'
end_strong = end_em = '\\end{em}'
start_q = "``"
end_q = "''"
start_div_note = '\\begin{quotation}\\textbf{Note:}'
end_div_note = '\\end{quotation}'
start_th = '\\textbf{'
end_th = '}'
class SectionLatexSpitter(LatexSpitter):
baseLevel = 1
start_title = '\\section{'
def visitNode_title(self, node):
self.visitNodeDefault(node)
#self.writer('\\label{%s}}\n' % os.path.basename(self.filename))
self.writer('\\label{%s}}\n' % realpath(self.filename))
end_title = end_body = start_body = start_html = ''
class ChapterLatexSpitter(SectionLatexSpitter):
baseLevel = 0
start_title = '\\chapter{'
class HeadingLatexSpitter(BaseLatexSpitter):
start_q = "``"
end_q = "''"
writeNodeData = LatexSpitter.writeNodeData.im_func
class FootnoteLatexSpitter(LatexSpitter):
"""For multi-paragraph footnotes, this avoids having an empty leading
paragraph."""
start_p = ''
def visitNode_span_footnote(self, node):
self.visitNodeDefault(node)
def visitNode_p(self, node):
self.visitNodeDefault(node)
self.start_p = LatexSpitter.start_p
class BookLatexSpitter(LatexSpitter):
def visitNode_body(self, node):
tocs=domhelpers.locateNodes([node], 'class', 'toc')
domhelpers.clearNode(node)
if len(tocs):
toc=tocs[0]
node.appendChild(toc)
self.visitNodeDefault(node)
def visitNode_link(self, node):
if not node.hasAttribute('rel'):
return self.visitNodeDefault(node)
node.tagName += '_'+node.getAttribute('rel')
self.visitNode(node)
def visitNode_link_author(self, node):
self.writer('\\author{%s}\n' % node.getAttribute('text'))
def visitNode_link_stylesheet(self, node):
if node.hasAttribute('type') and node.hasAttribute('href'):
if node.getAttribute('type')=='application/x-latex':
packagename=node.getAttribute('href')
packagebase,ext=os.path.splitext(packagename)
self.writer('\\usepackage{%s}\n' % packagebase)
start_html = r'''\documentclass[oneside]{book}
\usepackage{graphicx}
\usepackage{times,mathptmx}
'''
start_body = r'''\begin{document}
\maketitle
\tableofcontents
'''
start_li=''
end_li=''
start_ul=''
end_ul=''
def visitNode_a(self, node):
if node.hasAttribute('class'):
a_class=node.getAttribute('class')
if a_class.endswith('listing'):
return self.visitNode_a_listing(node)
else:
return getattr(self, 'visitNode_a_%s' % a_class)(node)
if node.hasAttribute('href'):
return self.visitNode_a_href(node)
if node.hasAttribute('name'):
return self.visitNode_a_name(node)
self.visitNodeDefault(node)
def visitNode_a_chapter(self, node):
self.writer('\\chapter{')
self.visitNodeDefault(node)
self.writer('}\n')
def visitNode_a_sect(self, node):
base,ext=os.path.splitext(node.getAttribute('href'))
self.writer('\\input{%s}\n' % base)
def processFile(spitter, fin):
dom = microdom.parse(fin).documentElement
spitter.visitNode(dom)
def convertFile(filename, spitterClass):
fout = open(os.path.splitext(filename)[0]+".tex", 'w')
spitter = spitterClass(fout.write, os.path.dirname(filename), filename)
fin = open(filename)
processFile(spitter, fin)
fin.close()
fout.close() | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/lore/latex.py | latex.py |
#
from twisted.lore import tree, process
from twisted.web import domhelpers, microdom
from twisted.python import reflect
import parser, urlparse, os.path
# parser.suite in Python 2.3 raises SyntaxError, <2.3 raises parser.ParserError
parserErrors = (SyntaxError, parser.ParserError)
class TagChecker:
def check(self, dom, filename):
self.hadErrors = 0
for method in reflect.prefixedMethods(self, 'check_'):
method(dom, filename)
if self.hadErrors:
raise process.ProcessingFailure("invalid format")
def _reportError(self, filename, element, error):
hlint = element.hasAttribute('hlint') and element.getAttribute('hlint')
if hlint != 'off':
self.hadErrors = 1
pos = getattr(element, '_markpos', None) or (0, 0)
print "%s:%s:%s: %s" % ((filename,)+pos+(error,))
class DefaultTagChecker(TagChecker):
def __init__(self, allowedTags, allowedClasses):
self.allowedTags = allowedTags
self.allowedClasses = allowedClasses
def check_disallowedElements(self, dom, filename):
def m(node, self=self):
return not self.allowedTags(node.tagName)
for element in domhelpers.findElements(dom, m):
self._reportError(filename, element,
'unrecommended tag %s' % element.tagName)
def check_disallowedClasses(self, dom, filename):
def matcher(element, self=self):
if not element.hasAttribute('class'):
return 0
checker = self.allowedClasses.get(element.tagName, lambda x:0)
return not checker(element.getAttribute('class'))
for element in domhelpers.findElements(dom, matcher):
self._reportError(filename, element,
'unknown class %s' %element.getAttribute('class'))
def check_quote(self, dom, filename):
def matcher(node):
return ('"' in getattr(node, 'data', '') and
not isinstance(node, microdom.Comment) and
not [1 for n in domhelpers.getParents(node)[1:-1]
if n.tagName in ('pre', 'code')])
for node in domhelpers.findNodes(dom, matcher):
self._reportError(filename, node.parentNode, 'contains quote')
def check_styleattr(self, dom, filename):
for node in domhelpers.findElementsWithAttribute(dom, 'style'):
self._reportError(filename, node, 'explicit style')
def check_align(self, dom, filename):
for node in domhelpers.findElementsWithAttribute(dom, 'align'):
self._reportError(filename, node, 'explicit alignment')
def check_style(self, dom, filename):
for node in domhelpers.findNodesNamed(dom, 'style'):
if domhelpers.getNodeText(node) != '':
self._reportError(filename, node, 'hand hacked style')
def check_title(self, dom, filename):
doc = dom.documentElement
title = domhelpers.findNodesNamed(dom, 'title')
if len(title)!=1:
return self._reportError(filename, doc, 'not exactly one title')
h1 = domhelpers.findNodesNamed(dom, 'h1')
if len(h1)!=1:
return self._reportError(filename, doc, 'not exactly one h1')
if domhelpers.getNodeText(h1[0]) != domhelpers.getNodeText(title[0]):
self._reportError(filename, h1[0], 'title and h1 text differ')
def check_80_columns(self, dom, filename):
for node in domhelpers.findNodesNamed(dom, 'pre'):
# the ps/pdf output is in a font that cuts off at 80 characters,
# so this is enforced to make sure the interesting parts (which
# are likely to be on the right-hand edge) stay on the printed
# page.
for line in domhelpers.gatherTextNodes(node, 1).split('\n'):
if len(line.rstrip()) > 80:
self._reportError(filename, node,
'text wider than 80 columns in pre')
for node in domhelpers.findNodesNamed(dom, 'a'):
if node.getAttribute('class', '').endswith('listing'):
try:
fn = os.path.dirname(filename)
fn = os.path.join(fn, node.getAttribute('href'))
lines = open(fn,'r').readlines()
except:
self._reportError(filename, node,
'bad listing href: %r' %
node.getAttribute('href'))
continue
for line in lines:
if len(line.rstrip()) > 80:
self._reportError(filename, node,
'listing wider than 80 columns')
def check_pre_py_listing(self, dom, filename):
for node in domhelpers.findNodesNamed(dom, 'pre'):
if node.getAttribute('class') == 'python':
try:
text = domhelpers.getNodeText(node)
# Fix < and >
text = text.replace('>', '>').replace('<', '<')
# Strip blank lines
lines = filter(None,[l.rstrip() for l in text.split('\n')])
# Strip leading space
while not [1 for line in lines if line[:1] not in ('',' ')]:
lines = [line[1:] for line in lines]
text = '\n'.join(lines) + '\n'
try:
parser.suite(text)
except parserErrors, e:
# Pretend the "..." idiom is syntactically valid
text = text.replace("...","'...'")
parser.suite(text)
except parserErrors, e:
self._reportError(filename, node,
'invalid python code:' + str(e))
def check_anchor_in_heading(self, dom, filename):
headingNames = ['h%d' % n for n in range(1,7)]
for hname in headingNames:
for node in domhelpers.findNodesNamed(dom, hname):
if domhelpers.findNodesNamed(node, 'a'):
self._reportError(filename, node, 'anchor in heading')
def check_texturl_matches_href(self, dom, filename):
for node in domhelpers.findNodesNamed(dom, 'a'):
if not node.hasAttribute('href'):
continue
text = domhelpers.getNodeText(node)
proto = urlparse.urlparse(text)[0]
if proto and ' ' not in text:
if text != node.getAttribute('href',''):
self._reportError(filename, node,
'link text does not match href')
def check_a_py_listing(self, dom, filename):
for node in domhelpers.findNodesNamed(dom, 'a'):
if node.getAttribute('class') == 'py-listing':
fn = os.path.join(os.path.dirname(filename),
node.getAttribute('href'))
lines = open(fn).readlines()
lines = lines[int(node.getAttribute('skipLines', 0)):]
for line, num in zip(lines, range(len(lines))):
if line.count('59 Temple Place, Suite 330, Boston'):
self._reportError(filename, node,
'included source file %s has licence boilerplate.'
' Use skipLines="%d".'
% (fn, int(node.getAttribute('skipLines',0))+num+1))
def check_lists(self, dom, filename):
for node in (domhelpers.findNodesNamed(dom, 'ul')+
domhelpers.findNodesNamed(dom, 'ol')):
if not node.childNodes:
self._reportError(filename, node, 'empty list')
for child in node.childNodes:
if child.nodeName != 'li':
self._reportError(filename, node,
'only list items allowed in lists')
def list2dict(l):
d = {}
for el in l:
d[el] = None
return d
classes = list2dict(['shell', 'API', 'python', 'py-prototype', 'py-filename',
'py-src-string', 'py-signature', 'py-src-parameter',
'py-src-identifier', 'py-src-keyword'])
tags = list2dict(["html", "title", "head", "body", "h1", "h2", "h3", "ol", "ul",
"dl", "li", "dt", "dd", "p", "code", "img", "blockquote", "a",
"cite", "div", "span", "strong", "em", "pre", "q", "table",
"tr", "td", "th", "style", "sub", "sup", "link"])
span = list2dict(['footnote', 'manhole-output', 'index'])
div = list2dict(['note', 'boxed', 'doit'])
a = list2dict(['listing', 'py-listing', 'html-listing', 'absolute'])
pre = list2dict(['python', 'shell', 'python-interpreter', 'elisp'])
allowed = {'code': classes.has_key, 'span': span.has_key, 'div': div.has_key,
'a': a.has_key, 'pre': pre.has_key, 'ul': lambda x: x=='toc',
'ol': lambda x: x=='toc', 'li': lambda x: x=='ignoretoc'}
def getDefaultChecker():
return DefaultTagChecker(tags.has_key, allowed)
def doFile(file, checker):
dom = tree.parseFileAndReport(file)
if dom:
checker.check(dom, file) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/lore/lint.py | lint.py |
import re, os, cStringIO, time, cgi, string, urlparse
from twisted import copyright
from twisted.python import htmlizer, text
from twisted.web import microdom, domhelpers
import process, latex, indexer, numberer, htmlbook
from twisted.python.util import InsensitiveDict
# relative links to html files
def fixLinks(document, ext):
"""
Rewrite links to XHTML lore input documents so they point to lore XHTML
output documents.
Any node with an C{href} attribute which does not contain a value starting
with C{http}, C{https}, C{ftp}, or C{mailto} and which does not have a
C{class} attribute of C{absolute} or which contains C{listing} and which
does point to an URL ending with C{html} will have that attribute value
rewritten so that the filename extension is C{ext} instead of C{html}.
@type document: A DOM Node or Document
@param document: The input document which contains all of the content to be
presented.
@type ext: C{str}
@param ext: The extension to use when selecting an output file name. This
replaces the extension of the input file name.
@return: C{None}
"""
supported_schemes=['http', 'https', 'ftp', 'mailto']
for node in domhelpers.findElementsWithAttribute(document, 'href'):
href = node.getAttribute("href")
if urlparse.urlparse(href)[0] in supported_schemes:
continue
if node.getAttribute("class", "") == "absolute":
continue
if node.getAttribute("class", "").find('listing') != -1:
continue
# This is a relative link, so it should be munged.
if href.endswith('html') or href[:href.rfind('#')].endswith('html'):
fname, fext = os.path.splitext(href)
if '#' in fext:
fext = ext+'#'+fext.split('#', 1)[1]
else:
fext = ext
node.setAttribute("href", fname + fext)
def addMtime(document, fullpath):
"""
Set the last modified time of the given document.
@type document: A DOM Node or Document
@param document: The output template which defines the presentation of the
last modified time.
@type fullpath: C{str}
@param fullpath: The file name from which to take the last modified time.
@return: C{None}
"""
for node in domhelpers.findElementsWithAttribute(document, "class","mtime"):
node.appendChild(microdom.Text(time.ctime(os.path.getmtime(fullpath))))
def _getAPI(node):
"""
Retrieve the fully qualified Python name represented by the given node.
The name is represented by one or two aspects of the node: the value of the
node's first child forms the end of the name. If the node has a C{base}
attribute, that attribute's value is prepended to the node's value, with
C{.} separating the two parts.
@rtype: C{str}
@return: The fully qualified Python name.
"""
base = ""
if node.hasAttribute("base"):
base = node.getAttribute("base") + "."
return base+node.childNodes[0].nodeValue
def fixAPI(document, url):
"""
Replace API references with links to API documentation.
@type document: A DOM Node or Document
@param document: The input document which contains all of the content to be
presented.
@type url: C{str}
@param url: A string which will be interpolated with the fully qualified
Python name of any API reference encountered in the input document, the
result of which will be used as a link to API documentation for that name
in the output document.
@return: C{None}
"""
# API references
for node in domhelpers.findElementsWithAttribute(document, "class", "API"):
fullname = _getAPI(node)
node2 = microdom.Element('a', {'href': url%fullname, 'title': fullname})
node2.childNodes = node.childNodes
node.childNodes = [node2]
node.removeAttribute('base')
def fontifyPython(document):
"""
Syntax color any node in the given document which contains a Python source
listing.
@type document: A DOM Node or Document
@param document: The input document which contains all of the content to be
presented.
@return: C{None}
"""
def matcher(node):
return (node.nodeName == 'pre' and node.hasAttribute('class') and
node.getAttribute('class') == 'python')
for node in domhelpers.findElements(document, matcher):
fontifyPythonNode(node)
def fontifyPythonNode(node):
"""
Syntax color the given node containing Python source code.
@return: C{None}
"""
oldio = cStringIO.StringIO()
latex.getLatexText(node, oldio.write,
entities={'lt': '<', 'gt': '>', 'amp': '&'})
oldio = cStringIO.StringIO(oldio.getvalue().strip()+'\n')
newio = cStringIO.StringIO()
htmlizer.filter(oldio, newio, writer=htmlizer.SmallerHTMLWriter)
newio.seek(0)
newel = microdom.parse(newio).documentElement
newel.setAttribute("class", "python")
node.parentNode.replaceChild(newel, node)
def addPyListings(document, dir):
"""
Insert Python source listings into the given document from files in the
given directory based on C{py-listing} nodes.
Any node in C{document} with a C{class} attribute set to C{py-listing} will
have source lines taken from the file named in that node's C{href}
attribute (searched for in C{dir}) inserted in place of that node.
If a node has a C{skipLines} attribute, its value will be parsed as an
integer and that many lines will be skipped at the beginning of the source
file.
@type document: A DOM Node or Document
@param document: The document within which to make listing replacements.
@type dir: C{str}
@param dir: The directory in which to find source files containing the
referenced Python listings.
@return: C{None}
"""
for node in domhelpers.findElementsWithAttribute(document, "class",
"py-listing"):
filename = node.getAttribute("href")
outfile = cStringIO.StringIO()
lines = map(string.rstrip, open(os.path.join(dir, filename)).readlines())
data = '\n'.join(lines[int(node.getAttribute('skipLines', 0)):])
data = cStringIO.StringIO(text.removeLeadingTrailingBlanks(data))
htmlizer.filter(data, outfile, writer=htmlizer.SmallerHTMLWriter)
val = outfile.getvalue()
_replaceWithListing(node, val, filename, "py-listing")
def _replaceWithListing(node, val, filename, class_):
captionTitle = domhelpers.getNodeText(node)
if captionTitle == os.path.basename(filename):
captionTitle = 'Source listing'
text = ('<div class="%s">%s<div class="caption">%s - '
'<a href="%s"><span class="filename">%s</span></a></div></div>' %
(class_, val, captionTitle, filename, filename))
newnode = microdom.parseString(text).documentElement
node.parentNode.replaceChild(newnode, node)
def addHTMLListings(document, dir):
"""
Insert HTML source listings into the given document from files in the given
directory based on C{html-listing} nodes.
Any node in C{document} with a C{class} attribute set to C{html-listing}
will have source lines taken from the file named in that node's C{href}
attribute (searched for in C{dir}) inserted in place of that node.
@type document: A DOM Node or Document
@param document: The document within which to make listing replacements.
@type dir: C{str}
@param dir: The directory in which to find source files containing the
referenced HTML listings.
@return: C{None}
"""
for node in domhelpers.findElementsWithAttribute(document, "class",
"html-listing"):
filename = node.getAttribute("href")
val = ('<pre class="htmlsource">\n%s</pre>' %
cgi.escape(open(os.path.join(dir, filename)).read()))
_replaceWithListing(node, val, filename, "html-listing")
def addPlainListings(document, dir):
"""
Insert text listings into the given document from files in the given
directory based on C{listing} nodes.
Any node in C{document} with a C{class} attribute set to C{listing} will
have source lines taken from the file named in that node's C{href}
attribute (searched for in C{dir}) inserted in place of that node.
@type document: A DOM Node or Document
@param document: The document within which to make listing replacements.
@type dir: C{str}
@param dir: The directory in which to find source files containing the
referenced text listings.
@return: C{None}
"""
for node in domhelpers.findElementsWithAttribute(document, "class",
"listing"):
filename = node.getAttribute("href")
val = ('<pre>\n%s</pre>' %
cgi.escape(open(os.path.join(dir, filename)).read()))
_replaceWithListing(node, val, filename, "listing")
def getHeaders(document):
"""
Return all H2 and H3 nodes in the given document.
@type document: A DOM Node or Document
@rtype: C{list}
"""
return domhelpers.findElements(
document,
lambda n, m=re.compile('h[23]$').match: m(n.nodeName))
def generateToC(document):
"""
Create a table of contents for the given document.
@type document: A DOM Node or Document
@rtype: A DOM Node
@return: a Node containing a table of contents based on the headers of the
given document.
"""
toc, level, id = '\n<ol>\n', 0, 0
for element in getHeaders(document):
elementLevel = int(element.tagName[1])-2
toc += (level-elementLevel)*'</ul>\n'
toc += (elementLevel-level)*'<ul>'
toc += '<li><a href="#auto%d">' % id
toc += domhelpers.getNodeText(element)
toc += '</a></li>\n'
level = elementLevel
anchor = microdom.parseString('<a name="auto%d" />' % id).documentElement
element.childNodes.append(anchor)
id += 1
toc += '</ul>\n' * level
toc += '</ol>\n'
return microdom.parseString(toc).documentElement
def putInToC(document, toc):
"""
Insert the given table of contents into the given document.
The node with C{class} attribute set to C{toc} has its children replaced
with C{toc}.
@type document: A DOM Node or Document
@type toc: A DOM Node
"""
tocOrig = domhelpers.findElementsWithAttribute(document, 'class', 'toc')
if tocOrig:
tocOrig= tocOrig[0]
tocOrig.childNodes = [toc]
def removeH1(document):
"""
Replace all C{h1} nodes in the given document with empty C{span} nodes.
C{h1} nodes mark up document sections and the output template is given an
opportunity to present this information in a different way.
@type document: A DOM Node or Document
@param document: The input document which contains all of the content to be
presented.
@return: C{None}
"""
h1 = domhelpers.findNodesNamed(document, 'h1')
empty = microdom.Element('span')
for node in h1:
node.parentNode.replaceChild(empty, node)
def footnotes(document):
"""
Find footnotes in the given document, move them to the end of the body, and
generate links to them.
A footnote is any node with a C{class} attribute set to C{footnote}.
Footnote links are generated as superscript. Footnotes are collected in a
C{ol} node at the end of the document.
@type document: A DOM Node or Document
@param document: The input document which contains all of the content to be
presented.
@return: C{None}
"""
footnotes = domhelpers.findElementsWithAttribute(document, "class",
"footnote")
if not footnotes:
return
footnoteElement = microdom.Element('ol')
id = 1
for footnote in footnotes:
href = microdom.parseString('<a href="#footnote-%(id)d">'
'<super>%(id)d</super></a>'
% vars()).documentElement
text = ' '.join(domhelpers.getNodeText(footnote).split())
href.setAttribute('title', text)
target = microdom.Element('a', attributes={'name': 'footnote-%d' % id})
target.childNodes = [footnote]
footnoteContent = microdom.Element('li')
footnoteContent.childNodes = [target]
footnoteElement.childNodes.append(footnoteContent)
footnote.parentNode.replaceChild(href, footnote)
id += 1
body = domhelpers.findNodesNamed(document, "body")[0]
header = microdom.parseString('<h2>Footnotes</h2>').documentElement
body.childNodes.append(header)
body.childNodes.append(footnoteElement)
def notes(document):
"""
Find notes in the given document and mark them up as such.
A note is any node with a C{class} attribute set to C{note}.
(I think this is a very stupid feature. When I found it I actually
exclaimed out loud. -exarkun)
@type document: A DOM Node or Document
@param document: The input document which contains all of the content to be
presented.
@return: C{None}
"""
notes = domhelpers.findElementsWithAttribute(document, "class", "note")
notePrefix = microdom.parseString('<strong>Note: </strong>').documentElement
for note in notes:
note.childNodes.insert(0, notePrefix)
def compareMarkPos(a, b):
"""
Perform in every way identically to L{cmp} for valid inputs.
XXX - replace this with L{cmp}
"""
linecmp = cmp(a[0], b[0])
if linecmp:
return linecmp
return cmp(a[1], b[1])
def comparePosition(firstElement, secondElement):
"""
Compare the two elements given by their position in the document or
documents they were parsed from.
@type firstElement: C{twisted.web.microdom.Element}
@type secondElement: C{twisted.web.microdom.Element}
@return: C{-1}, C{0}, or C{1}, with the same meanings as the return value
of L{cmp}.
"""
return compareMarkPos(firstElement._markpos, secondElement._markpos)
def findNodeJustBefore(target, nodes):
"""
Find the node in C{nodes} which appeared immediately before C{target} in
the input document.
@type target: L{twisted.web.microdom.Element}
@type nodes: C{list} of L{twisted.web.microdom.Element}
@return: An element from C{nodes}
"""
result = None
for node in nodes:
if comparePosition(target, node) < 0:
return result
result = node
return result
def getFirstAncestorWithSectionHeader(entry):
"""
Visit the ancestors of C{entry} until one with at least one C{h2} child
node is found, then return all of that node's C{h2} child nodes.
@type entry: A DOM Node
@param entry: The node from which to begin traversal. This node itself is
excluded from consideration.
@rtype: C{list} of DOM Nodes
@return: All C{h2} nodes of the ultimately selected parent node.
"""
for a in domhelpers.getParents(entry)[1:]:
headers = domhelpers.findNodesNamed(a, "h2")
if len(headers) > 0:
return headers
return []
def getSectionNumber(header):
"""
Retrieve the section number of the given node.
@type header: A DOM Node or L{None}
@param header: The section from which to extract a number. The section
number is the value of this node's first child.
@return: C{None} or a C{str} giving the section number.
"""
if not header:
return None
return header.childNodes[0].value.strip()
def getSectionReference(entry):
"""
Find the section number which contains the given node.
This function looks at the given node's ancestry until it finds a node
which defines a section, then returns that section's number.
@type entry: A DOM Node
@param entry: The node for which to determine the section.
@rtype: C{str}
@return: The section number, as returned by C{getSectionNumber} of the
first ancestor of C{entry} which defines a section, as determined by
L{getFirstAncestorWithSectionHeader}.
"""
headers = getFirstAncestorWithSectionHeader(entry)
myHeader = findNodeJustBefore(entry, headers)
return getSectionNumber(myHeader)
def index(document, filename, chapterReference):
"""
Extract index entries from the given document and store them for later use
and insert named anchors so that the index can link back to those entries.
Any node with a C{class} attribute set to C{index} is considered an index
entry.
@type document: A DOM Node or Document
@param document: The input document which contains all of the content to be
presented.
@type filename: C{str}
@param filename: A link to the output for the given document which will be
included in the index to link to any index entry found here.
@type chapterReference: ???
@param chapterReference: ???
@return: C{None}
"""
entries = domhelpers.findElementsWithAttribute(document, "class", "index")
if not entries:
return
i = 0;
for entry in entries:
i += 1
anchor = 'index%02d' % i
if chapterReference:
ref = getSectionReference(entry) or chapterReference
else:
ref = 'link'
indexer.addEntry(filename, anchor, entry.attributes['value'], ref)
# does nodeName even affect anything?
entry.nodeName = entry.tagName = entry.endTagName = 'a'
entry.attributes = InsensitiveDict({'name': anchor})
def setIndexLink(template, indexFilename):
"""
Insert a link to an index document.
Any node with a C{class} attribute set to C{index-link} will have its tag
name changed to C{a} and its C{href} attribute set to C{indexFilename}.
@type template: A DOM Node or Document
@param template: The output template which defines the presentation of the
version information.
@type indexFilename: C{str}
@param indexFilename: The address of the index document to which to link.
If any C{False} value, this function will do nothing.
@return: C{None}
"""
if not indexFilename:
return
indexLinks = domhelpers.findElementsWithAttribute(template, "class", "index-link")
for link in indexLinks:
link.nodeName = link.tagName = link.endTagName = 'a'
link.attributes = InsensitiveDict({'href': indexFilename})
def numberDocument(document, chapterNumber):
"""
Number the sections of the given document.
A dot-separated chapter, section number is added to the beginning of each
section, as defined by C{h2} nodes.
@type document: A DOM Node or Document
@param document: The input document which contains all of the content to be
presented.
@type chapterNumber: C{int}
@param chapterNumber: The chapter number of this content in an overall
document.
@return: C{None}
"""
i = 1
for node in domhelpers.findNodesNamed(document, "h2"):
node.childNodes = [microdom.Text("%s.%d " % (chapterNumber, i))] + node.childNodes
i += 1
def fixRelativeLinks(document, linkrel):
"""
Replace relative links in C{str} and C{href} attributes with links relative
to C{linkrel}.
@type document: A DOM Node or Document
@param document: The output template.
@type linkrel: C{str}
@param linkrel: An prefix to apply to all relative links in C{src} or
C{href} attributes in the input document when generating the output
document.
"""
for attr in 'src', 'href':
for node in domhelpers.findElementsWithAttribute(document, attr):
href = node.getAttribute(attr)
if not href.startswith('http') and not href.startswith('/'):
node.setAttribute(attr, linkrel+node.getAttribute(attr))
def setTitle(template, title, chapterNumber):
"""
Add title and chapter number information to the template document.
The title is added to the end of the first C{title} tag and the end of the
first tag with a C{class} attribute set to C{title}. If specified, the
chapter is inserted before the title.
@type template: A DOM Node or Document
@param template: The output template which defines the presentation of the
version information.
@type title: C{list} of DOM Nodes
@param title: Nodes from the input document defining its title.
@type chapterNumber: C{int}
@param chapterNumber: The chapter number of this content in an overall
document. If not applicable, any C{False} value will result in this
information being omitted.
@return: C{None}
"""
for nodeList in (domhelpers.findNodesNamed(template, "title"),
domhelpers.findElementsWithAttribute(template, "class",
'title')):
if nodeList:
if numberer.getNumberSections() and chapterNumber:
nodeList[0].childNodes.append(microdom.Text('%s. ' % chapterNumber))
nodeList[0].childNodes.extend(title)
def setAuthors(template, authors):
"""
Add author information to the template document.
Names and contact information for authors are added to each node with a
C{class} attribute set to C{authors} and to the template head as C{link}
nodes.
@type template: A DOM Node or Document
@param template: The output template which defines the presentation of the
version information.
@type authors: C{list} of two-tuples of C{str}
@param authors: List of names and contact information for the authors of
the input document.
@return: C{None}
"""
# First, similarly to setTitle, insert text into an <div class="authors">
text = ''
for name, href in authors:
# FIXME: Do proper quoting/escaping (is it ok to use
# xml.sax.saxutils.{escape,quoteattr}?)
anchor = '<a href="%s">%s</a>' % (href, name)
if (name, href) == authors[-1]:
if len(authors) == 1:
text = anchor
else:
text += 'and ' + anchor
else:
text += anchor + ','
childNodes = microdom.parseString('<span>' + text +'</span>').childNodes
for node in domhelpers.findElementsWithAttribute(template,
"class", 'authors'):
node.childNodes.extend(childNodes)
# Second, add appropriate <link rel="author" ...> tags to the <head>.
head = domhelpers.findNodesNamed(template, 'head')[0]
authors = [microdom.parseString('<link rel="author" href="%s" title="%s"/>'
% (href, name)).childNodes[0]
for name, href in authors]
head.childNodes.extend(authors)
def setVersion(template, version):
"""
Add a version indicator to the given template.
@type template: A DOM Node or Document
@param template: The output template which defines the presentation of the
version information.
@type version: C{str}
@param version: The version string to add to the template.
@return: C{None}
"""
for node in domhelpers.findElementsWithAttribute(template, "class",
"version"):
node.appendChild(microdom.Text(version))
def getOutputFileName(originalFileName, outputExtension, index=None):
"""
Return a filename which is the same as C{originalFileName} except for the
extension, which is replaced with C{outputExtension}.
For example, if C{originalFileName} is C{'/foo/bar.baz'} and
C{outputExtension} is C{'quux'}, the return value will be
C{'/foo/bar.quux'}.
@type originalFileName: C{str}
@type outputExtension: C{stR}
@param index: ignored, never passed.
@rtype: C{str}
"""
return os.path.splitext(originalFileName)[0]+outputExtension
def munge(document, template, linkrel, dir, fullpath, ext, url, config, outfileGenerator=getOutputFileName):
"""
Mutate C{template} until it resembles C{document}.
@type document: A DOM Node or Document
@param document: The input document which contains all of the content to be
presented.
@type template: A DOM Node or Document
@param template: The template document which defines the desired
presentation format of the content.
@type linkrel: C{str}
@param linkrel: An prefix to apply to all relative links in C{src} or
C{href} attributes in the input document when generating the output
document.
@type dir: C{str}
@param dir: The directory in which to search for source listing files.
@type fullpath: C{str}
@param fullpath: The file name which contained the input document.
@type ext: C{str}
@param ext: The extension to use when selecting an output file name. This
replaces the extension of the input file name.
@type url: C{str}
@param url: A string which will be interpolated with the fully qualified
Python name of any API reference encountered in the input document, the
result of which will be used as a link to API documentation for that name
in the output document.
@type config: C{dict}
@param config: Further specification of the desired form of the output.
Valid keys in this dictionary::
noapi: If present and set to a True value, links to API documentation
will not be generated.
version: A string which will be included in the output to indicate the
version of this documentation.
@type outfileGenerator: Callable of C{str}, C{str} returning C{str}
@param outfileGenerator: Output filename factory. This is invoked with the
intput filename and C{ext} and the output document is serialized to the
file with the name returned.
@return: C{None}
"""
fixRelativeLinks(template, linkrel)
addMtime(template, fullpath)
removeH1(document)
if not config.get('noapi', False):
fixAPI(document, url)
fontifyPython(document)
fixLinks(document, ext)
addPyListings(document, dir)
addHTMLListings(document, dir)
addPlainListings(document, dir)
putInToC(template, generateToC(document))
footnotes(document)
notes(document)
setIndexLink(template, indexer.getIndexFilename())
setVersion(template, config.get('version', ''))
# Insert the document into the template
chapterNumber = htmlbook.getNumber(fullpath)
title = domhelpers.findNodesNamed(document, 'title')[0].childNodes
setTitle(template, title, chapterNumber)
if numberer.getNumberSections() and chapterNumber:
numberDocument(document, chapterNumber)
index(document, outfileGenerator(os.path.split(fullpath)[1], ext),
htmlbook.getReference(fullpath))
authors = domhelpers.findNodesNamed(document, 'link')
authors = [(node.getAttribute('title',''), node.getAttribute('href', ''))
for node in authors if node.getAttribute('rel', '') == 'author']
setAuthors(template, authors)
body = domhelpers.findNodesNamed(document, "body")[0]
tmplbody = domhelpers.findElementsWithAttribute(template, "class",
"body")[0]
tmplbody.childNodes = body.childNodes
tmplbody.setAttribute("class", "content")
def parseFileAndReport(filename):
"""
Parse and return the contents of the given lore XHTML document.
@type filename: C{str}
@param filename: The name of a file containing a lore XHTML document to
load.
@raise process.ProcessingFailure: When the contents of the specified file
cannot be parsed.
@rtype: A DOM Document
@return: The document contained in C{filename}.
"""
try:
return microdom.parse(open(filename))
except microdom.MismatchedTags, e:
raise process.ProcessingFailure(
"%s:%s: begin mismatched tags <%s>/</%s>" %
(e.begLine, e.begCol, e.got, e.expect),
"%s:%s: end mismatched tags <%s>/</%s>" %
(e.endLine, e.endCol, e.got, e.expect))
except microdom.ParseError, e:
raise process.ProcessingFailure("%s:%s:%s" % (e.line, e.col, e.message))
except IOError, e:
raise process.ProcessingFailure(e.strerror + ", filename was '" + filename + "'")
def makeSureDirectoryExists(filename):
filename = os.path.abspath(filename)
dirname = os.path.dirname(filename)
if (not os.path.exists(dirname)):
os.makedirs(dirname)
def doFile(filename, linkrel, ext, url, templ, options={}, outfileGenerator=getOutputFileName):
"""
Process the input document at C{filename} and write an output document.
@type filename: C{str}
@param filename: The path to the input file which will be processed.
@type linkrel: C{str}
@param linkrel: An prefix to apply to all relative links in C{src} or
C{href} attributes in the input document when generating the output
document.
@type ext: C{str}
@param ext: The extension to use when selecting an output file name. This
replaces the extension of the input file name.
@type url: C{str}
@param url: A string which will be interpolated with the fully qualified
Python name of any API reference encountered in the input document, the
result of which will be used as a link to API documentation for that name
in the output document.
@type templ: A DOM Node or Document
@param templ: The template on which the output document will be based.
This is mutated and then serialized to the output file.
@type options: C{dict}
@param options: Further specification of the desired form of the output.
Valid keys in this dictionary::
noapi: If present and set to a True value, links to API documentation
will not be generated.
version: A string which will be included in the output to indicate the
version of this documentation.
@type outfileGenerator: Callable of C{str}, C{str} returning C{str}
@param outfileGenerator: Output filename factory. This is invoked with the
intput filename and C{ext} and the output document is serialized to the
file with the name returned.
@return: C{None}
"""
doc = parseFileAndReport(filename)
clonedNode = templ.cloneNode(1)
munge(doc, clonedNode, linkrel, os.path.dirname(filename), filename, ext,
url, options, outfileGenerator)
newFilename = outfileGenerator(filename, ext)
makeSureDirectoryExists(newFilename)
clonedNode.writexml(open(newFilename, 'wb')) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/lore/tree.py | tree.py |
#
from __future__ import nested_scopes
import os, tempfile
from twisted.web import domhelpers, microdom
import latex, tree, lint, default
class MathLatexSpitter(latex.LatexSpitter):
start_html = '\\documentclass{amsart}\n'
def visitNode_div_latexmacros(self, node):
self.writer(domhelpers.getNodeText(node))
def visitNode_span_latexformula(self, node):
self.writer('\[')
self.writer(domhelpers.getNodeText(node))
self.writer('\]')
def formulaeToImages(document, dir):
# gather all macros
macros = ''
for node in domhelpers.findElementsWithAttribute(document, 'class',
'latexmacros'):
macros += domhelpers.getNodeText(node)
node.parentNode.removeChild(node)
i = 0
for node in domhelpers.findElementsWithAttribute(document, 'class',
'latexformula'):
latexText='''\\documentclass[12pt]{amsart}%s
\\begin{document}\[%s\]
\\end{document}''' % (macros, domhelpers.getNodeText(node))
file = tempfile.mktemp()
open(file+'.tex', 'w').write(latexText)
os.system('latex %s.tex' % file)
os.system('dvips %s.dvi -o %s.ps' % (os.path.basename(file), file))
baseimgname = 'latexformula%d.png' % i
imgname = os.path.join(dir, baseimgname)
i += 1
os.system('pstoimg -type png -crop a -trans -interlace -out '
'%s %s.ps' % (imgname, file))
newNode = microdom.parseString('<span><br /><img src="%s" /><br /></span>' %
baseimgname)
node.parentNode.replaceChild(newNode, node)
def doFile(fn, docsdir, ext, url, templ, linkrel='', d=None):
d = d or {}
doc = tree.parseFileAndReport(fn)
formulaeToImages(doc, os.path.dirname(fn))
cn = templ.cloneNode(1)
tree.munge(doc, cn, linkrel, docsdir, fn, ext, url, d)
cn.writexml(open(os.path.splitext(fn)[0]+ext, 'wb'))
class ProcessingFunctionFactory(default.ProcessingFunctionFactory):
latexSpitters = {None: MathLatexSpitter}
def getDoFile(self):
return doFile
def getLintChecker(self):
checker = lint.getDefaultChecker()
checker.allowedClasses = checker.allowedClasses.copy()
oldDiv = checker.allowedClasses['div']
oldSpan = checker.allowedClasses['span']
checker.allowedClasses['div'] = lambda x:oldDiv(x) or x=='latexmacros'
checker.allowedClasses['span'] = (lambda x:oldSpan(x) or
x=='latexformula')
return checker
factory = ProcessingFunctionFactory() | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/lore/lmath.py | lmath.py |
#
from cStringIO import StringIO
import os, re
from twisted.python import text
from twisted.web import domhelpers
import latex, tree
spaceRe = re.compile('\s+')
def texiEscape(text):
return spaceRe.sub(text, ' ')
entities = latex.entities.copy()
entities['copy'] = '@copyright{}'
class TexiSpitter(latex.BaseLatexSpitter):
baseLevel = 1
def writeNodeData(self, node):
buf = StringIO()
latex.getLatexText(node, self.writer, texiEscape, entities)
def visitNode_title(self, node):
self.writer('@node ')
self.visitNodeDefault(node)
self.writer('\n')
self.writer('@section ')
self.visitNodeDefault(node)
self.writer('\n')
headers = tree.getHeaders(domhelpers.getParents(node)[-1])
if not headers:
return
self.writer('@menu\n')
for header in headers:
self.writer('* %s::\n' % domhelpers.getNodeText(header))
self.writer('@end menu\n')
def visitNode_pre(self, node):
self.writer('@verbatim\n')
buf = StringIO()
latex.getLatexText(node, buf.write, entities=entities)
self.writer(text.removeLeadingTrailingBlanks(buf.getvalue()))
self.writer('@end verbatim\n')
def visitNode_code(self, node):
fout = StringIO()
latex.getLatexText(node, fout.write, texiEscape, entities)
self.writer('@code{'+fout.getvalue()+'}')
def visitNodeHeader(self, node):
self.writer('\n\n@node ')
self.visitNodeDefault(node)
self.writer('\n')
level = (int(node.tagName[1])-2)+self.baseLevel
self.writer('\n\n@'+level*'sub'+'section ')
self.visitNodeDefault(node)
self.writer('\n')
def visitNode_a_listing(self, node):
fileName = os.path.join(self.currDir, node.getAttribute('href'))
self.writer('@verbatim\n')
self.writer(open(fileName).read())
self.writer('@end verbatim')
# Write a caption for this source listing
def visitNode_a_href(self, node):
self.visitNodeDefault(node)
def visitNode_a_name(self, node):
self.visitNodeDefault(node)
visitNode_h2 = visitNode_h3 = visitNode_h4 = visitNodeHeader
start_dl = '@itemize\n'
end_dl = '@end itemize\n'
start_ul = '@itemize\n'
end_ul = '@end itemize\n'
start_ol = '@enumerate\n'
end_ol = '@end enumerate\n'
start_li = '@item\n'
end_li = '\n'
start_dt = '@item\n'
end_dt = ': '
end_dd = '\n'
start_p = '\n\n'
start_strong = start_em = '@emph{'
end_strong = end_em = '}'
start_q = "``"
end_q = "''"
start_span_footnote = '@footnote{'
end_span_footnote = '}'
start_div_note = '@quotation\n@strong{Note:}'
end_div_note = '@end quotation\n'
start_th = '@strong{'
end_th = '}' | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/lore/texi.py | texi.py |
#
"""Rudimentary slide support for Lore.
TODO:
- Complete mgp output target
- syntax highlighting
- saner font handling
- probably lots more
- Add HTML output targets
- one slides per page (with navigation links)
- all in one page
Example input file::
<html>
<head><title>Title of talk</title></head>
<body>
<h1>Title of talk</h1>
<h2>First Slide</h2>
<ul>
<li>Bullet point</li>
<li>Look ma, I'm <strong>bold</strong>!</li>
<li>... etc ...</li>
</ul>
<h2>Second Slide</h2>
<pre class="python">
# Sample code sample.
print "Hello, World!"
</pre>
</body>
</html>
"""
from __future__ import nested_scopes
from twisted.lore import default
from twisted.web import domhelpers, microdom
from twisted.python import text
# These should be factored out
from twisted.lore.latex import BaseLatexSpitter, LatexSpitter, processFile, \
getLatexText, HeadingLatexSpitter
from twisted.lore.tree import getHeaders
from tree import removeH1, fixAPI, fontifyPython, \
addPyListings, addHTMLListings, setTitle
import os, os.path, re
from cStringIO import StringIO
hacked_entities = { 'amp': ' &', 'gt': ' >', 'lt': ' <', 'quot': ' "',
'copy': ' (c)'}
entities = { 'amp': '&', 'gt': '>', 'lt': '<', 'quot': '"',
'copy': '(c)'}
class MagicpointOutput(BaseLatexSpitter):
bulletDepth = 0
def writeNodeData(self, node):
buf = StringIO()
getLatexText(node, buf.write, entities=hacked_entities)
data = buf.getvalue().rstrip().replace('\n', ' ')
self.writer(re.sub(' +', ' ', data))
def visitNode_title(self, node):
self.title = domhelpers.getNodeText(node)
def visitNode_body(self, node):
# Adapted from tree.generateToC
self.fontStack = [('standard', None)]
# Title slide
self.writer(self.start_h2)
self.writer(self.title)
self.writer(self.end_h2)
self.writer('%center\n\n\n\n\n')
for authorNode in domhelpers.findElementsWithAttribute(node, 'class', 'author'):
getLatexText(authorNode, self.writer, entities=entities)
self.writer('\n')
# Table of contents
self.writer(self.start_h2)
self.writer(self.title)
self.writer(self.end_h2)
for element in getHeaders(node):
level = int(element.tagName[1])-1
self.writer(level * '\t')
self.writer(domhelpers.getNodeText(element))
self.writer('\n')
self.visitNodeDefault(node)
def visitNode_div_author(self, node):
# Skip this node; it's already been used by visitNode_body
pass
def visitNode_div_pause(self, node):
self.writer('%pause\n')
def visitNode_pre(self, node):
# TODO: Syntax highlighting
buf = StringIO()
getLatexText(node, buf.write, entities=entities)
data = buf.getvalue()
data = text.removeLeadingTrailingBlanks(data)
lines = data.split('\n')
self.fontStack.append(('typewriter', 4))
self.writer('%' + self.fontName() + '\n')
for line in lines:
self.writer(' ' + line + '\n')
del self.fontStack[-1]
self.writer('%' + self.fontName() + '\n')
def visitNode_ul(self, node):
if self.bulletDepth > 0:
self.writer(self._start_ul)
self.bulletDepth += 1
self.start_li = self._start_li * self.bulletDepth
self.visitNodeDefault(node)
self.bulletDepth -= 1
self.start_li = self._start_li * self.bulletDepth
def visitNode_strong(self, node):
self.doFont(node, 'bold')
def visitNode_em(self, node):
self.doFont(node, 'italic')
def visitNode_code(self, node):
self.doFont(node, 'typewriter')
def doFont(self, node, style):
self.fontStack.append((style, None))
self.writer(' \n%cont, ' + self.fontName() + '\n')
self.visitNodeDefault(node)
del self.fontStack[-1]
self.writer('\n%cont, ' + self.fontName() + '\n')
def fontName(self):
names = [x[0] for x in self.fontStack]
if 'typewriter' in names:
name = 'typewriter'
else:
name = ''
if 'bold' in names:
name += 'bold'
if 'italic' in names:
name += 'italic'
if name == '':
name = 'standard'
sizes = [x[1] for x in self.fontStack]
sizes.reverse()
for size in sizes:
if size:
return 'font "%s", size %d' % (name, size)
return 'font "%s"' % name
start_h2 = "%page\n\n"
end_h2 = '\n\n\n'
_start_ul = '\n'
_start_li = "\t"
end_li = "\n"
def convertFile(filename, outputter, template, ext=".mgp"):
fout = open(os.path.splitext(filename)[0]+ext, 'w')
fout.write(open(template).read())
spitter = outputter(fout.write, os.path.dirname(filename), filename)
fin = open(filename)
processFile(spitter, fin)
fin.close()
fout.close()
# HTML DOM tree stuff
def splitIntoSlides(document):
body = domhelpers.findNodesNamed(document, 'body')[0]
slides = []
slide = []
title = '(unset)'
for child in body.childNodes:
if isinstance(child, microdom.Element) and child.tagName == 'h2':
if slide:
slides.append((title, slide))
slide = []
title = domhelpers.getNodeText(child)
else:
slide.append(child)
slides.append((title, slide))
return slides
def insertPrevNextLinks(slides, filename, ext):
for slide in slides:
for name, offset in (("previous", -1), ("next", +1)):
if (slide.pos > 0 and name == "previous") or \
(slide.pos < len(slides)-1 and name == "next"):
for node in domhelpers.findElementsWithAttribute(slide.dom, "class", name):
if node.tagName == 'a':
node.setAttribute('href', '%s-%d%s'
% (filename[0], slide.pos+offset, ext))
else:
node.appendChild(microdom.Text(slides[slide.pos+offset].title))
else:
for node in domhelpers.findElementsWithAttribute(slide.dom, "class", name):
pos = 0
for child in node.parentNode.childNodes:
if child is node:
del node.parentNode.childNodes[pos]
break
pos += 1
class HTMLSlide:
def __init__(self, dom, title, pos):
self.dom = dom
self.title = title
self.pos = pos
def munge(document, template, linkrel, d, fullpath, ext, url, config):
# FIXME: This has *way* to much duplicated crap in common with tree.munge
#fixRelativeLinks(template, linkrel)
removeH1(document)
fixAPI(document, url)
fontifyPython(document)
addPyListings(document, d)
addHTMLListings(document, d)
#fixLinks(document, ext)
#putInToC(template, generateToC(document))
template = template.cloneNode(1)
# Insert the slides into the template
slides = []
pos = 0
for title, slide in splitIntoSlides(document):
t = template.cloneNode(1)
setTitle(t, [microdom.Text(title)])
tmplbody = domhelpers.findElementsWithAttribute(t, "class", "body")[0]
tmplbody.childNodes = slide
tmplbody.setAttribute("class", "content")
# FIXME: Next/Prev links
# FIXME: Perhaps there should be a "Template" class? (setTitle/setBody
# could be methods...)
slides.append(HTMLSlide(t, title, pos))
pos += 1
insertPrevNextLinks(slides, os.path.splitext(os.path.basename(fullpath)), ext)
return slides
from tree import makeSureDirectoryExists
def getOutputFileName(originalFileName, outputExtension, index):
return os.path.splitext(originalFileName)[0]+'-'+str(index) + outputExtension
def doFile(filename, linkrel, ext, url, templ, options={}, outfileGenerator=getOutputFileName):
from tree import parseFileAndReport
doc = parseFileAndReport(filename)
slides = munge(doc, templ, linkrel, os.path.dirname(filename), filename, ext, url, options)
for slide, index in zip(slides, range(len(slides))):
newFilename = outfileGenerator(filename, ext, index)
makeSureDirectoryExists(newFilename)
slide.dom.writexml(open(newFilename, 'wb'))
# Prosper output
class ProsperSlides(LatexSpitter):
firstSlide = 1
start_html = '\\documentclass[ps]{prosper}\n'
start_body = '\\begin{document}\n'
start_div_author = '\\author{'
end_div_author = '}'
def visitNode_h2(self, node):
if self.firstSlide:
self.firstSlide = 0
self.end_body = '\\end{slide}\n\n' + self.end_body
else:
self.writer('\\end{slide}\n\n')
self.writer('\\begin{slide}{')
spitter = HeadingLatexSpitter(self.writer, self.currDir, self.filename)
spitter.visitNodeDefault(node)
self.writer('}')
def _write_img(self, target):
self.writer('\\begin{center}\\includegraphics[%%\nwidth=1.0\n\\textwidth,'
'height=1.0\\textheight,\nkeepaspectratio]{%s}\\end{center}\n' % target)
class PagebreakLatex(LatexSpitter):
everyN = 1
currentN = 0
seenH2 = 0
start_html = LatexSpitter.start_html+"\\date{}\n"
start_body = '\\begin{document}\n\n'
def visitNode_h2(self, node):
if not self.seenH2:
self.currentN = 0
self.seenH2 = 1
else:
self.currentN += 1
self.currentN %= self.everyN
if not self.currentN:
self.writer('\\clearpage\n')
level = (int(node.tagName[1])-2)+self.baseLevel
self.writer('\n\n\\'+level*'sub'+'section*{')
spitter = HeadingLatexSpitter(self.writer, self.currDir, self.filename)
spitter.visitNodeDefault(node)
self.writer('}\n')
class TwoPagebreakLatex(PagebreakLatex):
everyN = 2
class SlidesProcessingFunctionFactory(default.ProcessingFunctionFactory):
latexSpitters = default.ProcessingFunctionFactory.latexSpitters.copy()
latexSpitters['prosper'] = ProsperSlides
latexSpitters['page'] = PagebreakLatex
latexSpitters['twopage'] = TwoPagebreakLatex
def getDoFile(self):
return doFile
def generate_mgp(self, d, fileNameGenerator=None):
template = d.get('template', 'template.mgp')
df = lambda file, linkrel: convertFile(file, MagicpointOutput, template, ext=".mgp")
return df
factory=SlidesProcessingFunctionFactory() | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/lore/slides.py | slides.py |
#
import sys, os
import tree #todo: get rid of this later
import indexer
class NoProcessorError(Exception):
pass
class ProcessingFailure(Exception):
pass
cols = 79
def dircount(d):
return len([1 for el in d.split("/") if el != '.'])
class Walker:
def __init__(self, df, fext, linkrel):
self.df = df
self.linkrel = linkrel
self.fext = fext
self.walked = []
self.failures = []
def walkdir(self, topdir, prefix=''):
self.basecount = dircount(topdir)
os.path.walk(topdir, self.walk, prefix)
def walk(self, prefix, d, names):
linkrel = prefix + '../' * (dircount(d) - self.basecount)
for name in names:
fullpath = os.path.join(d, name)
fext = os.path.splitext(name)[1]
if fext == self.fext:
self.walked.append((linkrel, fullpath))
def generate(self):
i = 0
indexer.clearEntries()
tree.filenum = 0
for linkrel, fullpath in self.walked:
linkrel = self.linkrel + linkrel
i += 1
fname = os.path.splitext(fullpath)[0]
self.percentdone((float(i) / len(self.walked)), fname)
try:
self.df(fullpath, linkrel)
except ProcessingFailure, e:
self.failures.append((fullpath, e))
indexer.generateIndex()
self.percentdone(1., None)
def percentdone(self, percent, fname):
# override for neater progress bars
proglen = 40
hashes = int(percent * proglen)
spaces = proglen - hashes
progstat = "[%s%s] (%s)" %('#' * hashes, ' ' * spaces,fname or "*Done*")
progstat += (cols - len(progstat)) * ' '
progstat += '\r'
sys.stdout.write(progstat)
sys.stdout.flush()
if fname is None:
print
class PlainReportingWalker(Walker):
def percentdone(self, percent, fname):
if fname:
print fname
class NullReportingWalker(Walker):
def percentdone(self, percent, fname):
pass
def parallelGenerator(originalFileName, outputExtension):
return os.path.splitext(originalFileName)[0]+outputExtension
def fooAddingGenerator(originalFileName, outputExtension):
return os.path.splitext(originalFileName)[0]+"foo"+outputExtension
def outputdirGenerator(originalFileName, outputExtension, inputdir, outputdir):
originalFileName = os.path.abspath(originalFileName)
abs_inputdir = os.path.abspath(inputdir)
if os.path.commonprefix((originalFileName, abs_inputdir)) != abs_inputdir:
raise ValueError("Original file name '" + originalFileName +
"' not under input directory '" + abs_inputdir + "'")
adjustedPath = os.path.join(outputdir, os.path.basename(originalFileName))
return tree.getOutputFileName(adjustedPath, outputExtension)
def getFilenameGenerator(config, outputExt):
if config.get('outputdir'):
return (lambda originalFileName, outputExtension:
outputdirGenerator(originalFileName, outputExtension,
os.path.abspath(config.get('inputdir')),
os.path.abspath(config.get('outputdir'))))
else:
return tree.getOutputFileName
def getProcessor(module, output, config):
try:
m = getattr(module.factory, 'generate_'+output)
except AttributeError:
raise NoProcessorError("cannot generate "+output+" output")
if config.get('ext'):
ext = config['ext']
else:
from default import htmlDefault
ext = htmlDefault['ext']
return m(config, getFilenameGenerator(config, ext)) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/lore/process.py | process.py |
#
"""
Nevow support for lore. DEPRECATED.
Don't use this module, it will be removed in the release of Twisted
after 2.3. If you want static templating with Nevow, instantiate a
rend.Page() and call renderString (or renderSynchronously) yourself.
Do something like::
lore -inevow --config pageclass=some.module.SomePageSubclass [other-opts]
API Stability: unstable
Maintainer: U{Christopher Armstrong<mailto:[email protected]>}
"""
import warnings
warnings.warn("twisted.lore.nevowlore is deprecated. Please instantiate "
"rend.Page and call renderString or renderSynchronously "
"yourself.", DeprecationWarning, stacklevel=2)
import os
from twisted.web import microdom
from twisted.python import reflect
from twisted.web import sux
from twisted.lore import default, tree, process
from nevow import loaders
def parseStringAndReport(s):
try:
return microdom.parseString(s)
except microdom.MismatchedTags, e:
raise process.ProcessingFailure(
"%s:%s: begin mismatched tags <%s>/</%s>" %
(e.begLine, e.begCol, e.got, e.expect),
"%s:%s: end mismatched tags <%s>/</%s>" %
(e.endLine, e.endCol, e.got, e.expect))
except microdom.ParseError, e:
raise process.ProcessingFailure("%s:%s:%s" % (e.line, e.col, e.message))
except IOError, e:
raise process.ProcessingFailure(e.strerror)
def ____wait(d):
"."
from twisted.internet import reactor
from twisted.python import failure
l = []
d.addBoth(l.append)
while not l:
reactor.iterate()
if isinstance(l[0], failure.Failure):
l[0].raiseException()
return l[0]
def nevowify(filename, linkrel, ext, url, templ, options=None, outfileGenerator=tree.getOutputFileName):
if options is None:
options = {}
pclass = options['pageclass']
pclass = reflect.namedObject(pclass)
page = pclass(docFactory=loaders.htmlfile(filename))
s = page.renderString()
s = ____wait(s)
newFilename = outfileGenerator(filename, ext)
if options.has_key('nolore'):
open(newFilename, 'w').write(s)
return
doc = parseStringAndReport(s)
clonedNode = templ.cloneNode(1)
tree.munge(doc, clonedNode, linkrel, os.path.dirname(filename), filename, ext,
url, options, outfileGenerator)
tree.makeSureDirectoryExists(newFilename)
clonedNode.writexml(open(newFilename, 'wb'))
class NevowProcessorFactory:
def getDoFile(self):
return nevowify
def generate_html(self, options, filenameGenerator=tree.getOutputFileName):
n = default.htmlDefault.copy()
n.update(options)
options = n
try:
fp = open(options['template'])
templ = microdom.parse(fp)
except IOError, e:
raise process.NoProcessorError(e.filename+": "+e.strerror)
except sux.ParseError, e:
raise process.NoProcessorError(str(e))
df = lambda file, linkrel: self.getDoFile()(file, linkrel, options['ext'],
options['baseurl'], templ, options, filenameGenerator)
return df
factory = NevowProcessorFactory() | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/lore/nevowlore.py | nevowlore.py |
import sys
from zope.interface import Interface, Attribute
from twisted.lore import process, indexer, numberer, htmlbook
from twisted.python import usage, plugin as oldplugin, reflect
from twisted import plugin as newplugin
class IProcessor(Interface):
"""
"""
factory = Attribute(
"")
class Options(usage.Options):
optFlags = [["plain", 'p', "Report filenames without progress bar"],
["null", 'n', "Do not report filenames"],
["number", 'N', "Add chapter/section numbers to section headings"],
]
optParameters = [
["input", "i", 'lore'],
["inputext", "e", ".xhtml", "The extension that your Lore input files have"],
["docsdir", "d", None],
["linkrel", "l", ''],
["output", "o", 'html'],
["index", "x", None, "The base filename you want to give your index file"],
["book", "b", None, "The book file to generate a book from"],
["prefixurl", None, "", "The prefix to stick on to relative links; only useful when processing directories"],
]
#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 = {"logfile":"log file name", "random":"random seed"}
zsh_extras = ["*:files:_files"]
def __init__(self, *args, **kw):
usage.Options.__init__(self, *args, **kw)
self.config = {}
def opt_config(self, s):
if '=' in s:
k, v = s.split('=', 1)
self.config[k] = v
else:
self.config[s] = 1
def parseArgs(self, *files):
self['files'] = files
def getProcessor(input, output, config):
plugins = oldplugin._getPlugIns("lore")
for plug in plugins:
if plug.tapname == input:
module = plug.load()
break
else:
plugins = newplugin.getPlugins(IProcessor)
for plug in plugins:
if plug.name == input:
module = reflect.namedModule(plug.moduleName)
break
else:
# try treating it as a module name
try:
module = reflect.namedModule(input)
except ImportError:
print '%s: no such input: %s' % (sys.argv[0], input)
return
try:
return process.getProcessor(module, output, config)
except process.NoProcessorError, e:
print "%s: %s" % (sys.argv[0], e)
def getWalker(df, opt):
klass = process.Walker
if opt['plain']:
klass = process.PlainReportingWalker
if opt['null']:
klass = process.NullReportingWalker
return klass(df, opt['inputext'], opt['linkrel'])
def runGivenOptions(opt):
"""Do everything but parse the options; useful for testing.
Returns a descriptive string if there's an error."""
book = None
if opt['book']:
book = htmlbook.Book(opt['book'])
df = getProcessor(opt['input'], opt['output'], opt.config)
if not df:
return 'getProcessor() failed'
walker = getWalker(df, opt)
if opt['files']:
for filename in opt['files']:
walker.walked.append(('', filename))
elif book:
for filename in book.getFiles():
walker.walked.append(('', filename))
else:
walker.walkdir(opt['docsdir'] or '.', opt['prefixurl'])
if opt['index']:
indexFilename = opt['index']
elif book:
indexFilename = book.getIndexFilename()
else:
indexFilename = None
if indexFilename:
indexer.setIndexFilename("%s.%s" % (indexFilename, opt['output']))
else:
indexer.setIndexFilename(None)
## TODO: get numberSections from book, if any
numberer.setNumberSections(opt['number'])
walker.generate()
if walker.failures:
for (file, errors) in walker.failures:
for error in errors:
print "%s:%s" % (file, error)
return 'Walker failures'
def run():
opt = Options()
try:
opt.parseOptions()
except usage.UsageError, errortext:
print '%s: %s' % (sys.argv[0], errortext)
print '%s: Try --help for usage details.' % sys.argv[0]
sys.exit(1)
result = runGivenOptions(opt)
if result:
print result
sys.exit(1)
if __name__ == '__main__':
run() | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/lore/scripts/lore.py | lore.py |
from twisted.spread import pb
from twisted.spread import banana
import os
import types
class Maildir(pb.Referenceable):
def __init__(self, directory, rootDirectory):
self.virtualDirectory = directory
self.rootDirectory = rootDirectory
self.directory = os.path.join(rootDirectory, directory)
def getFolderMessage(self, folder, name):
if '/' in name:
raise IOError("can only open files in '%s' directory'" % folder)
fp = open(os.path.join(self.directory, 'new', name))
try:
return fp.read()
finally:
fp.close()
def deleteFolderMessage(self, folder, name):
if '/' in name:
raise IOError("can only delete files in '%s' directory'" % folder)
os.rename(os.path.join(self.directory, folder, name),
os.path.join(self.rootDirectory, '.Trash', folder, name))
def deleteNewMessage(self, name):
return self.deleteFolderMessage('new', name)
remote_deleteNewMessage = deleteNewMessage
def deleteCurMessage(self, name):
return self.deleteFolderMessage('cur', name)
remote_deleteCurMessage = deleteCurMessage
def getNewMessages(self):
return os.listdir(os.path.join(self.directory, 'new'))
remote_getNewMessages = getNewMessages
def getCurMessages(self):
return os.listdir(os.path.join(self.directory, 'cur'))
remote_getCurMessages = getCurMessages
def getNewMessage(self, name):
return self.getFolderMessage('new', name)
remote_getNewMessage = getNewMessage
def getCurMessage(self, name):
return self.getFolderMessage('cur', name)
remote_getCurMessage = getCurMessage
def getSubFolder(self, name):
if name[0] == '.':
raise IOError("subfolder name cannot begin with a '.'")
name = name.replace('/', ':')
if self.virtualDirectoy == '.':
name = '.'+name
else:
name = self.virtualDirectory+':'+name
if not self._isSubFolder(name):
raise IOError("not a subfolder")
return Maildir(name, self.rootDirectory)
remote_getSubFolder = getSubFolder
def _isSubFolder(self, name):
return (not os.path.isdir(os.path.join(self.rootDirectory, name)) or
not os.path.isfile(os.path.join(self.rootDirectory, name,
'maildirfolder')))
class MaildirCollection(pb.Referenceable):
def __init__(self, root):
self.root = root
def getSubFolders(self):
return os.listdir(self.getRoot())
remote_getSubFolders = getSubFolders
def getSubFolder(self, name):
if '/' in name or name[0] == '.':
raise IOError("invalid name")
return Maildir('.', os.path.join(self.getRoot(), name))
remote_getSubFolder = getSubFolder
class MaildirBroker(pb.Broker):
def proto_getCollection(self, requestID, name, domain, password):
collection = self._getCollection()
if collection is None:
self.sendError(requestID, "permission denied")
else:
self.sendAnswer(requestID, collection)
def getCollection(self, name, domain, password):
if not self.domains.has_key(domain):
return
domain = self.domains[domain]
if (domain.dbm.has_key(name) and
domain.dbm[name] == password):
return MaildirCollection(domain.userDirectory(name))
class MaildirClient(pb.Broker):
def getCollection(self, name, domain, password, callback, errback):
requestID = self.newRequestID()
self.waitingForAnswers[requestID] = callback, errback
self.sendCall("getCollection", requestID, name, domain, password) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/mail/pb.py | pb.py |
from __future__ import nested_scopes
from __future__ import generators
from twisted.protocols import basic
from twisted.protocols import policies
from twisted.internet import defer
from twisted.internet import error
from twisted.internet.defer import maybeDeferred
from twisted.python import log, util, failure, text
from twisted.internet import interfaces
from twisted import cred
import twisted.cred.error
import twisted.cred.credentials
import rfc822
import base64
import binascii
import time
import hmac
import re
import tempfile
import string
import time
import random
import types
import sys
from zope.interface import implements, Interface
import email.Utils
try:
import cStringIO as StringIO
except:
import StringIO
class MessageSet(object):
"""
Essentially an infinite bitfield, with some extra features.
@type getnext: Function taking C{int} returning C{int}
@ivar getnext: A function that returns the next message number,
used when iterating through the MessageSet. By default, a function
returning the next integer is supplied, but as this can be rather
inefficient for sparse UID iterations, it is recommended to supply
one when messages are requested by UID. The argument is provided
as a hint to the implementation and may be ignored if it makes sense
to do so (eg, if an iterator is being used that maintains its own
state, it is guaranteed that it will not be called out-of-order).
"""
_empty = []
def __init__(self, start=_empty, end=_empty):
"""
Create a new MessageSet()
@type start: Optional C{int}
@param start: Start of range, or only message number
@type end: Optional C{int}
@param end: End of range.
"""
self._last = self._empty # Last message/UID in use
self.ranges = [] # List of ranges included
self.getnext = lambda x: x+1 # A function which will return the next
# message id. Handy for UID requests.
if start is self._empty:
return
if isinstance(start, types.ListType):
self.ranges = start[:]
self.clean()
else:
self.add(start,end)
# Ooo. A property.
def last():
def _setLast(self,value):
if self._last is not self._empty:
raise ValueError("last already set")
self._last = value
for i,(l,h) in enumerate(self.ranges):
if l is not None:
break # There are no more Nones after this
l = value
if h is None:
h = value
if l > h:
l, h = h, l
self.ranges[i] = (l,h)
self.clean()
def _getLast(self):
return self._last
doc = '''
"Highest" message number, refered to by "*".
Must be set before attempting to use the MessageSet.
'''
return _getLast, _setLast, None, doc
last = property(*last())
def add(self, start, end=_empty):
"""
Add another range
@type start: C{int}
@param start: Start of range, or only message number
@type end: Optional C{int}
@param end: End of range.
"""
if end is self._empty:
end = start
if self._last is not self._empty:
if start is None:
start = self.last
if end is None:
end = self.last
if start > end:
# Try to keep in low, high order if possible
# (But we don't know what None means, this will keep
# None at the start of the ranges list)
start, end = end, start
self.ranges.append((start,end))
self.clean()
def __add__(self, other):
if isinstance(other, MessageSet):
ranges = self.ranges + other.ranges
return MessageSet(ranges)
else:
res = MessageSet(self.ranges)
try:
res.add(*other)
except TypeError:
res.add(other)
return res
def extend(self, other):
if isinstance(other, MessageSet):
self.ranges.extend(other.ranges)
self.clean()
else:
try:
self.add(*other)
except TypeError:
self.add(other)
return self
def clean(self):
"""
Clean ranges list, combining adjacent ranges
"""
self.ranges.sort()
oldl, oldh = None, None
for i,(l,h) in enumerate(self.ranges):
if l is None:
continue
# l is >= oldl and h is >= oldh due to sort()
if oldl is not None and l <= oldh+1:
l = oldl
h = max(oldh,h)
self.ranges[i-1] = None
self.ranges[i] = (l,h)
oldl,oldh = l,h
self.ranges = filter(None, self.ranges)
def __contains__(self, value):
"""
May raise TypeError if we encounter unknown "high" values
"""
for l,h in self.ranges:
if l is None:
raise TypeError(
"Can't determine membership; last value not set")
if l <= value <= h:
return True
return False
def _iterator(self):
for l,h in self.ranges:
l = self.getnext(l-1)
while l <= h:
yield l
l = self.getnext(l)
if l is None:
break
def __iter__(self):
if self.ranges and self.ranges[0][0] is None:
raise TypeError("Can't iterate; last value not set")
return self._iterator()
def __len__(self):
res = 0
for l, h in self.ranges:
if l is None:
raise TypeError("Can't size object; last value not set")
res += (h - l) + 1
return res
def __str__(self):
p = []
for low, high in self.ranges:
if low == high:
if low is None:
p.append('*')
else:
p.append(str(low))
elif low is None:
p.append('%d:*' % (high,))
else:
p.append('%d:%d' % (low, high))
return ','.join(p)
def __repr__(self):
return '<MessageSet %s>' % (str(self),)
def __eq__(self, other):
if isinstance(other, MessageSet):
return self.ranges == other.ranges
return False
class LiteralString:
def __init__(self, size, defered):
self.size = size
self.data = []
self.defer = defered
def write(self, data):
self.size -= len(data)
passon = None
if self.size > 0:
self.data.append(data)
else:
if self.size:
data, passon = data[:self.size], data[self.size:]
else:
passon = ''
if data:
self.data.append(data)
return passon
def callback(self, line):
"""
Call defered with data and rest of line
"""
self.defer.callback((''.join(self.data), line))
class LiteralFile:
_memoryFileLimit = 1024 * 1024 * 10
def __init__(self, size, defered):
self.size = size
self.defer = defered
if size > self._memoryFileLimit:
self.data = tempfile.TemporaryFile()
else:
self.data = StringIO.StringIO()
def write(self, data):
self.size -= len(data)
passon = None
if self.size > 0:
self.data.write(data)
else:
if self.size:
data, passon = data[:self.size], data[self.size:]
else:
passon = ''
if data:
self.data.write(data)
return passon
def callback(self, line):
"""
Call defered with data and rest of line
"""
self.data.seek(0,0)
self.defer.callback((self.data, line))
class WriteBuffer:
"""Buffer up a bunch of writes before sending them all to a transport at once.
"""
def __init__(self, transport, size=8192):
self.bufferSize = size
self.transport = transport
self._length = 0
self._writes = []
def write(self, s):
self._length += len(s)
self._writes.append(s)
if self._length > self.bufferSize:
self.flush()
def flush(self):
if self._writes:
self.transport.writeSequence(self._writes)
self._writes = []
self._length = 0
class Command:
_1_RESPONSES = ('CAPABILITY', 'FLAGS', 'LIST', 'LSUB', 'STATUS', 'SEARCH', 'NAMESPACE')
_2_RESPONSES = ('EXISTS', 'EXPUNGE', 'FETCH', 'RECENT')
_OK_RESPONSES = ('UIDVALIDITY', 'READ-WRITE', 'READ-ONLY', 'UIDNEXT', 'PERMANENTFLAGS')
defer = None
def __init__(self, command, args=None, wantResponse=(),
continuation=None, *contArgs, **contKw):
self.command = command
self.args = args
self.wantResponse = wantResponse
self.continuation = lambda x: continuation(x, *contArgs, **contKw)
self.lines = []
def format(self, tag):
if self.args is None:
return ' '.join((tag, self.command))
return ' '.join((tag, self.command, self.args))
def finish(self, lastLine, unusedCallback):
send = []
unuse = []
for L in self.lines:
names = parseNestedParens(L)
N = len(names)
if (N >= 1 and names[0] in self._1_RESPONSES or
N >= 2 and names[0] == 'OK' and isinstance(names[1], types.ListType) and names[1][0] in self._OK_RESPONSES):
send.append(L)
elif N >= 3 and names[1] in self._2_RESPONSES:
if isinstance(names[2], list) and len(names[2]) >= 1 and names[2][0] == 'FLAGS' and 'FLAGS' not in self.args:
unuse.append(L)
else:
send.append(L)
elif N >= 2 and names[1] in self._2_RESPONSES:
send.append(L)
else:
unuse.append(L)
d, self.defer = self.defer, None
d.callback((send, lastLine))
if unuse:
unusedCallback(unuse)
class LOGINCredentials(cred.credentials.UsernamePassword):
def __init__(self):
self.challenges = ['Password\0', 'User Name\0']
self.responses = ['password', 'username']
cred.credentials.UsernamePassword.__init__(self, None, None)
def getChallenge(self):
return self.challenges.pop()
def setResponse(self, response):
setattr(self, self.responses.pop(), response)
def moreChallenges(self):
return bool(self.challenges)
class PLAINCredentials(cred.credentials.UsernamePassword):
def __init__(self):
cred.credentials.UsernamePassword.__init__(self, None, None)
def getChallenge(self):
return ''
def setResponse(self, response):
parts = response[:-1].split('\0', 1)
if len(parts) != 2:
raise IllegalClientResponse("Malformed Response - wrong number of parts")
self.username, self.password = parts
def moreChallenges(self):
return False
class IMAP4Exception(Exception):
def __init__(self, *args):
Exception.__init__(self, *args)
class IllegalClientResponse(IMAP4Exception): pass
class IllegalOperation(IMAP4Exception): pass
class IllegalMailboxEncoding(IMAP4Exception): pass
class IMailboxListener(Interface):
"""Interface for objects interested in mailbox events"""
def modeChanged(writeable):
"""Indicates that the write status of a mailbox has changed.
@type writeable: C{bool}
@param writeable: A true value if write is now allowed, false
otherwise.
"""
def flagsChanged(newFlags):
"""Indicates that the flags of one or more messages have changed.
@type newFlags: C{dict}
@param newFlags: A mapping of message identifiers to tuples of flags
now set on that message.
"""
def newMessages(exists, recent):
"""Indicates that the number of messages in a mailbox has changed.
@type exists: C{int} or C{None}
@param exists: The total number of messages now in this mailbox.
If the total number of messages has not changed, this should be
C{None}.
@type recent: C{int}
@param recent: The number of messages now flagged \\Recent.
If the number of recent messages has not changed, this should be
C{None}.
"""
class IMAP4Server(basic.LineReceiver, policies.TimeoutMixin):
"""
Protocol implementation for an IMAP4rev1 server.
The server can be in any of four states:
- Non-authenticated
- Authenticated
- Selected
- Logout
"""
implements(IMailboxListener)
# Identifier for this server software
IDENT = 'Twisted IMAP4rev1 Ready'
# Number of seconds before idle timeout
# Initially 1 minute. Raised to 30 minutes after login.
timeOut = 60
POSTAUTH_TIMEOUT = 60 * 30
# Whether STARTTLS has been issued successfully yet or not.
startedTLS = False
# Whether our transport supports TLS
canStartTLS = False
# Mapping of tags to commands we have received
tags = None
# The object which will handle logins for us
portal = None
# The account object for this connection
account = None
# Logout callback
_onLogout = None
# The currently selected mailbox
mbox = None
# Command data to be processed when literal data is received
_pendingLiteral = None
# Maximum length to accept for a "short" string literal
_literalStringLimit = 4096
# IChallengeResponse factories for AUTHENTICATE command
challengers = None
state = 'unauth'
parseState = 'command'
def __init__(self, chal = None, contextFactory = None, scheduler = None):
if chal is None:
chal = {}
self.challengers = chal
self.ctx = contextFactory
if scheduler is None:
scheduler = iterateInReactor
self._scheduler = scheduler
self._queuedAsync = []
def capabilities(self):
cap = {'AUTH': self.challengers.keys()}
if self.ctx and self.canStartTLS:
if not self.startedTLS and interfaces.ISSLTransport(self.transport, None) is None:
cap['LOGINDISABLED'] = None
cap['STARTTLS'] = None
cap['NAMESPACE'] = None
cap['IDLE'] = None
return cap
def connectionMade(self):
self.tags = {}
self.canStartTLS = interfaces.ITLSTransport(self.transport, None) is not None
self.setTimeout(self.timeOut)
self.sendServerGreeting()
def connectionLost(self, reason):
self.setTimeout(None)
if self._onLogout:
self._onLogout()
self._onLogout = None
def timeoutConnection(self):
self.sendLine('* BYE Autologout; connection idle too long')
self.transport.loseConnection()
if self.mbox:
self.mbox.removeListener(self)
cmbx = ICloseableMailbox(self.mbox, None)
if cmbx is not None:
maybeDeferred(cmbx.close).addErrback(log.err)
self.mbox = None
self.state = 'timeout'
def rawDataReceived(self, data):
self.resetTimeout()
passon = self._pendingLiteral.write(data)
if passon is not None:
self.setLineMode(passon)
# Avoid processing commands while buffers are being dumped to
# our transport
blocked = None
def _unblock(self):
commands = self.blocked
self.blocked = None
while commands and self.blocked is None:
self.lineReceived(commands.pop(0))
if self.blocked is not None:
self.blocked.extend(commands)
# def sendLine(self, line):
# print 'C:', repr(line)
# return basic.LineReceiver.sendLine(self, line)
def lineReceived(self, line):
# print 'S:', repr(line)
if self.blocked is not None:
self.blocked.append(line)
return
self.resetTimeout()
f = getattr(self, 'parse_' + self.parseState)
try:
f(line)
except Exception, e:
self.sendUntaggedResponse('BAD Server error: ' + str(e))
log.err()
def parse_command(self, line):
args = line.split(None, 2)
rest = None
if len(args) == 3:
tag, cmd, rest = args
elif len(args) == 2:
tag, cmd = args
elif len(args) == 1:
tag = args[0]
self.sendBadResponse(tag, 'Missing command')
return None
else:
self.sendBadResponse(None, 'Null command')
return None
cmd = cmd.upper()
try:
return self.dispatchCommand(tag, cmd, rest)
except IllegalClientResponse, e:
self.sendBadResponse(tag, 'Illegal syntax: ' + str(e))
except IllegalOperation, e:
self.sendNegativeResponse(tag, 'Illegal operation: ' + str(e))
except IllegalMailboxEncoding, e:
self.sendNegativeResponse(tag, 'Illegal mailbox name: ' + str(e))
def parse_pending(self, line):
d = self._pendingLiteral
self._pendingLiteral = None
self.parseState = 'command'
d.callback(line)
def dispatchCommand(self, tag, cmd, rest, uid=None):
f = self.lookupCommand(cmd)
if f:
fn = f[0]
parseargs = f[1:]
self.__doCommand(tag, fn, [self, tag], parseargs, rest, uid)
else:
self.sendBadResponse(tag, 'Unsupported command')
def lookupCommand(self, cmd):
return getattr(self, '_'.join((self.state, cmd.upper())), None)
def __doCommand(self, tag, handler, args, parseargs, line, uid):
for (i, arg) in enumerate(parseargs):
if callable(arg):
parseargs = parseargs[i+1:]
maybeDeferred(arg, self, line).addCallback(
self.__cbDispatch, tag, handler, args,
parseargs, uid).addErrback(self.__ebDispatch, tag)
return
else:
args.append(arg)
if line:
# Too many arguments
raise IllegalClientResponse("Too many arguments for command: " + repr(line))
if uid is not None:
handler(uid=uid, *args)
else:
handler(*args)
def __cbDispatch(self, (arg, rest), tag, fn, args, parseargs, uid):
args.append(arg)
self.__doCommand(tag, fn, args, parseargs, rest, uid)
def __ebDispatch(self, failure, tag):
if failure.check(IllegalClientResponse):
self.sendBadResponse(tag, 'Illegal syntax: ' + str(failure.value))
elif failure.check(IllegalOperation):
self.sendNegativeResponse(tag, 'Illegal operation: ' +
str(failure.value))
elif failure.check(IllegalMailboxEncoding):
self.sendNegativeResponse(tag, 'Illegal mailbox name: ' +
str(failure.value))
else:
self.sendBadResponse(tag, 'Server error: ' + str(failure.value))
log.err(failure)
def _stringLiteral(self, size):
if size > self._literalStringLimit:
raise IllegalClientResponse(
"Literal too long! I accept at most %d octets" %
(self._literalStringLimit,))
d = defer.Deferred()
self.parseState = 'pending'
self._pendingLiteral = LiteralString(size, d)
self.sendContinuationRequest('Ready for %d octets of text' % size)
self.setRawMode()
return d
def _fileLiteral(self, size):
d = defer.Deferred()
self.parseState = 'pending'
self._pendingLiteral = LiteralFile(size, d)
self.sendContinuationRequest('Ready for %d octets of data' % size)
self.setRawMode()
return d
def arg_astring(self, line):
"""
Parse an astring from the line, return (arg, rest), possibly
via a deferred (to handle literals)
"""
line = line.strip()
if not line:
raise IllegalClientResponse("Missing argument")
d = None
arg, rest = None, None
if line[0] == '"':
try:
spam, arg, rest = line.split('"',2)
rest = rest[1:] # Strip space
except ValueError:
raise IllegalClientResponse("Unmatched quotes")
elif line[0] == '{':
# literal
if line[-1] != '}':
raise IllegalClientResponse("Malformed literal")
try:
size = int(line[1:-1])
except ValueError:
raise IllegalClientResponse("Bad literal size: " + line[1:-1])
d = self._stringLiteral(size)
else:
arg = line.split(' ',1)
if len(arg) == 1:
arg.append('')
arg, rest = arg
return d or (arg, rest)
# ATOM: Any CHAR except ( ) { % * " \ ] CTL SP (CHAR is 7bit)
atomre = re.compile(r'(?P<atom>[^\](){%*"\\\x00-\x20\x80-\xff]+)( (?P<rest>.*$)|$)')
def arg_atom(self, line):
"""
Parse an atom from the line
"""
if not line:
raise IllegalClientResponse("Missing argument")
m = self.atomre.match(line)
if m:
return m.group('atom'), m.group('rest')
else:
raise IllegalClientResponse("Malformed ATOM")
def arg_plist(self, line):
"""
Parse a (non-nested) parenthesised list from the line
"""
if not line:
raise IllegalClientResponse("Missing argument")
if line[0] != "(":
raise IllegalClientResponse("Missing parenthesis")
i = line.find(")")
if i == -1:
raise IllegalClientResponse("Mismatched parenthesis")
return (parseNestedParens(line[1:i],0), line[i+2:])
def arg_literal(self, line):
"""
Parse a literal from the line
"""
if not line:
raise IllegalClientResponse("Missing argument")
if line[0] != '{':
raise IllegalClientResponse("Missing literal")
if line[-1] != '}':
raise IllegalClientResponse("Malformed literal")
try:
size = int(line[1:-1])
except ValueError:
raise IllegalClientResponse("Bad literal size: " + line[1:-1])
return self._fileLiteral(size)
def arg_searchkeys(self, line):
"""
searchkeys
"""
query = parseNestedParens(line)
# XXX Should really use list of search terms and parse into
# a proper tree
return (query, '')
def arg_seqset(self, line):
"""
sequence-set
"""
rest = ''
arg = line.split(' ',1)
if len(arg) == 2:
rest = arg[1]
arg = arg[0]
try:
return (parseIdList(arg), rest)
except IllegalIdentifierError, e:
raise IllegalClientResponse("Bad message number " + str(e))
def arg_fetchatt(self, line):
"""
fetch-att
"""
p = _FetchParser()
p.parseString(line)
return (p.result, '')
def arg_flaglist(self, line):
"""
Flag part of store-att-flag
"""
flags = []
if line[0] == '(':
if line[-1] != ')':
raise IllegalClientResponse("Mismatched parenthesis")
line = line[1:-1]
while line:
m = self.atomre.search(line)
if not m:
raise IllegalClientResponse("Malformed flag")
if line[0] == '\\' and m.start() == 1:
flags.append('\\' + m.group('atom'))
elif m.start() == 0:
flags.append(m.group('atom'))
else:
raise IllegalClientResponse("Malformed flag")
line = m.group('rest')
return (flags, '')
def arg_line(self, line):
"""
Command line of UID command
"""
return (line, '')
def opt_plist(self, line):
"""
Optional parenthesised list
"""
if line.startswith('('):
return self.arg_plist(line)
else:
return (None, line)
def opt_datetime(self, line):
"""
Optional date-time string
"""
if line.startswith('"'):
try:
spam, date, rest = line.split('"',2)
except IndexError:
raise IllegalClientResponse("Malformed date-time")
return (date, rest[1:])
else:
return (None, line)
def opt_charset(self, line):
"""
Optional charset of SEARCH command
"""
if line[:7].upper() == 'CHARSET':
arg = line.split(' ',2)
if len(arg) == 1:
raise IllegalClientResponse("Missing charset identifier")
if len(arg) == 2:
arg.append('')
spam, arg, rest = arg
return (arg, rest)
else:
return (None, line)
def sendServerGreeting(self):
msg = '[CAPABILITY %s] %s' % (' '.join(self.listCapabilities()), self.IDENT)
self.sendPositiveResponse(message=msg)
def sendBadResponse(self, tag = None, message = ''):
self._respond('BAD', tag, message)
def sendPositiveResponse(self, tag = None, message = ''):
self._respond('OK', tag, message)
def sendNegativeResponse(self, tag = None, message = ''):
self._respond('NO', tag, message)
def sendUntaggedResponse(self, message, async=False):
if not async or (self.blocked is None):
self._respond(message, None, None)
else:
self._queuedAsync.append(message)
def sendContinuationRequest(self, msg = 'Ready for additional command text'):
if msg:
self.sendLine('+ ' + msg)
else:
self.sendLine('+')
def _respond(self, state, tag, message):
if state in ('OK', 'NO', 'BAD') and self._queuedAsync:
lines = self._queuedAsync
self._queuedAsync = []
for msg in lines:
self._respond(msg, None, None)
if not tag:
tag = '*'
if message:
self.sendLine(' '.join((tag, state, message)))
else:
self.sendLine(' '.join((tag, state)))
def listCapabilities(self):
caps = ['IMAP4rev1']
for c, v in self.capabilities().iteritems():
if v is None:
caps.append(c)
elif len(v):
caps.extend([('%s=%s' % (c, cap)) for cap in v])
return caps
def do_CAPABILITY(self, tag):
self.sendUntaggedResponse('CAPABILITY ' + ' '.join(self.listCapabilities()))
self.sendPositiveResponse(tag, 'CAPABILITY completed')
unauth_CAPABILITY = (do_CAPABILITY,)
auth_CAPABILITY = unauth_CAPABILITY
select_CAPABILITY = unauth_CAPABILITY
logout_CAPABILITY = unauth_CAPABILITY
def do_LOGOUT(self, tag):
self.sendUntaggedResponse('BYE Nice talking to you')
self.sendPositiveResponse(tag, 'LOGOUT successful')
self.transport.loseConnection()
unauth_LOGOUT = (do_LOGOUT,)
auth_LOGOUT = unauth_LOGOUT
select_LOGOUT = unauth_LOGOUT
logout_LOGOUT = unauth_LOGOUT
def do_NOOP(self, tag):
self.sendPositiveResponse(tag, 'NOOP No operation performed')
unauth_NOOP = (do_NOOP,)
auth_NOOP = unauth_NOOP
select_NOOP = unauth_NOOP
logout_NOOP = unauth_NOOP
def do_AUTHENTICATE(self, tag, args):
args = args.upper().strip()
if args not in self.challengers:
self.sendNegativeResponse(tag, 'AUTHENTICATE method unsupported')
else:
self.authenticate(self.challengers[args](), tag)
unauth_AUTHENTICATE = (do_AUTHENTICATE, arg_atom)
def authenticate(self, chal, tag):
if self.portal is None:
self.sendNegativeResponse(tag, 'Temporary authentication failure')
return
self._setupChallenge(chal, tag)
def _setupChallenge(self, chal, tag):
try:
challenge = chal.getChallenge()
except Exception, e:
self.sendBadResponse(tag, 'Server error: ' + str(e))
else:
coded = base64.encodestring(challenge)[:-1]
self.parseState = 'pending'
self._pendingLiteral = defer.Deferred()
self.sendContinuationRequest(coded)
self._pendingLiteral.addCallback(self.__cbAuthChunk, chal, tag)
self._pendingLiteral.addErrback(self.__ebAuthChunk, tag)
def __cbAuthChunk(self, result, chal, tag):
try:
uncoded = base64.decodestring(result)
except binascii.Error:
raise IllegalClientResponse("Malformed Response - not base64")
chal.setResponse(uncoded)
if chal.moreChallenges():
self._setupChallenge(chal, tag)
else:
self.portal.login(chal, None, IAccount).addCallbacks(
self.__cbAuthResp,
self.__ebAuthResp,
(tag,), None, (tag,), None
)
def __cbAuthResp(self, (iface, avatar, logout), tag):
assert iface is IAccount, "IAccount is the only supported interface"
self.account = avatar
self.state = 'auth'
self._onLogout = logout
self.sendPositiveResponse(tag, 'Authentication successful')
self.setTimeout(self.POSTAUTH_TIMEOUT)
def __ebAuthResp(self, failure, tag):
if failure.check(cred.error.UnauthorizedLogin):
self.sendNegativeResponse(tag, 'Authentication failed: unauthorized')
elif failure.check(cred.error.UnhandledCredentials):
self.sendNegativeResponse(tag, 'Authentication failed: server misconfigured')
else:
self.sendBadResponse(tag, 'Server error: login failed unexpectedly')
log.err(failure)
def __ebAuthChunk(self, failure, tag):
self.sendNegativeResponse(tag, 'Authentication failed: ' + str(failure.value))
def do_STARTTLS(self, tag):
if self.startedTLS:
self.sendNegativeResponse(tag, 'TLS already negotiated')
elif self.ctx and self.canStartTLS:
self.sendPositiveResponse(tag, 'Begin TLS negotiation now')
self.transport.startTLS(self.ctx)
self.startedTLS = True
self.challengers = self.challengers.copy()
if 'LOGIN' not in self.challengers:
self.challengers['LOGIN'] = LOGINCredentials
if 'PLAIN' not in self.challengers:
self.challengers['PLAIN'] = PLAINCredentials
else:
self.sendNegativeResponse(tag, 'TLS not available')
unauth_STARTTLS = (do_STARTTLS,)
def do_LOGIN(self, tag, user, passwd):
if 'LOGINDISABLED' in self.capabilities():
self.sendBadResponse(tag, 'LOGIN is disabled before STARTTLS')
return
maybeDeferred(self.authenticateLogin, user, passwd
).addCallback(self.__cbLogin, tag
).addErrback(self.__ebLogin, tag
)
unauth_LOGIN = (do_LOGIN, arg_astring, arg_astring)
def authenticateLogin(self, user, passwd):
"""Lookup the account associated with the given parameters
Override this method to define the desired authentication behavior.
The default behavior is to defer authentication to C{self.portal}
if it is not None, or to deny the login otherwise.
@type user: C{str}
@param user: The username to lookup
@type passwd: C{str}
@param passwd: The password to login with
"""
if self.portal:
return self.portal.login(
cred.credentials.UsernamePassword(user, passwd),
None, IAccount
)
raise cred.error.UnauthorizedLogin()
def __cbLogin(self, (iface, avatar, logout), tag):
if iface is not IAccount:
self.sendBadResponse(tag, 'Server error: login returned unexpected value')
log.err("__cbLogin called with %r, IAccount expected" % (iface,))
else:
self.account = avatar
self._onLogout = logout
self.sendPositiveResponse(tag, 'LOGIN succeeded')
self.state = 'auth'
self.setTimeout(self.POSTAUTH_TIMEOUT)
def __ebLogin(self, failure, tag):
if failure.check(cred.error.UnauthorizedLogin):
self.sendNegativeResponse(tag, 'LOGIN failed')
else:
self.sendBadResponse(tag, 'Server error: ' + str(failure.value))
log.err(failure)
def do_NAMESPACE(self, tag):
personal = public = shared = None
np = INamespacePresenter(self.account, None)
if np is not None:
personal = np.getPersonalNamespaces()
public = np.getSharedNamespaces()
shared = np.getSharedNamespaces()
self.sendUntaggedResponse('NAMESPACE ' + collapseNestedLists([personal, public, shared]))
self.sendPositiveResponse(tag, "NAMESPACE command completed")
auth_NAMESPACE = (do_NAMESPACE,)
select_NAMESPACE = auth_NAMESPACE
def _parseMbox(self, name):
if isinstance(name, unicode):
return name
try:
return name.decode('imap4-utf-7')
except:
log.err()
raise IllegalMailboxEncoding(name)
def _selectWork(self, tag, name, rw, cmdName):
if self.mbox:
self.mbox.removeListener(self)
cmbx = ICloseableMailbox(self.mbox, None)
if cmbx is not None:
maybeDeferred(cmbx.close).addErrback(log.err)
self.mbox = None
self.state = 'auth'
name = self._parseMbox(name)
maybeDeferred(self.account.select, self._parseMbox(name), rw
).addCallback(self._cbSelectWork, cmdName, tag
).addErrback(self._ebSelectWork, cmdName, tag
)
def _ebSelectWork(self, failure, cmdName, tag):
self.sendBadResponse(tag, "%s failed: Server error" % (cmdName,))
log.err(failure)
def _cbSelectWork(self, mbox, cmdName, tag):
if mbox is None:
self.sendNegativeResponse(tag, 'No such mailbox')
return
if '\\noselect' in [s.lower() for s in mbox.getFlags()]:
self.sendNegativeResponse(tag, 'Mailbox cannot be selected')
return
flags = mbox.getFlags()
self.sendUntaggedResponse(str(mbox.getMessageCount()) + ' EXISTS')
self.sendUntaggedResponse(str(mbox.getRecentCount()) + ' RECENT')
self.sendUntaggedResponse('FLAGS (%s)' % ' '.join(flags))
self.sendPositiveResponse(None, '[UIDVALIDITY %d]' % mbox.getUIDValidity())
s = mbox.isWriteable() and 'READ-WRITE' or 'READ-ONLY'
mbox.addListener(self)
self.sendPositiveResponse(tag, '[%s] %s successful' % (s, cmdName))
self.state = 'select'
self.mbox = mbox
auth_SELECT = ( _selectWork, arg_astring, 1, 'SELECT' )
select_SELECT = auth_SELECT
auth_EXAMINE = ( _selectWork, arg_astring, 0, 'EXAMINE' )
select_EXAMINE = auth_EXAMINE
def do_IDLE(self, tag):
self.sendContinuationRequest(None)
self.parseTag = tag
self.lastState = self.parseState
self.parseState = 'idle'
def parse_idle(self, *args):
self.parseState = self.lastState
del self.lastState
self.sendPositiveResponse(self.parseTag, "IDLE terminated")
del self.parseTag
select_IDLE = ( do_IDLE, )
auth_IDLE = select_IDLE
def do_CREATE(self, tag, name):
name = self._parseMbox(name)
try:
result = self.account.create(name)
except MailboxException, c:
self.sendNegativeResponse(tag, str(c))
except:
self.sendBadResponse(tag, "Server error encountered while creating mailbox")
log.err()
else:
if result:
self.sendPositiveResponse(tag, 'Mailbox created')
else:
self.sendNegativeResponse(tag, 'Mailbox not created')
auth_CREATE = (do_CREATE, arg_astring)
select_CREATE = auth_CREATE
def do_DELETE(self, tag, name):
name = self._parseMbox(name)
if name.lower() == 'inbox':
self.sendNegativeResponse(tag, 'You cannot delete the inbox')
return
try:
self.account.delete(name)
except MailboxException, m:
self.sendNegativeResponse(tag, str(m))
except:
self.sendBadResponse(tag, "Server error encountered while deleting mailbox")
log.err()
else:
self.sendPositiveResponse(tag, 'Mailbox deleted')
auth_DELETE = (do_DELETE, arg_astring)
select_DELETE = auth_DELETE
def do_RENAME(self, tag, oldname, newname):
oldname, newname = [self._parseMbox(n) for n in oldname, newname]
if oldname.lower() == 'inbox' or newname.lower() == 'inbox':
self.sendNegativeResponse(tag, 'You cannot rename the inbox, or rename another mailbox to inbox.')
return
try:
self.account.rename(oldname, newname)
except TypeError:
self.sendBadResponse(tag, 'Invalid command syntax')
except MailboxException, m:
self.sendNegativeResponse(tag, str(m))
except:
self.sendBadResponse(tag, "Server error encountered while renaming mailbox")
log.err()
else:
self.sendPositiveResponse(tag, 'Mailbox renamed')
auth_RENAME = (do_RENAME, arg_astring, arg_astring)
select_RENAME = auth_RENAME
def do_SUBSCRIBE(self, tag, name):
name = self._parseMbox(name)
try:
self.account.subscribe(name)
except MailboxException, m:
self.sendNegativeResponse(tag, str(m))
except:
self.sendBadResponse(tag, "Server error encountered while subscribing to mailbox")
log.err()
else:
self.sendPositiveResponse(tag, 'Subscribed')
auth_SUBSCRIBE = (do_SUBSCRIBE, arg_astring)
select_SUBSCRIBE = auth_SUBSCRIBE
def do_UNSUBSCRIBE(self, tag, name):
name = self._parseMbox(name)
try:
self.account.unsubscribe(name)
except MailboxException, m:
self.sendNegativeResponse(tag, str(m))
except:
self.sendBadResponse(tag, "Server error encountered while unsubscribing from mailbox")
log.err()
else:
self.sendPositiveResponse(tag, 'Unsubscribed')
auth_UNSUBSCRIBE = (do_UNSUBSCRIBE, arg_astring)
select_UNSUBSCRIBE = auth_UNSUBSCRIBE
def _listWork(self, tag, ref, mbox, sub, cmdName):
mbox = self._parseMbox(mbox)
maybeDeferred(self.account.listMailboxes, ref, mbox
).addCallback(self._cbListWork, tag, sub, cmdName
).addErrback(self._ebListWork, tag
)
def _cbListWork(self, mailboxes, tag, sub, cmdName):
for (name, box) in mailboxes:
if not sub or self.account.isSubscribed(name):
flags = box.getFlags()
delim = box.getHierarchicalDelimiter()
resp = (DontQuoteMe(cmdName), map(DontQuoteMe, flags), delim, name.encode('imap4-utf-7'))
self.sendUntaggedResponse(collapseNestedLists(resp))
self.sendPositiveResponse(tag, '%s completed' % (cmdName,))
def _ebListWork(self, failure, tag):
self.sendBadResponse(tag, "Server error encountered while listing mailboxes.")
log.err(failure)
auth_LIST = (_listWork, arg_astring, arg_astring, 0, 'LIST')
select_LIST = auth_LIST
auth_LSUB = (_listWork, arg_astring, arg_astring, 1, 'LSUB')
select_LSUB = auth_LSUB
def do_STATUS(self, tag, mailbox, names):
mailbox = self._parseMbox(mailbox)
maybeDeferred(self.account.select, mailbox, 0
).addCallback(self._cbStatusGotMailbox, tag, mailbox, names
).addErrback(self._ebStatusGotMailbox, tag
)
def _cbStatusGotMailbox(self, mbox, tag, mailbox, names):
if mbox:
maybeDeferred(mbox.requestStatus, names).addCallbacks(
self.__cbStatus, self.__ebStatus,
(tag, mailbox), None, (tag, mailbox), None
)
else:
self.sendNegativeResponse(tag, "Could not open mailbox")
def _ebStatusGotMailbox(self, failure, tag):
self.sendBadResponse(tag, "Server error encountered while opening mailbox.")
log.err(failure)
auth_STATUS = (do_STATUS, arg_astring, arg_plist)
select_STATUS = auth_STATUS
def __cbStatus(self, status, tag, box):
line = ' '.join(['%s %s' % x for x in status.iteritems()])
self.sendUntaggedResponse('STATUS %s (%s)' % (box, line))
self.sendPositiveResponse(tag, 'STATUS complete')
def __ebStatus(self, failure, tag, box):
self.sendBadResponse(tag, 'STATUS %s failed: %s' % (box, str(failure.value)))
def do_APPEND(self, tag, mailbox, flags, date, message):
mailbox = self._parseMbox(mailbox)
maybeDeferred(self.account.select, mailbox
).addCallback(self._cbAppendGotMailbox, tag, flags, date, message
).addErrback(self._ebAppendGotMailbox, tag
)
def _cbAppendGotMailbox(self, mbox, tag, flags, date, message):
if not mbox:
self.sendNegativeResponse(tag, '[TRYCREATE] No such mailbox')
return
d = mbox.addMessage(message, flags, date)
d.addCallback(self.__cbAppend, tag, mbox)
d.addErrback(self.__ebAppend, tag)
def _ebAppendGotMailbox(self, failure, tag):
self.sendBadResponse(tag, "Server error encountered while opening mailbox.")
log.err(failure)
auth_APPEND = (do_APPEND, arg_astring, opt_plist, opt_datetime,
arg_literal)
select_APPEND = auth_APPEND
def __cbAppend(self, result, tag, mbox):
self.sendUntaggedResponse('%d EXISTS' % mbox.getMessageCount())
self.sendPositiveResponse(tag, 'APPEND complete')
def __ebAppend(self, failure, tag):
self.sendBadResponse(tag, 'APPEND failed: ' + str(failure.value))
def do_CHECK(self, tag):
d = self.checkpoint()
if d is None:
self.__cbCheck(None, tag)
else:
d.addCallbacks(
self.__cbCheck,
self.__ebCheck,
callbackArgs=(tag,),
errbackArgs=(tag,)
)
select_CHECK = (do_CHECK,)
def __cbCheck(self, result, tag):
self.sendPositiveResponse(tag, 'CHECK completed')
def __ebCheck(self, failure, tag):
self.sendBadResponse(tag, 'CHECK failed: ' + str(failure.value))
def checkpoint(self):
"""Called when the client issues a CHECK command.
This should perform any checkpoint operations required by the server.
It may be a long running operation, but may not block. If it returns
a deferred, the client will only be informed of success (or failure)
when the deferred's callback (or errback) is invoked.
"""
return None
def do_CLOSE(self, tag):
d = None
if self.mbox.isWriteable():
d = maybeDeferred(self.mbox.expunge)
cmbx = ICloseableMailbox(self.mbox, None)
if cmbx is not None:
if d is not None:
d.addCallback(lambda result: cmbx.close())
else:
d = maybeDeferred(cmbx.close)
if d is not None:
d.addCallbacks(self.__cbClose, self.__ebClose, (tag,), None, (tag,), None)
else:
self.__cbClose(None, tag)
select_CLOSE = (do_CLOSE,)
def __cbClose(self, result, tag):
self.sendPositiveResponse(tag, 'CLOSE completed')
self.mbox.removeListener(self)
self.mbox = None
self.state = 'auth'
def __ebClose(self, failure, tag):
self.sendBadResponse(tag, 'CLOSE failed: ' + str(failure.value))
def do_EXPUNGE(self, tag):
if self.mbox.isWriteable():
maybeDeferred(self.mbox.expunge).addCallbacks(
self.__cbExpunge, self.__ebExpunge, (tag,), None, (tag,), None
)
else:
self.sendNegativeResponse(tag, 'EXPUNGE ignored on read-only mailbox')
select_EXPUNGE = (do_EXPUNGE,)
def __cbExpunge(self, result, tag):
for e in result:
self.sendUntaggedResponse('%d EXPUNGE' % e)
self.sendPositiveResponse(tag, 'EXPUNGE completed')
def __ebExpunge(self, failure, tag):
self.sendBadResponse(tag, 'EXPUNGE failed: ' + str(failure.value))
log.err(failure)
def do_SEARCH(self, tag, charset, query, uid=0):
sm = ISearchableMailbox(self.mbox, None)
if sm is not None:
maybeDeferred(sm.search, query, uid=uid).addCallbacks(
self.__cbSearch, self.__ebSearch,
(tag, self.mbox, uid), None, (tag,), None
)
else:
s = parseIdList('1:*')
maybeDeferred(self.mbox.fetch, s, uid=uid).addCallbacks(
self.__cbManualSearch, self.__ebSearch,
(tag, self.mbox, query, uid), None, (tag,), None
)
select_SEARCH = (do_SEARCH, opt_charset, arg_searchkeys)
def __cbSearch(self, result, tag, mbox, uid):
if uid:
result = map(mbox.getUID, result)
ids = ' '.join([str(i) for i in result])
self.sendUntaggedResponse('SEARCH ' + ids)
self.sendPositiveResponse(tag, 'SEARCH completed')
def __cbManualSearch(self, result, tag, mbox, query, uid, searchResults = None):
if searchResults is None:
searchResults = []
i = 0
for (i, (id, msg)) in zip(range(5), result):
if self.searchFilter(query, id, msg):
if uid:
searchResults.append(str(msg.getUID()))
else:
searchResults.append(str(id))
if i == 4:
from twisted.internet import reactor
reactor.callLater(0, self.__cbManualSearch, result, tag, mbox, query, uid, searchResults)
else:
if searchResults:
self.sendUntaggedResponse('SEARCH ' + ' '.join(searchResults))
self.sendPositiveResponse(tag, 'SEARCH completed')
def searchFilter(self, query, id, msg):
while query:
if not self.singleSearchStep(query, id, msg):
return False
return True
def singleSearchStep(self, query, id, msg):
q = query.pop(0)
if isinstance(q, list):
if not self.searchFilter(q, id, msg):
return False
else:
c = q.upper()
f = getattr(self, 'search_' + c)
if f:
if not f(query, id, msg):
return False
else:
# IMAP goes *out of its way* to be complex
# Sequence sets to search should be specified
# with a command, like EVERYTHING ELSE.
try:
m = parseIdList(c)
except:
log.err('Unknown search term: ' + c)
else:
if id not in m:
return False
return True
def search_ALL(self, query, id, msg):
return True
def search_ANSWERED(self, query, id, msg):
return '\\Answered' in msg.getFlags()
def search_BCC(self, query, id, msg):
bcc = msg.getHeaders(False, 'bcc').get('bcc', '')
return bcc.lower().find(query.pop(0).lower()) != -1
def search_BEFORE(self, query, id, msg):
date = parseTime(query.pop(0))
return rfc822.parsedate(msg.getInternalDate()) < date
def search_BODY(self, query, id, msg):
body = query.pop(0).lower()
return text.strFile(body, msg.getBodyFile(), False)
def search_CC(self, query, id, msg):
cc = msg.getHeaders(False, 'cc').get('cc', '')
return cc.lower().find(query.pop(0).lower()) != -1
def search_DELETED(self, query, id, msg):
return '\\Deleted' in msg.getFlags()
def search_DRAFT(self, query, id, msg):
return '\\Draft' in msg.getFlags()
def search_FLAGGED(self, query, id, msg):
return '\\Flagged' in msg.getFlags()
def search_FROM(self, query, id, msg):
fm = msg.getHeaders(False, 'from').get('from', '')
return fm.lower().find(query.pop(0).lower()) != -1
def search_HEADER(self, query, id, msg):
hdr = query.pop(0).lower()
hdr = msg.getHeaders(False, hdr).get(hdr, '')
return hdr.lower().find(query.pop(0).lower()) != -1
def search_KEYWORD(self, query, id, msg):
query.pop(0)
return False
def search_LARGER(self, query, id, msg):
return int(query.pop(0)) < msg.getSize()
def search_NEW(self, query, id, msg):
return '\\Recent' in msg.getFlags() and '\\Seen' not in msg.getFlags()
def search_NOT(self, query, id, msg):
return not self.singleSearchStep(query, id, msg)
def search_OLD(self, query, id, msg):
return '\\Recent' not in msg.getFlags()
def search_ON(self, query, id, msg):
date = parseTime(query.pop(0))
return rfc822.parsedate(msg.getInternalDate()) == date
def search_OR(self, query, id, msg):
a = self.singleSearchStep(query, id, msg)
b = self.singleSearchStep(query, id, msg)
return a or b
def search_RECENT(self, query, id, msg):
return '\\Recent' in msg.getFlags()
def search_SEEN(self, query, id, msg):
return '\\Seen' in msg.getFlags()
def search_SENTBEFORE(self, query, id, msg):
date = msg.getHeader(False, 'date').get('date', '')
date = rfc822.parsedate(date)
return date < parseTime(query.pop(0))
def search_SENTON(self, query, id, msg):
date = msg.getHeader(False, 'date').get('date', '')
date = rfc822.parsedate(date)
return date[:3] == parseTime(query.pop(0))[:3]
def search_SENTSINCE(self, query, id, msg):
date = msg.getHeader(False, 'date').get('date', '')
date = rfc822.parsedate(date)
return date > parseTime(query.pop(0))
def search_SINCE(self, query, id, msg):
date = parseTime(query.pop(0))
return rfc822.parsedate(msg.getInternalDate()) > date
def search_SMALLER(self, query, id, msg):
return int(query.pop(0)) > msg.getSize()
def search_SUBJECT(self, query, id, msg):
subj = msg.getHeaders(False, 'subject').get('subject', '')
return subj.lower().find(query.pop(0).lower()) != -1
def search_TEXT(self, query, id, msg):
# XXX - This must search headers too
body = query.pop(0).lower()
return text.strFile(body, msg.getBodyFile(), False)
def search_TO(self, query, id, msg):
to = msg.getHeaders(False, 'to').get('to', '')
return to.lower().find(query.pop(0).lower()) != -1
def search_UID(self, query, id, msg):
c = query.pop(0)
m = parseIdList(c)
return msg.getUID() in m
def search_UNANSWERED(self, query, id, msg):
return '\\Answered' not in msg.getFlags()
def search_UNDELETED(self, query, id, msg):
return '\\Deleted' not in msg.getFlags()
def search_UNDRAFT(self, query, id, msg):
return '\\Draft' not in msg.getFlags()
def search_UNFLAGGED(self, query, id, msg):
return '\\Flagged' not in msg.getFlags()
def search_UNKEYWORD(self, query, id, msg):
query.pop(0)
return False
def search_UNSEEN(self, query, id, msg):
return '\\Seen' not in msg.getFlags()
def __ebSearch(self, failure, tag):
self.sendBadResponse(tag, 'SEARCH failed: ' + str(failure.value))
log.err(failure)
def do_FETCH(self, tag, messages, query, uid=0):
if query:
maybeDeferred(self.mbox.fetch, messages, uid=uid
).addCallback(iter
).addCallback(self.__cbFetch, tag, query, uid
).addErrback(self.__ebFetch, tag
)
else:
self.sendPositiveResponse(tag, 'FETCH complete')
select_FETCH = (do_FETCH, arg_seqset, arg_fetchatt)
def __cbFetch(self, results, tag, query, uid):
if self.blocked is None:
self.blocked = []
self._oldTimeout = self.setTimeout(None)
try:
id, msg = results.next()
except StopIteration:
# All results have been processed, deliver completion notification.
self.sendPositiveResponse(tag, 'FETCH completed')
# The idle timeout was suspended while we delivered results,
# restore it now.
self.setTimeout(self._oldTimeout)
del self._oldTimeout
# Instance state is now consistent again (ie, it is as though
# the fetch command never ran), so allow any pending blocked
# commands to execute.
self._unblock()
else:
self.spewMessage(id, msg, query, uid
).addCallback(lambda _: self.__cbFetch(results, tag, query, uid)
).addErrback(self.__ebSpewMessage
)
def __ebSpewMessage(self, failure):
# This indicates a programming error.
# There's no reliable way to indicate anything to the client, since we
# may have already written an arbitrary amount of data in response to
# the command.
log.err(failure)
self.transport.loseConnection()
def spew_envelope(self, id, msg, _w=None, _f=None):
if _w is None:
_w = self.transport.write
_w('ENVELOPE ' + collapseNestedLists([getEnvelope(msg)]))
def spew_flags(self, id, msg, _w=None, _f=None):
if _w is None:
_w = self.transport.write
_w('FLAGS ' + '(%s)' % (' '.join(msg.getFlags())))
def spew_internaldate(self, id, msg, _w=None, _f=None):
if _w is None:
_w = self.transport.write
idate = msg.getInternalDate()
ttup = rfc822.parsedate_tz(idate)
if ttup is None:
log.msg("%d:%r: unpareseable internaldate: %r" % (id, msg, idate))
raise IMAP4Exception("Internal failure generating INTERNALDATE")
odate = time.strftime("%d-%b-%Y %H:%M:%S ", ttup[:9])
if ttup[9] is None:
odate = odate + "+0000"
else:
if ttup[9] >= 0:
sign = "+"
else:
sign = "-"
odate = odate + sign + string.zfill(str(((abs(ttup[9]) / 3600) * 100 + (abs(ttup[9]) % 3600) / 60)), 4)
_w('INTERNALDATE ' + _quote(odate))
def spew_rfc822header(self, id, msg, _w=None, _f=None):
if _w is None:
_w = self.transport.write
hdrs = _formatHeaders(msg.getHeaders(True))
_w('RFC822.HEADER ' + _literal(hdrs))
def spew_rfc822text(self, id, msg, _w=None, _f=None):
if _w is None:
_w = self.transport.write
_w('RFC822.TEXT ')
_f()
return FileProducer(msg.getBodyFile()
).beginProducing(self.transport
)
def spew_rfc822size(self, id, msg, _w=None, _f=None):
if _w is None:
_w = self.transport.write
_w('RFC822.SIZE ' + str(msg.getSize()))
def spew_rfc822(self, id, msg, _w=None, _f=None):
if _w is None:
_w = self.transport.write
_w('RFC822 ')
_f()
mf = IMessageFile(msg, None)
if mf is not None:
return FileProducer(mf.open()
).beginProducing(self.transport
)
return MessageProducer(msg, None, self._scheduler
).beginProducing(self.transport
)
def spew_uid(self, id, msg, _w=None, _f=None):
if _w is None:
_w = self.transport.write
_w('UID ' + str(msg.getUID()))
def spew_bodystructure(self, id, msg, _w=None, _f=None):
_w('BODYSTRUCTURE ' + collapseNestedLists([getBodyStructure(msg, True)]))
def spew_body(self, part, id, msg, _w=None, _f=None):
if _w is None:
_w = self.transport.write
for p in part.part:
if msg.isMultipart():
msg = msg.getSubPart(p)
elif p > 0:
# Non-multipart messages have an implicit first part but no
# other parts - reject any request for any other part.
raise TypeError("Requested subpart of non-multipart message")
if part.header:
hdrs = msg.getHeaders(part.header.negate, *part.header.fields)
hdrs = _formatHeaders(hdrs)
_w(str(part) + ' ' + _literal(hdrs))
elif part.text:
_w(str(part) + ' ')
_f()
return FileProducer(msg.getBodyFile()
).beginProducing(self.transport
)
elif part.mime:
hdrs = _formatHeaders(msg.getHeaders(True))
_w(str(part) + ' ' + _literal(hdrs))
elif part.empty:
_w(str(part) + ' ')
_f()
if part.part:
return FileProducer(msg.getBodyFile()
).beginProducing(self.transport
)
else:
mf = IMessageFile(msg, None)
if mf is not None:
return FileProducer(mf.open()).beginProducing(self.transport)
return MessageProducer(msg, None, self._scheduler).beginProducing(self.transport)
else:
_w('BODY ' + collapseNestedLists([getBodyStructure(msg)]))
def spewMessage(self, id, msg, query, uid):
wbuf = WriteBuffer(self.transport)
write = wbuf.write
flush = wbuf.flush
def start():
write('* %d FETCH (' % (id,))
def finish():
write(')\r\n')
def space():
write(' ')
def spew():
seenUID = False
start()
for part in query:
if part.type == 'uid':
seenUID = True
if part.type == 'body':
yield self.spew_body(part, id, msg, write, flush)
else:
f = getattr(self, 'spew_' + part.type)
yield f(id, msg, write, flush)
if part is not query[-1]:
space()
if uid and not seenUID:
space()
yield self.spew_uid(id, msg, write, flush)
finish()
flush()
return self._scheduler(spew())
def __ebFetch(self, failure, tag):
log.err(failure)
self.sendBadResponse(tag, 'FETCH failed: ' + str(failure.value))
def do_STORE(self, tag, messages, mode, flags, uid=0):
mode = mode.upper()
silent = mode.endswith('SILENT')
if mode.startswith('+'):
mode = 1
elif mode.startswith('-'):
mode = -1
else:
mode = 0
maybeDeferred(self.mbox.store, messages, flags, mode, uid=uid).addCallbacks(
self.__cbStore, self.__ebStore, (tag, self.mbox, uid, silent), None, (tag,), None
)
select_STORE = (do_STORE, arg_seqset, arg_atom, arg_flaglist)
def __cbStore(self, result, tag, mbox, uid, silent):
if result and not silent:
for (k, v) in result.iteritems():
if uid:
uidstr = ' UID %d' % mbox.getUID(k)
else:
uidstr = ''
self.sendUntaggedResponse('%d FETCH (FLAGS (%s)%s)' %
(k, ' '.join(v), uidstr))
self.sendPositiveResponse(tag, 'STORE completed')
def __ebStore(self, failure, tag):
self.sendBadResponse(tag, 'Server error: ' + str(failure.value))
def do_COPY(self, tag, messages, mailbox, uid=0):
mailbox = self._parseMbox(mailbox)
maybeDeferred(self.account.select, mailbox
).addCallback(self._cbCopySelectedMailbox, tag, messages, mailbox, uid
).addErrback(self._ebCopySelectedMailbox, tag
)
select_COPY = (do_COPY, arg_seqset, arg_astring)
def _cbCopySelectedMailbox(self, mbox, tag, messages, mailbox, uid):
if not mbox:
self.sendNegativeResponse(tag, 'No such mailbox: ' + mailbox)
else:
maybeDeferred(self.mbox.fetch, messages, uid
).addCallback(self.__cbCopy, tag, mbox
).addCallback(self.__cbCopied, tag, mbox
).addErrback(self.__ebCopy, tag
)
def _ebCopySelectedMailbox(self, failure, tag):
self.sendBadResponse(tag, 'Server error: ' + str(failure.value))
def __cbCopy(self, messages, tag, mbox):
# XXX - This should handle failures with a rollback or something
addedDeferreds = []
addedIDs = []
failures = []
fastCopyMbox = IMessageCopier(mbox, None)
for (id, msg) in messages:
if fastCopyMbox is not None:
d = maybeDeferred(fastCopyMbox.copy, msg)
addedDeferreds.append(d)
continue
# XXX - The following should be an implementation of IMessageCopier.copy
# on an IMailbox->IMessageCopier adapter.
flags = msg.getFlags()
date = msg.getInternalDate()
body = IMessageFile(msg, None)
if body is not None:
bodyFile = body.open()
d = maybeDeferred(mbox.addMessage, bodyFile, flags, date)
else:
def rewind(f):
f.seek(0)
return f
buffer = tempfile.TemporaryFile()
d = MessageProducer(msg, buffer, self._scheduler
).beginProducing(None
).addCallback(lambda _, b=buffer, f=flags, d=date: mbox.addMessage(rewind(b), f, d)
)
addedDeferreds.append(d)
return defer.DeferredList(addedDeferreds)
def __cbCopied(self, deferredIds, tag, mbox):
ids = []
failures = []
for (status, result) in deferredIds:
if status:
ids.append(result)
else:
failures.append(result.value)
if failures:
self.sendNegativeResponse(tag, '[ALERT] Some messages were not copied')
else:
self.sendPositiveResponse(tag, 'COPY completed')
def __ebCopy(self, failure, tag):
self.sendBadResponse(tag, 'COPY failed:' + str(failure.value))
log.err(failure)
def do_UID(self, tag, command, line):
command = command.upper()
if command not in ('COPY', 'FETCH', 'STORE', 'SEARCH'):
raise IllegalClientResponse(command)
self.dispatchCommand(tag, command, line, uid=1)
select_UID = (do_UID, arg_atom, arg_line)
#
# IMailboxListener implementation
#
def modeChanged(self, writeable):
if writeable:
self.sendUntaggedResponse(message='[READ-WRITE]', async=True)
else:
self.sendUntaggedResponse(message='[READ-ONLY]', async=True)
def flagsChanged(self, newFlags):
for (mId, flags) in newFlags.iteritems():
msg = '%d FETCH (FLAGS (%s))' % (mId, ' '.join(flags))
self.sendUntaggedResponse(msg, async=True)
def newMessages(self, exists, recent):
if exists is not None:
self.sendUntaggedResponse('%d EXISTS' % exists, async=True)
if recent is not None:
self.sendUntaggedResponse('%d RECENT' % recent, async=True)
class UnhandledResponse(IMAP4Exception): pass
class NegativeResponse(IMAP4Exception): pass
class NoSupportedAuthentication(IMAP4Exception):
def __init__(self, serverSupports, clientSupports):
IMAP4Exception.__init__(self, 'No supported authentication schemes available')
self.serverSupports = serverSupports
self.clientSupports = clientSupports
def __str__(self):
return (IMAP4Exception.__str__(self)
+ ': Server supports %r, client supports %r'
% (self.serverSupports, self.clientSupports))
class IllegalServerResponse(IMAP4Exception): pass
TIMEOUT_ERROR = error.TimeoutError()
class IMAP4Client(basic.LineReceiver, policies.TimeoutMixin):
"""IMAP4 client protocol implementation
@ivar state: A string representing the state the connection is currently
in.
"""
implements(IMailboxListener)
tags = None
waiting = None
queued = None
tagID = 1
state = None
startedTLS = False
# Number of seconds to wait before timing out a connection.
# If the number is <= 0 no timeout checking will be performed.
timeout = 0
# Capabilities are not allowed to change during the session
# So cache the first response and use that for all later
# lookups
_capCache = None
_memoryFileLimit = 1024 * 1024 * 10
# Authentication is pluggable. This maps names to IClientAuthentication
# objects.
authenticators = None
STATUS_CODES = ('OK', 'NO', 'BAD', 'PREAUTH', 'BYE')
STATUS_TRANSFORMATIONS = {
'MESSAGES': int, 'RECENT': int, 'UNSEEN': int
}
context = None
def __init__(self, contextFactory = None):
self.tags = {}
self.queued = []
self.authenticators = {}
self.context = contextFactory
self._tag = None
self._parts = None
self._lastCmd = None
def registerAuthenticator(self, auth):
"""Register a new form of authentication
When invoking the authenticate() method of IMAP4Client, the first
matching authentication scheme found will be used. The ordering is
that in which the server lists support authentication schemes.
@type auth: Implementor of C{IClientAuthentication}
@param auth: The object to use to perform the client
side of this authentication scheme.
"""
self.authenticators[auth.getName().upper()] = auth
def rawDataReceived(self, data):
if self.timeout > 0:
self.resetTimeout()
self._pendingSize -= len(data)
if self._pendingSize > 0:
self._pendingBuffer.write(data)
else:
passon = ''
if self._pendingSize < 0:
data, passon = data[:self._pendingSize], data[self._pendingSize:]
self._pendingBuffer.write(data)
rest = self._pendingBuffer
self._pendingBuffer = None
self._pendingSize = None
rest.seek(0, 0)
self._parts.append(rest.read())
self.setLineMode(passon.lstrip('\r\n'))
# def sendLine(self, line):
# print 'S:', repr(line)
# return basic.LineReceiver.sendLine(self, line)
def _setupForLiteral(self, rest, octets):
self._pendingBuffer = self.messageFile(octets)
self._pendingSize = octets
if self._parts is None:
self._parts = [rest, '\r\n']
else:
self._parts.extend([rest, '\r\n'])
self.setRawMode()
def connectionMade(self):
if self.timeout > 0:
self.setTimeout(self.timeout)
def connectionLost(self, reason):
"""We are no longer connected"""
if self.timeout > 0:
self.setTimeout(None)
if self.queued is not None:
queued = self.queued
self.queued = None
for cmd in queued:
cmd.defer.errback(reason)
if self.tags is not None:
tags = self.tags
self.tags = None
for cmd in tags.itervalues():
if cmd is not None and cmd.defer is not None:
cmd.defer.errback(reason)
def lineReceived(self, line):
# print 'C: ' + repr(line)
if self.timeout > 0:
self.resetTimeout()
lastPart = line.rfind(' ')
if lastPart != -1:
lastPart = line[lastPart + 1:]
if lastPart.startswith('{') and lastPart.endswith('}'):
# It's a literal a-comin' in
try:
octets = int(lastPart[1:-1])
except ValueError:
raise IllegalServerResponse(line)
if self._parts is None:
self._tag, parts = line.split(None, 1)
else:
parts = line
self._setupForLiteral(parts, octets)
return
if self._parts is None:
# It isn't a literal at all
self._regularDispatch(line)
else:
# If an expression is in progress, no tag is required here
# Since we didn't find a literal indicator, this expression
# is done.
self._parts.append(line)
tag, rest = self._tag, ''.join(self._parts)
self._tag = self._parts = None
self.dispatchCommand(tag, rest)
def timeoutConnection(self):
if self._lastCmd and self._lastCmd.defer is not None:
d, self._lastCmd.defer = self._lastCmd.defer, None
d.errback(TIMEOUT_ERROR)
if self.queued:
for cmd in self.queued:
if cmd.defer is not None:
d, cmd.defer = cmd.defer, d
d.errback(TIMEOUT_ERROR)
self.transport.loseConnection()
def _regularDispatch(self, line):
parts = line.split(None, 1)
if len(parts) != 2:
parts.append('')
tag, rest = parts
self.dispatchCommand(tag, rest)
def messageFile(self, octets):
"""Create a file to which an incoming message may be written.
@type octets: C{int}
@param octets: The number of octets which will be written to the file
@rtype: Any object which implements C{write(string)} and
C{seek(int, int)}
@return: A file-like object
"""
if octets > self._memoryFileLimit:
return tempfile.TemporaryFile()
else:
return StringIO.StringIO()
def makeTag(self):
tag = '%0.4X' % self.tagID
self.tagID += 1
return tag
def dispatchCommand(self, tag, rest):
if self.state is None:
f = self.response_UNAUTH
else:
f = getattr(self, 'response_' + self.state.upper(), None)
if f:
try:
f(tag, rest)
except:
log.err()
self.transport.loseConnection()
else:
log.err("Cannot dispatch: %s, %s, %s" % (self.state, tag, rest))
self.transport.loseConnection()
def response_UNAUTH(self, tag, rest):
if self.state is None:
# Server greeting, this is
status, rest = rest.split(None, 1)
if status.upper() == 'OK':
self.state = 'unauth'
elif status.upper() == 'PREAUTH':
self.state = 'auth'
else:
# XXX - This is rude.
self.transport.loseConnection()
raise IllegalServerResponse(tag + ' ' + rest)
b, e = rest.find('['), rest.find(']')
if b != -1 and e != -1:
self.serverGreeting(self.__cbCapabilities(([rest[b:e]], None)))
else:
self.serverGreeting(None)
else:
self._defaultHandler(tag, rest)
def response_AUTH(self, tag, rest):
self._defaultHandler(tag, rest)
def _defaultHandler(self, tag, rest):
if tag == '*' or tag == '+':
if not self.waiting:
self._extraInfo([rest])
else:
cmd = self.tags[self.waiting]
if tag == '+':
cmd.continuation(rest)
else:
cmd.lines.append(rest)
else:
try:
cmd = self.tags[tag]
except KeyError:
# XXX - This is rude.
self.transport.loseConnection()
raise IllegalServerResponse(tag + ' ' + rest)
else:
status, line = rest.split(None, 1)
if status == 'OK':
# Give them this last line, too
cmd.finish(rest, self._extraInfo)
else:
cmd.defer.errback(IMAP4Exception(line))
del self.tags[tag]
self.waiting = None
self._flushQueue()
def _flushQueue(self):
if self.queued:
cmd = self.queued.pop(0)
t = self.makeTag()
self.tags[t] = cmd
self.sendLine(cmd.format(t))
self.waiting = t
def _extraInfo(self, lines):
# XXX - This is terrible.
# XXX - Also, this should collapse temporally proximate calls into single
# invocations of IMailboxListener methods, where possible.
flags = {}
recent = exists = None
for L in lines:
if L.find('EXISTS') != -1:
exists = int(L.split()[0])
elif L.find('RECENT') != -1:
recent = int(L.split()[0])
elif L.find('READ-ONLY') != -1:
self.modeChanged(0)
elif L.find('READ-WRITE') != -1:
self.modeChanged(1)
elif L.find('FETCH') != -1:
for (mId, fetched) in self.__cbFetch(([L], None)).iteritems():
sum = []
for f in fetched.get('FLAGS', []):
sum.append(f)
flags.setdefault(mId, []).extend(sum)
else:
log.msg('Unhandled unsolicited response: ' + repr(L))
if flags:
self.flagsChanged(flags)
if recent is not None or exists is not None:
self.newMessages(exists, recent)
def sendCommand(self, cmd):
cmd.defer = defer.Deferred()
if self.waiting:
self.queued.append(cmd)
return cmd.defer
t = self.makeTag()
self.tags[t] = cmd
self.sendLine(cmd.format(t))
self.waiting = t
self._lastCmd = cmd
return cmd.defer
def getCapabilities(self, useCache=1):
"""Request the capabilities available on this server.
This command is allowed in any state of connection.
@type useCache: C{bool}
@param useCache: Specify whether to use the capability-cache or to
re-retrieve the capabilities from the server. Server capabilities
should never change, so for normal use, this flag should never be
false.
@rtype: C{Deferred}
@return: A deferred whose callback will be invoked with a
dictionary mapping capability types to lists of supported
mechanisms, or to None if a support list is not applicable.
"""
if useCache and self._capCache is not None:
return defer.succeed(self._capCache)
cmd = 'CAPABILITY'
resp = ('CAPABILITY',)
d = self.sendCommand(Command(cmd, wantResponse=resp))
d.addCallback(self.__cbCapabilities)
return d
def __cbCapabilities(self, (lines, tagline)):
caps = {}
for rest in lines:
rest = rest.split()[1:]
for cap in rest:
eq = cap.find('=')
if eq == -1:
caps[cap] = None
else:
caps.setdefault(cap[:eq], []).append(cap[eq+1:])
self._capCache = caps
return caps
def logout(self):
"""Inform the server that we are done with the connection.
This command is allowed in any state of connection.
@rtype: C{Deferred}
@return: A deferred whose callback will be invoked with None
when the proper server acknowledgement has been received.
"""
d = self.sendCommand(Command('LOGOUT', wantResponse=('BYE',)))
d.addCallback(self.__cbLogout)
return d
def __cbLogout(self, (lines, tagline)):
self.transport.loseConnection()
# We don't particularly care what the server said
return None
def noop(self):
"""Perform no operation.
This command is allowed in any state of connection.
@rtype: C{Deferred}
@return: A deferred whose callback will be invoked with a list
of untagged status updates the server responds with.
"""
d = self.sendCommand(Command('NOOP'))
d.addCallback(self.__cbNoop)
return d
def __cbNoop(self, (lines, tagline)):
# Conceivable, this is elidable.
# It is, afterall, a no-op.
return lines
def startTLS(self, contextFactory=None):
"""
Initiates a 'STARTTLS' request and negotiates the TLS / SSL
Handshake.
@param contextFactory: The TLS / SSL Context Factory to
leverage. If the contextFactory is None the IMAP4Client will
either use the current TLS / SSL Context Factory or attempt to
create a new one.
@type contextFactory: C{ssl.ClientContextFactory}
@return: A Deferred which fires when the transport has been
secured according to the given contextFactory, or which fails
if the transport cannot be secured.
"""
assert not self.startedTLS, "Client and Server are currently communicating via TLS"
if contextFactory is None:
contextFactory = self._getContextFactory()
if contextFactory is None:
return defer.fail(IMAP4Exception(
"IMAP4Client requires a TLS context to "
"initiate the STARTTLS handshake"))
if 'STARTTLS' not in self._capCache:
return defer.fail(IMAP4Exception(
"Server does not support secure communication "
"via TLS / SSL"))
tls = interfaces.ITLSTransport(self.transport, None)
if tls is None:
return defer.fail(IMAP4Exception(
"IMAP4Client transport does not implement "
"interfaces.ITLSTransport"))
d = self.sendCommand(Command('STARTTLS'))
d.addCallback(self._startedTLS, contextFactory)
d.addCallback(lambda _: self.getCapabilities())
return d
def authenticate(self, secret):
"""Attempt to enter the authenticated state with the server
This command is allowed in the Non-Authenticated state.
@rtype: C{Deferred}
@return: A deferred whose callback is invoked if the authentication
succeeds and whose errback will be invoked otherwise.
"""
if self._capCache is None:
d = self.getCapabilities()
else:
d = defer.succeed(self._capCache)
d.addCallback(self.__cbAuthenticate, secret)
return d
def __cbAuthenticate(self, caps, secret):
auths = caps.get('AUTH', ())
for scheme in auths:
if scheme.upper() in self.authenticators:
cmd = Command('AUTHENTICATE', scheme, (),
self.__cbContinueAuth, scheme,
secret)
return self.sendCommand(cmd)
if self.startedTLS:
return defer.fail(NoSupportedAuthentication(
auths, self.authenticators.keys()))
else:
def ebStartTLS(err):
err.trap(IMAP4Exception)
# We couldn't negotiate TLS for some reason
return defer.fail(NoSupportedAuthentication(
auths, self.authenticators.keys()))
d = self.startTLS()
d.addErrback(ebStartTLS)
d.addCallback(lambda _: self.getCapabilities())
d.addCallback(self.__cbAuthTLS, secret)
return d
def __cbContinueAuth(self, rest, scheme, secret):
try:
chal = base64.decodestring(rest + '\n')
except binascii.Error:
self.sendLine('*')
raise IllegalServerResponse(rest)
self.transport.loseConnection()
else:
auth = self.authenticators[scheme]
chal = auth.challengeResponse(secret, chal)
self.sendLine(base64.encodestring(chal).strip())
def __cbAuthTLS(self, caps, secret):
auths = caps.get('AUTH', ())
for scheme in auths:
if scheme.upper() in self.authenticators:
cmd = Command('AUTHENTICATE', scheme, (),
self.__cbContinueAuth, scheme,
secret)
return self.sendCommand(cmd)
raise NoSupportedAuthentication(auths, self.authenticators.keys())
def login(self, username, password):
"""Authenticate with the server using a username and password
This command is allowed in the Non-Authenticated state. If the
server supports the STARTTLS capability and our transport supports
TLS, TLS is negotiated before the login command is issued.
A more secure way to log in is to use C{startTLS} or
C{authenticate} or both.
@type username: C{str}
@param username: The username to log in with
@type password: C{str}
@param password: The password to log in with
@rtype: C{Deferred}
@return: A deferred whose callback is invoked if login is successful
and whose errback is invoked otherwise.
"""
d = maybeDeferred(self.getCapabilities)
d.addCallback(self.__cbLoginCaps, username, password)
return d
def serverGreeting(self, caps):
"""Called when the server has sent us a greeting.
@type caps: C{dict}
@param caps: Capabilities the server advertised in its greeting.
"""
def _getContextFactory(self):
if self.context is not None:
return self.context
try:
from twisted.internet import ssl
except ImportError:
return None
else:
context = ssl.ClientContextFactory()
context.method = ssl.SSL.TLSv1_METHOD
return context
def __cbLoginCaps(self, capabilities, username, password):
# If the server advertises STARTTLS, we might want to try to switch to TLS
tryTLS = 'STARTTLS' in capabilities
# If our transport supports switching to TLS, we might want to try to switch to TLS.
tlsableTransport = interfaces.ITLSTransport(self.transport, None) is not None
# If our transport is not already using TLS, we might want to try to switch to TLS.
nontlsTransport = interfaces.ISSLTransport(self.transport, None) is None
if not self.startedTLS and tryTLS and tlsableTransport and nontlsTransport:
d = self.startTLS()
d.addCallbacks(
self.__cbLoginTLS,
self.__ebLoginTLS,
callbackArgs=(username, password),
)
return d
else:
if nontlsTransport:
log.msg("Server has no TLS support. logging in over cleartext!")
args = ' '.join((_quote(username), _quote(password)))
return self.sendCommand(Command('LOGIN', args))
def _startedTLS(self, result, context):
self.transport.startTLS(context)
self._capCache = None
self.startedTLS = True
return result
def __cbLoginTLS(self, result, username, password):
args = ' '.join((_quote(username), _quote(password)))
return self.sendCommand(Command('LOGIN', args))
def __ebLoginTLS(self, failure):
log.err(failure)
return failure
def namespace(self):
"""Retrieve information about the namespaces available to this account
This command is allowed in the Authenticated and Selected states.
@rtype: C{Deferred}
@return: A deferred whose callback is invoked with namespace
information. An example of this information is::
[[['', '/']], [], []]
which indicates a single personal namespace called '' with '/'
as its hierarchical delimiter, and no shared or user namespaces.
"""
cmd = 'NAMESPACE'
resp = ('NAMESPACE',)
d = self.sendCommand(Command(cmd, wantResponse=resp))
d.addCallback(self.__cbNamespace)
return d
def __cbNamespace(self, (lines, last)):
for line in lines:
parts = line.split(None, 1)
if len(parts) == 2:
if parts[0] == 'NAMESPACE':
# XXX UGGG parsing hack :(
r = parseNestedParens('(' + parts[1] + ')')[0]
return [e or [] for e in r]
log.err("No NAMESPACE response to NAMESPACE command")
return [[], [], []]
def select(self, mailbox):
"""Select a mailbox
This command is allowed in the Authenticated and Selected states.
@type mailbox: C{str}
@param mailbox: The name of the mailbox to select
@rtype: C{Deferred}
@return: A deferred whose callback is invoked with mailbox
information if the select is successful and whose errback is
invoked otherwise. Mailbox information consists of a dictionary
with the following keys and values::
FLAGS: A list of strings containing the flags settable on
messages in this mailbox.
EXISTS: An integer indicating the number of messages in this
mailbox.
RECENT: An integer indicating the number of \"recent\"
messages in this mailbox.
UNSEEN: An integer indicating the number of messages not
flagged \\Seen in this mailbox.
PERMANENTFLAGS: A list of strings containing the flags that
can be permanently set on messages in this mailbox.
UIDVALIDITY: An integer uniquely identifying this mailbox.
"""
cmd = 'SELECT'
args = _prepareMailboxName(mailbox)
resp = ('FLAGS', 'EXISTS', 'RECENT', 'UNSEEN', 'PERMANENTFLAGS', 'UIDVALIDITY')
d = self.sendCommand(Command(cmd, args, wantResponse=resp))
d.addCallback(self.__cbSelect, 1)
return d
def examine(self, mailbox):
"""Select a mailbox in read-only mode
This command is allowed in the Authenticated and Selected states.
@type mailbox: C{str}
@param mailbox: The name of the mailbox to examine
@rtype: C{Deferred}
@return: A deferred whose callback is invoked with mailbox
information if the examine is successful and whose errback
is invoked otherwise. Mailbox information consists of a dictionary
with the following keys and values::
'FLAGS': A list of strings containing the flags settable on
messages in this mailbox.
'EXISTS': An integer indicating the number of messages in this
mailbox.
'RECENT': An integer indicating the number of \"recent\"
messages in this mailbox.
'UNSEEN': An integer indicating the number of messages not
flagged \\Seen in this mailbox.
'PERMANENTFLAGS': A list of strings containing the flags that
can be permanently set on messages in this mailbox.
'UIDVALIDITY': An integer uniquely identifying this mailbox.
"""
cmd = 'EXAMINE'
args = _prepareMailboxName(mailbox)
resp = ('FLAGS', 'EXISTS', 'RECENT', 'UNSEEN', 'PERMANENTFLAGS', 'UIDVALIDITY')
d = self.sendCommand(Command(cmd, args, wantResponse=resp))
d.addCallback(self.__cbSelect, 0)
return d
def __cbSelect(self, (lines, tagline), rw):
# In the absense of specification, we are free to assume:
# READ-WRITE access
datum = {'READ-WRITE': rw}
lines.append(tagline)
for parts in lines:
split = parts.split()
if len(split) == 2:
if split[1].upper().strip() == 'EXISTS':
try:
datum['EXISTS'] = int(split[0])
except ValueError:
raise IllegalServerResponse(parts)
elif split[1].upper().strip() == 'RECENT':
try:
datum['RECENT'] = int(split[0])
except ValueError:
raise IllegalServerResponse(parts)
else:
log.err('Unhandled SELECT response (1): ' + parts)
elif split[0].upper().strip() == 'FLAGS':
split = parts.split(None, 1)
datum['FLAGS'] = tuple(parseNestedParens(split[1])[0])
elif split[0].upper().strip() == 'OK':
begin = parts.find('[')
end = parts.find(']')
if begin == -1 or end == -1:
raise IllegalServerResponse(parts)
else:
content = parts[begin+1:end].split(None, 1)
if len(content) >= 1:
key = content[0].upper()
if key == 'READ-ONLY':
datum['READ-WRITE'] = 0
elif key == 'READ-WRITE':
datum['READ-WRITE'] = 1
elif key == 'UIDVALIDITY':
try:
datum['UIDVALIDITY'] = int(content[1])
except ValueError:
raise IllegalServerResponse(parts)
elif key == 'UNSEEN':
try:
datum['UNSEEN'] = int(content[1])
except ValueError:
raise IllegalServerResponse(parts)
elif key == 'UIDNEXT':
datum['UIDNEXT'] = int(content[1])
elif key == 'PERMANENTFLAGS':
datum['PERMANENTFLAGS'] = tuple(parseNestedParens(content[1])[0])
else:
log.err('Unhandled SELECT response (2): ' + parts)
else:
log.err('Unhandled SELECT response (3): ' + parts)
else:
log.err('Unhandled SELECT response (4): ' + parts)
return datum
def create(self, name):
"""Create a new mailbox on the server
This command is allowed in the Authenticated and Selected states.
@type name: C{str}
@param name: The name of the mailbox to create.
@rtype: C{Deferred}
@return: A deferred whose callback is invoked if the mailbox creation
is successful and whose errback is invoked otherwise.
"""
return self.sendCommand(Command('CREATE', _prepareMailboxName(name)))
def delete(self, name):
"""Delete a mailbox
This command is allowed in the Authenticated and Selected states.
@type name: C{str}
@param name: The name of the mailbox to delete.
@rtype: C{Deferred}
@return: A deferred whose calblack is invoked if the mailbox is
deleted successfully and whose errback is invoked otherwise.
"""
return self.sendCommand(Command('DELETE', _prepareMailboxName(name)))
def rename(self, oldname, newname):
"""Rename a mailbox
This command is allowed in the Authenticated and Selected states.
@type oldname: C{str}
@param oldname: The current name of the mailbox to rename.
@type newname: C{str}
@param newname: The new name to give the mailbox.
@rtype: C{Deferred}
@return: A deferred whose callback is invoked if the rename is
successful and whose errback is invoked otherwise.
"""
oldname = _prepareMailboxName(oldname)
newname = _prepareMailboxName(newname)
return self.sendCommand(Command('RENAME', ' '.join((oldname, newname))))
def subscribe(self, name):
"""Add a mailbox to the subscription list
This command is allowed in the Authenticated and Selected states.
@type name: C{str}
@param name: The mailbox to mark as 'active' or 'subscribed'
@rtype: C{Deferred}
@return: A deferred whose callback is invoked if the subscription
is successful and whose errback is invoked otherwise.
"""
return self.sendCommand(Command('SUBSCRIBE', _prepareMailboxName(name)))
def unsubscribe(self, name):
"""Remove a mailbox from the subscription list
This command is allowed in the Authenticated and Selected states.
@type name: C{str}
@param name: The mailbox to unsubscribe
@rtype: C{Deferred}
@return: A deferred whose callback is invoked if the unsubscription
is successful and whose errback is invoked otherwise.
"""
return self.sendCommand(Command('UNSUBSCRIBE', _prepareMailboxName(name)))
def list(self, reference, wildcard):
"""List a subset of the available mailboxes
This command is allowed in the Authenticated and Selected states.
@type reference: C{str}
@param reference: The context in which to interpret C{wildcard}
@type wildcard: C{str}
@param wildcard: The pattern of mailbox names to match, optionally
including either or both of the '*' and '%' wildcards. '*' will
match zero or more characters and cross hierarchical boundaries.
'%' will also match zero or more characters, but is limited to a
single hierarchical level.
@rtype: C{Deferred}
@return: A deferred whose callback is invoked with a list of C{tuple}s,
the first element of which is a C{tuple} of mailbox flags, the second
element of which is the hierarchy delimiter for this mailbox, and the
third of which is the mailbox name; if the command is unsuccessful,
the deferred's errback is invoked instead.
"""
cmd = 'LIST'
args = '"%s" "%s"' % (reference, wildcard.encode('imap4-utf-7'))
resp = ('LIST',)
d = self.sendCommand(Command(cmd, args, wantResponse=resp))
d.addCallback(self.__cbList, 'LIST')
return d
def lsub(self, reference, wildcard):
"""List a subset of the subscribed available mailboxes
This command is allowed in the Authenticated and Selected states.
The parameters and returned object are the same as for the C{list}
method, with one slight difference: Only mailboxes which have been
subscribed can be included in the resulting list.
"""
cmd = 'LSUB'
args = '"%s" "%s"' % (reference, wildcard.encode('imap4-utf-7'))
resp = ('LSUB',)
d = self.sendCommand(Command(cmd, args, wantResponse=resp))
d.addCallback(self.__cbList, 'LSUB')
return d
def __cbList(self, (lines, last), command):
results = []
for L in lines:
parts = parseNestedParens(L)
if len(parts) != 4:
raise IllegalServerResponse, L
if parts[0] == command:
parts[1] = tuple(parts[1])
results.append(tuple(parts[1:]))
return results
def status(self, mailbox, *names):
"""Retrieve the status of the given mailbox
This command is allowed in the Authenticated and Selected states.
@type mailbox: C{str}
@param mailbox: The name of the mailbox to query
@type names: C{str}
@param names: The status names to query. These may be any number of:
MESSAGES, RECENT, UIDNEXT, UIDVALIDITY, and UNSEEN.
@rtype: C{Deferred}
@return: A deferred whose callback is invoked with the status information
if the command is successful and whose errback is invoked otherwise.
"""
cmd = 'STATUS'
args = "%s (%s)" % (_prepareMailboxName(mailbox), ' '.join(names))
resp = ('STATUS',)
d = self.sendCommand(Command(cmd, args, wantResponse=resp))
d.addCallback(self.__cbStatus)
return d
def __cbStatus(self, (lines, last)):
status = {}
for line in lines:
parts = parseNestedParens(line)
if parts[0] == 'STATUS':
items = parts[2]
items = [items[i:i+2] for i in range(0, len(items), 2)]
status.update(dict(items))
for k in status.keys():
t = self.STATUS_TRANSFORMATIONS.get(k)
if t:
try:
status[k] = t(status[k])
except Exception, e:
raise IllegalServerResponse('(%s %s): %s' % (k, status[k], str(e)))
return status
def append(self, mailbox, message, flags = (), date = None):
"""Add the given message to the given mailbox.
This command is allowed in the Authenticated and Selected states.
@type mailbox: C{str}
@param mailbox: The mailbox to which to add this message.
@type message: Any file-like object
@param message: The message to add, in RFC822 format. Newlines
in this file should be \\r\\n-style.
@type flags: Any iterable of C{str}
@param flags: The flags to associated with this message.
@type date: C{str}
@param date: The date to associate with this message. This should
be of the format DD-MM-YYYY HH:MM:SS +/-HHMM. For example, in
Eastern Standard Time, on July 1st 2004 at half past 1 PM,
\"01-07-2004 13:30:00 -0500\".
@rtype: C{Deferred}
@return: A deferred whose callback is invoked when this command
succeeds or whose errback is invoked if it fails.
"""
message.seek(0, 2)
L = message.tell()
message.seek(0, 0)
fmt = '%s (%s)%s {%d}'
if date:
date = ' "%s"' % date
else:
date = ''
cmd = fmt % (
_prepareMailboxName(mailbox), ' '.join(flags),
date, L
)
d = self.sendCommand(Command('APPEND', cmd, (), self.__cbContinueAppend, message))
return d
def __cbContinueAppend(self, lines, message):
s = basic.FileSender()
return s.beginFileTransfer(message, self.transport, None
).addCallback(self.__cbFinishAppend)
def __cbFinishAppend(self, foo):
self.sendLine('')
def check(self):
"""Tell the server to perform a checkpoint
This command is allowed in the Selected state.
@rtype: C{Deferred}
@return: A deferred whose callback is invoked when this command
succeeds or whose errback is invoked if it fails.
"""
return self.sendCommand(Command('CHECK'))
def close(self):
"""Return the connection to the Authenticated state.
This command is allowed in the Selected state.
Issuing this command will also remove all messages flagged \\Deleted
from the selected mailbox if it is opened in read-write mode,
otherwise it indicates success by no messages are removed.
@rtype: C{Deferred}
@return: A deferred whose callback is invoked when the command
completes successfully or whose errback is invoked if it fails.
"""
return self.sendCommand(Command('CLOSE'))
def expunge(self):
"""Return the connection to the Authenticate state.
This command is allowed in the Selected state.
Issuing this command will perform the same actions as issuing the
close command, but will also generate an 'expunge' response for
every message deleted.
@rtype: C{Deferred}
@return: A deferred whose callback is invoked with a list of the
'expunge' responses when this command is successful or whose errback
is invoked otherwise.
"""
cmd = 'EXPUNGE'
resp = ('EXPUNGE',)
d = self.sendCommand(Command(cmd, wantResponse=resp))
d.addCallback(self.__cbExpunge)
return d
def __cbExpunge(self, (lines, last)):
ids = []
for line in lines:
parts = line.split(None, 1)
if len(parts) == 2:
if parts[1] == 'EXPUNGE':
try:
ids.append(int(parts[0]))
except ValueError:
raise IllegalServerResponse, line
return ids
def search(self, *queries, **kwarg):
"""Search messages in the currently selected mailbox
This command is allowed in the Selected state.
Any non-zero number of queries are accepted by this method, as
returned by the C{Query}, C{Or}, and C{Not} functions.
One keyword argument is accepted: if uid is passed in with a non-zero
value, the server is asked to return message UIDs instead of message
sequence numbers.
@rtype: C{Deferred}
@return: A deferred whose callback will be invoked with a list of all
the message sequence numbers return by the search, or whose errback
will be invoked if there is an error.
"""
if kwarg.get('uid'):
cmd = 'UID SEARCH'
else:
cmd = 'SEARCH'
args = ' '.join(queries)
d = self.sendCommand(Command(cmd, args, wantResponse=(cmd,)))
d.addCallback(self.__cbSearch)
return d
def __cbSearch(self, (lines, end)):
ids = []
for line in lines:
parts = line.split(None, 1)
if len(parts) == 2:
if parts[0] == 'SEARCH':
try:
ids.extend(map(int, parts[1].split()))
except ValueError:
raise IllegalServerResponse, line
return ids
def fetchUID(self, messages, uid=0):
"""Retrieve the unique identifier for one or more messages
This command is allowed in the Selected state.
@type messages: C{MessageSet} or C{str}
@param messages: A message sequence set
@type uid: C{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.
@rtype: C{Deferred}
@return: A deferred whose callback is invoked with a dict mapping
message sequence numbers to unique message identifiers, or whose
errback is invoked if there is an error.
"""
d = self._fetch(messages, useUID=uid, uid=1)
d.addCallback(self.__cbFetch)
return d
def fetchFlags(self, messages, uid=0):
"""Retrieve the flags for one or more messages
This command is allowed in the Selected state.
@type messages: C{MessageSet} or C{str}
@param messages: The messages for which to retrieve flags.
@type uid: C{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.
@rtype: C{Deferred}
@return: A deferred whose callback is invoked with a dict mapping
message numbers to lists of flags, or whose errback is invoked if
there is an error.
"""
d = self._fetch(str(messages), useUID=uid, flags=1)
d.addCallback(self.__cbFetch)
return d
def fetchInternalDate(self, messages, uid=0):
"""Retrieve the internal date associated with one or more messages
This command is allowed in the Selected state.
@type messages: C{MessageSet} or C{str}
@param messages: The messages for which to retrieve the internal date.
@type uid: C{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.
@rtype: C{Deferred}
@return: A deferred whose callback is invoked with a dict mapping
message numbers to date strings, or whose errback is invoked
if there is an error. Date strings take the format of
\"day-month-year time timezone\".
"""
d = self._fetch(str(messages), useUID=uid, internaldate=1)
d.addCallback(self.__cbFetch)
return d
def fetchEnvelope(self, messages, uid=0):
"""Retrieve the envelope data for one or more messages
This command is allowed in the Selected state.
@type messages: C{MessageSet} or C{str}
@param messages: The messages for which to retrieve envelope data.
@type uid: C{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.
@rtype: C{Deferred}
@return: A deferred whose callback is invoked with a dict mapping
message numbers to envelope data, or whose errback is invoked
if there is an error. Envelope data consists of a sequence of the
date, subject, from, sender, reply-to, to, cc, bcc, in-reply-to,
and message-id header fields. The date, subject, in-reply-to, and
message-id fields are strings, while the from, sender, reply-to,
to, cc, and bcc fields contain address data. Address data consists
of a sequence of name, source route, mailbox name, and hostname.
Fields which are not present for a particular address may be C{None}.
"""
d = self._fetch(str(messages), useUID=uid, envelope=1)
d.addCallback(self.__cbFetch)
return d
def fetchBodyStructure(self, messages, uid=0):
"""Retrieve the structure of the body of one or more messages
This command is allowed in the Selected state.
@type messages: C{MessageSet} or C{str}
@param messages: The messages for which to retrieve body structure
data.
@type uid: C{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.
@rtype: C{Deferred}
@return: A deferred whose callback is invoked with a dict mapping
message numbers to body structure data, or whose errback is invoked
if there is an error. Body structure data describes the MIME-IMB
format of a message and consists of a sequence of mime type, mime
subtype, parameters, content id, description, encoding, and size.
The fields following the size field are variable: if the mime
type/subtype is message/rfc822, the contained message's envelope
information, body structure data, and number of lines of text; if
the mime type is text, the number of lines of text. Extension fields
may also be included; if present, they are: the MD5 hash of the body,
body disposition, body language.
"""
d = self._fetch(messages, useUID=uid, bodystructure=1)
d.addCallback(self.__cbFetch)
return d
def fetchSimplifiedBody(self, messages, uid=0):
"""Retrieve the simplified body structure of one or more messages
This command is allowed in the Selected state.
@type messages: C{MessageSet} or C{str}
@param messages: A message sequence set
@type uid: C{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.
@rtype: C{Deferred}
@return: A deferred whose callback is invoked with a dict mapping
message numbers to body data, or whose errback is invoked
if there is an error. The simplified body structure is the same
as the body structure, except that extension fields will never be
present.
"""
d = self._fetch(messages, useUID=uid, body=1)
d.addCallback(self.__cbFetch)
return d
def fetchMessage(self, messages, uid=0):
"""Retrieve one or more entire messages
This command is allowed in the Selected state.
@type messages: C{MessageSet} or C{str}
@param messages: A message sequence set
@type uid: C{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.
@rtype: C{Deferred}
@return: A deferred whose callback is invoked with a dict mapping
message objects (as returned by self.messageFile(), file objects by
default), to additional information, or whose errback is invoked if
there is an error.
"""
d = self._fetch(messages, useUID=uid, rfc822=1)
d.addCallback(self.__cbFetch)
return d
def fetchHeaders(self, messages, uid=0):
"""Retrieve headers of one or more messages
This command is allowed in the Selected state.
@type messages: C{MessageSet} or C{str}
@param messages: A message sequence set
@type uid: C{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.
@rtype: C{Deferred}
@return: A deferred whose callback is invoked with a dict mapping
message numbers to dicts of message headers, or whose errback is
invoked if there is an error.
"""
d = self._fetch(messages, useUID=uid, rfc822header=1)
d.addCallback(self.__cbFetch)
return d
def fetchBody(self, messages, uid=0):
"""Retrieve body text of one or more messages
This command is allowed in the Selected state.
@type messages: C{MessageSet} or C{str}
@param messages: A message sequence set
@type uid: C{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.
@rtype: C{Deferred}
@return: A deferred whose callback is invoked with a dict mapping
message numbers to file-like objects containing body text, or whose
errback is invoked if there is an error.
"""
d = self._fetch(messages, useUID=uid, rfc822text=1)
d.addCallback(self.__cbFetch)
return d
def fetchSize(self, messages, uid=0):
"""Retrieve the size, in octets, of one or more messages
This command is allowed in the Selected state.
@type messages: C{MessageSet} or C{str}
@param messages: A message sequence set
@type uid: C{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.
@rtype: C{Deferred}
@return: A deferred whose callback is invoked with a dict mapping
message numbers to sizes, or whose errback is invoked if there is
an error.
"""
d = self._fetch(messages, useUID=uid, rfc822size=1)
d.addCallback(self.__cbFetch)
return d
def fetchFull(self, messages, uid=0):
"""Retrieve several different fields of one or more messages
This command is allowed in the Selected state. This is equivalent
to issuing all of the C{fetchFlags}, C{fetchInternalDate},
C{fetchSize}, C{fetchEnvelope}, and C{fetchSimplifiedBody}
functions.
@type messages: C{MessageSet} or C{str}
@param messages: A message sequence set
@type uid: C{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.
@rtype: C{Deferred}
@return: A deferred whose callback is invoked with a dict mapping
message numbers to dict of the retrieved data values, or whose
errback is invoked if there is an error. They dictionary keys
are "flags", "date", "size", "envelope", and "body".
"""
d = self._fetch(
messages, useUID=uid, flags=1, internaldate=1,
rfc822size=1, envelope=1, body=1
)
d.addCallback(self.__cbFetch)
return d
def fetchAll(self, messages, uid=0):
"""Retrieve several different fields of one or more messages
This command is allowed in the Selected state. This is equivalent
to issuing all of the C{fetchFlags}, C{fetchInternalDate},
C{fetchSize}, and C{fetchEnvelope} functions.
@type messages: C{MessageSet} or C{str}
@param messages: A message sequence set
@type uid: C{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.
@rtype: C{Deferred}
@return: A deferred whose callback is invoked with a dict mapping
message numbers to dict of the retrieved data values, or whose
errback is invoked if there is an error. They dictionary keys
are "flags", "date", "size", and "envelope".
"""
d = self._fetch(
messages, useUID=uid, flags=1, internaldate=1,
rfc822size=1, envelope=1
)
d.addCallback(self.__cbFetch)
return d
def fetchFast(self, messages, uid=0):
"""Retrieve several different fields of one or more messages
This command is allowed in the Selected state. This is equivalent
to issuing all of the C{fetchFlags}, C{fetchInternalDate}, and
C{fetchSize} functions.
@type messages: C{MessageSet} or C{str}
@param messages: A message sequence set
@type uid: C{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.
@rtype: C{Deferred}
@return: A deferred whose callback is invoked with a dict mapping
message numbers to dict of the retrieved data values, or whose
errback is invoked if there is an error. They dictionary keys are
"flags", "date", and "size".
"""
d = self._fetch(
messages, useUID=uid, flags=1, internaldate=1, rfc822size=1
)
d.addCallback(self.__cbFetch)
return d
def __cbFetch(self, (lines, last)):
flags = {}
for line in lines:
parts = line.split(None, 2)
if len(parts) == 3:
if parts[1] == 'FETCH':
try:
id = int(parts[0])
except ValueError:
raise IllegalServerResponse, line
else:
data = parseNestedParens(parts[2])
while len(data) == 1 and isinstance(data, types.ListType):
data = data[0]
while data:
if len(data) < 2:
raise IllegalServerResponse("Not enough arguments", data)
flags.setdefault(id, {})[data[0]] = data[1]
del data[:2]
else:
print '(2)Ignoring ', parts
else:
print '(3)Ignoring ', parts
return flags
def fetchSpecific(self, messages, uid=0, headerType=None,
headerNumber=None, headerArgs=None, peek=None,
offset=None, length=None):
"""Retrieve a specific section of one or more messages
@type messages: C{MessageSet} or C{str}
@param messages: A message sequence set
@type uid: C{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.
@type headerType: C{str}
@param headerType: If specified, must be one of HEADER,
HEADER.FIELDS, HEADER.FIELDS.NOT, MIME, or TEXT, and will determine
which part of the message is retrieved. For HEADER.FIELDS and
HEADER.FIELDS.NOT, C{headerArgs} must be a sequence of header names.
For MIME, C{headerNumber} must be specified.
@type headerNumber: C{int} or C{int} sequence
@param headerNumber: The nested rfc822 index specifying the
entity to retrieve. For example, C{1} retrieves the first
entity of the message, and C{(2, 1, 3}) retrieves the 3rd
entity inside the first entity inside the second entity of
the message.
@type headerArgs: A sequence of C{str}
@param headerArgs: If C{headerType} is HEADER.FIELDS, these are the
headers to retrieve. If it is HEADER.FIELDS.NOT, these are the
headers to exclude from retrieval.
@type peek: C{bool}
@param peek: If true, cause the server to not set the \\Seen
flag on this message as a result of this command.
@type offset: C{int}
@param offset: The number of octets at the beginning of the result
to skip.
@type length: C{int}
@param length: The number of octets to retrieve.
@rtype: C{Deferred}
@return: A deferred whose callback is invoked with a mapping of
message numbers to retrieved data, or whose errback is invoked
if there is an error.
"""
fmt = '%s BODY%s[%s%s%s]%s'
if headerNumber is None:
number = ''
elif isinstance(headerNumber, types.IntType):
number = str(headerNumber)
else:
number = '.'.join(headerNumber)
if headerType is None:
header = ''
elif number:
header = '.' + headerType
else:
header = headerType
if header:
if headerArgs is not None:
payload = ' (%s)' % ' '.join(headerArgs)
else:
payload = ' ()'
else:
payload = ''
if offset is None:
extra = ''
else:
extra = '<%d.%d>' % (offset, length)
fetch = uid and 'UID FETCH' or 'FETCH'
cmd = fmt % (messages, peek and '.PEEK' or '', number, header, payload, extra)
d = self.sendCommand(Command(fetch, cmd, wantResponse=('FETCH',)))
d.addCallback(self.__cbFetchSpecific)
return d
def __cbFetchSpecific(self, (lines, last)):
info = {}
for line in lines:
parts = line.split(None, 2)
if len(parts) == 3:
if parts[1] == 'FETCH':
try:
id = int(parts[0])
except ValueError:
raise IllegalServerResponse, line
else:
info[id] = parseNestedParens(parts[2])
return info
def _fetch(self, messages, useUID=0, **terms):
fetch = useUID and 'UID FETCH' or 'FETCH'
if 'rfc822text' in terms:
del terms['rfc822text']
terms['rfc822.text'] = True
if 'rfc822size' in terms:
del terms['rfc822size']
terms['rfc822.size'] = True
if 'rfc822header' in terms:
del terms['rfc822header']
terms['rfc822.header'] = True
cmd = '%s (%s)' % (messages, ' '.join([s.upper() for s in terms.keys()]))
d = self.sendCommand(Command(fetch, cmd, wantResponse=('FETCH',)))
return d
def setFlags(self, messages, flags, silent=1, uid=0):
"""Set the flags for one or more messages.
This command is allowed in the Selected state.
@type messages: C{MessageSet} or C{str}
@param messages: A message sequence set
@type flags: Any iterable of C{str}
@param flags: The flags to set
@type silent: C{bool}
@param silent: If true, cause the server to supress its verbose
response.
@type uid: C{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.
@rtype: C{Deferred}
@return: A deferred whose callback is invoked with a list of the
the server's responses (C{[]} if C{silent} is true) or whose
errback is invoked if there is an error.
"""
return self._store(str(messages), silent and 'FLAGS.SILENT' or 'FLAGS', flags, uid)
def addFlags(self, messages, flags, silent=1, uid=0):
"""Add to the set flags for one or more messages.
This command is allowed in the Selected state.
@type messages: C{MessageSet} or C{str}
@param messages: A message sequence set
@type flags: Any iterable of C{str}
@param flags: The flags to set
@type silent: C{bool}
@param silent: If true, cause the server to supress its verbose
response.
@type uid: C{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.
@rtype: C{Deferred}
@return: A deferred whose callback is invoked with a list of the
the server's responses (C{[]} if C{silent} is true) or whose
errback is invoked if there is an error.
"""
return self._store(str(messages), silent and '+FLAGS.SILENT' or '+FLAGS', flags, uid)
def removeFlags(self, messages, flags, silent=1, uid=0):
"""Remove from the set flags for one or more messages.
This command is allowed in the Selected state.
@type messages: C{MessageSet} or C{str}
@param messages: A message sequence set
@type flags: Any iterable of C{str}
@param flags: The flags to set
@type silent: C{bool}
@param silent: If true, cause the server to supress its verbose
response.
@type uid: C{bool}
@param uid: Indicates whether the message sequence set is of message
numbers or of unique message IDs.
@rtype: C{Deferred}
@return: A deferred whose callback is invoked with a list of the
the server's responses (C{[]} if C{silent} is true) or whose
errback is invoked if there is an error.
"""
return self._store(str(messages), silent and '-FLAGS.SILENT' or '-FLAGS', flags, uid)
def _store(self, messages, cmd, flags, uid):
store = uid and 'UID STORE' or 'STORE'
args = ' '.join((messages, cmd, '(%s)' % ' '.join(flags)))
d = self.sendCommand(Command(store, args, wantResponse=('FETCH',)))
d.addCallback(self.__cbFetch)
return d
def copy(self, messages, mailbox, uid):
"""Copy the specified messages to the specified mailbox.
This command is allowed in the Selected state.
@type messages: C{str}
@param messages: A message sequence set
@type mailbox: C{str}
@param mailbox: The mailbox to which to copy the messages
@type uid: C{bool}
@param uid: If true, the C{messages} refers to message UIDs, rather
than message sequence numbers.
@rtype: C{Deferred}
@return: A deferred whose callback is invoked with a true value
when the copy is successful, or whose errback is invoked if there
is an error.
"""
if uid:
cmd = 'UID COPY'
else:
cmd = 'COPY'
args = '%s %s' % (messages, _prepareMailboxName(mailbox))
return self.sendCommand(Command(cmd, args))
#
# IMailboxListener methods
#
def modeChanged(self, writeable):
"""Override me"""
def flagsChanged(self, newFlags):
"""Override me"""
def newMessages(self, exists, recent):
"""Override me"""
class IllegalIdentifierError(IMAP4Exception): pass
def parseIdList(s):
res = MessageSet()
parts = s.split(',')
for p in parts:
if ':' in p:
low, high = p.split(':', 1)
try:
if low == '*':
low = None
else:
low = long(low)
if high == '*':
high = None
else:
high = long(high)
res.extend((low, high))
except ValueError:
raise IllegalIdentifierError(p)
else:
try:
if p == '*':
p = None
else:
p = long(p)
except ValueError:
raise IllegalIdentifierError(p)
else:
res.extend(p)
return res
class IllegalQueryError(IMAP4Exception): pass
_SIMPLE_BOOL = (
'ALL', 'ANSWERED', 'DELETED', 'DRAFT', 'FLAGGED', 'NEW', 'OLD', 'RECENT',
'SEEN', 'UNANSWERED', 'UNDELETED', 'UNDRAFT', 'UNFLAGGED', 'UNSEEN'
)
_NO_QUOTES = (
'LARGER', 'SMALLER', 'UID'
)
def Query(sorted=0, **kwarg):
"""Create a query string
Among the accepted keywords are::
all : If set to a true value, search all messages in the
current mailbox
answered : If set to a true value, search messages flagged with
\\Answered
bcc : A substring to search the BCC header field for
before : Search messages with an internal date before this
value. The given date should be a string in the format
of 'DD-Mon-YYYY'. For example, '03-Mar-2003'.
body : A substring to search the body of the messages for
cc : A substring to search the CC header field for
deleted : If set to a true value, search messages flagged with
\\Deleted
draft : If set to a true value, search messages flagged with
\\Draft
flagged : If set to a true value, search messages flagged with
\\Flagged
from : A substring to search the From header field for
header : A two-tuple of a header name and substring to search
for in that header
keyword : Search for messages with the given keyword set
larger : Search for messages larger than this number of octets
messages : Search only the given message sequence set.
new : If set to a true value, search messages flagged with
\\Recent but not \\Seen
old : If set to a true value, search messages not flagged with
\\Recent
on : Search messages with an internal date which is on this
date. The given date should be a string in the format
of 'DD-Mon-YYYY'. For example, '03-Mar-2003'.
recent : If set to a true value, search for messages flagged with
\\Recent
seen : If set to a true value, search for messages flagged with
\\Seen
sentbefore : Search for messages with an RFC822 'Date' header before
this date. The given date should be a string in the format
of 'DD-Mon-YYYY'. For example, '03-Mar-2003'.
senton : Search for messages with an RFC822 'Date' header which is
on this date The given date should be a string in the format
of 'DD-Mon-YYYY'. For example, '03-Mar-2003'.
sentsince : Search for messages with an RFC822 'Date' header which is
after this date. The given date should be a string in the format
of 'DD-Mon-YYYY'. For example, '03-Mar-2003'.
since : Search for messages with an internal date that is after
this date.. The given date should be a string in the format
of 'DD-Mon-YYYY'. For example, '03-Mar-2003'.
smaller : Search for messages smaller than this number of octets
subject : A substring to search the 'subject' header for
text : A substring to search the entire message for
to : A substring to search the 'to' header for
uid : Search only the messages in the given message set
unanswered : If set to a true value, search for messages not
flagged with \\Answered
undeleted : If set to a true value, search for messages not
flagged with \\Deleted
undraft : If set to a true value, search for messages not
flagged with \\Draft
unflagged : If set to a true value, search for messages not
flagged with \\Flagged
unkeyword : Search for messages without the given keyword set
unseen : If set to a true value, search for messages not
flagged with \\Seen
@type sorted: C{bool}
@param sorted: If true, the output will be sorted, alphabetically.
The standard does not require it, but it makes testing this function
easier. The default is zero, and this should be acceptable for any
application.
@rtype: C{str}
@return: The formatted query string
"""
cmd = []
keys = kwarg.keys()
if sorted:
keys.sort()
for k in keys:
v = kwarg[k]
k = k.upper()
if k in _SIMPLE_BOOL and v:
cmd.append(k)
elif k == 'HEADER':
cmd.extend([k, v[0], '"%s"' % (v[1],)])
elif k not in _NO_QUOTES:
cmd.extend([k, '"%s"' % (v,)])
else:
cmd.extend([k, '%s' % (v,)])
if len(cmd) > 1:
return '(%s)' % ' '.join(cmd)
else:
return ' '.join(cmd)
def Or(*args):
"""The disjunction of two or more queries"""
if len(args) < 2:
raise IllegalQueryError, args
elif len(args) == 2:
return '(OR %s %s)' % args
else:
return '(OR %s %s)' % (args[0], Or(*args[1:]))
def Not(query):
"""The negation of a query"""
return '(NOT %s)' % (query,)
class MismatchedNesting(IMAP4Exception):
pass
class MismatchedQuoting(IMAP4Exception):
pass
def wildcardToRegexp(wildcard, delim=None):
wildcard = wildcard.replace('*', '(?:.*?)')
if delim is None:
wildcard = wildcard.replace('%', '(?:.*?)')
else:
wildcard = wildcard.replace('%', '(?:(?:[^%s])*?)' % re.escape(delim))
return re.compile(wildcard, re.I)
def splitQuoted(s):
"""Split a string into whitespace delimited tokens
Tokens that would otherwise be separated but are surrounded by \"
remain as a single token. Any token that is not quoted and is
equal to \"NIL\" is tokenized as C{None}.
@type s: C{str}
@param s: The string to be split
@rtype: C{list} of C{str}
@return: A list of the resulting tokens
@raise MismatchedQuoting: Raised if an odd number of quotes are present
"""
s = s.strip()
result = []
inQuote = inWord = start = 0
for (i, c) in zip(range(len(s)), s):
if c == '"' and not inQuote:
inQuote = 1
start = i + 1
elif c == '"' and inQuote:
inQuote = 0
result.append(s[start:i])
start = i + 1
elif not inWord and not inQuote and c not in ('"' + string.whitespace):
inWord = 1
start = i
elif inWord and not inQuote and c in string.whitespace:
if s[start:i] == 'NIL':
result.append(None)
else:
result.append(s[start:i])
start = i
inWord = 0
if inQuote:
raise MismatchedQuoting(s)
if inWord:
if s[start:] == 'NIL':
result.append(None)
else:
result.append(s[start:])
return result
def splitOn(sequence, predicate, transformers):
result = []
mode = predicate(sequence[0])
tmp = [sequence[0]]
for e in sequence[1:]:
p = predicate(e)
if p != mode:
result.extend(transformers[mode](tmp))
tmp = [e]
mode = p
else:
tmp.append(e)
result.extend(transformers[mode](tmp))
return result
def collapseStrings(results):
"""
Turns a list of length-one strings and lists into a list of longer
strings and lists. For example,
['a', 'b', ['c', 'd']] is returned as ['ab', ['cd']]
@type results: C{list} of C{str} and C{list}
@param results: The list to be collapsed
@rtype: C{list} of C{str} and C{list}
@return: A new list which is the collapsed form of C{results}
"""
copy = []
begun = None
listsList = [isinstance(s, types.ListType) for s in results]
pred = lambda e: isinstance(e, types.TupleType)
tran = {
0: lambda e: splitQuoted(''.join(e)),
1: lambda e: [''.join([i[0] for i in e])]
}
for (i, c, isList) in zip(range(len(results)), results, listsList):
if isList:
if begun is not None:
copy.extend(splitOn(results[begun:i], pred, tran))
begun = None
copy.append(collapseStrings(c))
elif begun is None:
begun = i
if begun is not None:
copy.extend(splitOn(results[begun:], pred, tran))
return copy
def parseNestedParens(s, handleLiteral = 1):
"""Parse an s-exp-like string into a more useful data structure.
@type s: C{str}
@param s: The s-exp-like string to parse
@rtype: C{list} of C{str} and C{list}
@return: A list containing the tokens present in the input.
@raise MismatchedNesting: Raised if the number or placement
of opening or closing parenthesis is invalid.
"""
s = s.strip()
inQuote = 0
contentStack = [[]]
try:
i = 0
L = len(s)
while i < L:
c = s[i]
if inQuote:
if c == '\\':
contentStack[-1].append(s[i+1])
i += 2
continue
elif c == '"':
inQuote = not inQuote
contentStack[-1].append(c)
i += 1
else:
if c == '"':
contentStack[-1].append(c)
inQuote = not inQuote
i += 1
elif handleLiteral and c == '{':
end = s.find('}', i)
if end == -1:
raise ValueError, "Malformed literal"
literalSize = int(s[i+1:end])
contentStack[-1].append((s[end+3:end+3+literalSize],))
i = end + 3 + literalSize
elif c == '(' or c == '[':
contentStack.append([])
i += 1
elif c == ')' or c == ']':
contentStack[-2].append(contentStack.pop())
i += 1
else:
contentStack[-1].append(c)
i += 1
except IndexError:
raise MismatchedNesting(s)
if len(contentStack) != 1:
raise MismatchedNesting(s)
return collapseStrings(contentStack[0])
def _quote(s):
return '"%s"' % (s.replace('\\', '\\\\').replace('"', '\\"'),)
def _literal(s):
return '{%d}\r\n%s' % (len(s), s)
class DontQuoteMe:
def __init__(self, value):
self.value = value
def __str__(self):
return str(self.value)
_ATOM_SPECIALS = '(){ %*"'
def _needsQuote(s):
if s == '':
return 1
for c in s:
if c < '\x20' or c > '\x7f':
return 1
if c in _ATOM_SPECIALS:
return 1
return 0
def _prepareMailboxName(name):
name = name.encode('imap4-utf-7')
if _needsQuote(name):
return _quote(name)
return name
def _needsLiteral(s):
# Change this to "return 1" to wig out stupid clients
return '\n' in s or '\r' in s or len(s) > 1000
def collapseNestedLists(items):
"""Turn a nested list structure into an s-exp-like string.
Strings in C{items} will be sent as literals if they contain CR or LF,
otherwise they will be quoted. References to None in C{items} will be
translated to the atom NIL. Objects with a 'read' attribute will have
it called on them with no arguments and the returned string will be
inserted into the output as a literal. Integers will be converted to
strings and inserted into the output unquoted. Instances of
C{DontQuoteMe} will be converted to strings and inserted into the output
unquoted.
This function used to be much nicer, and only quote things that really
needed to be quoted (and C{DontQuoteMe} did not exist), however, many
broken IMAP4 clients were unable to deal with this level of sophistication,
forcing the current behavior to be adopted for practical reasons.
@type items: Any iterable
@rtype: C{str}
"""
pieces = []
for i in items:
if i is None:
pieces.extend([' ', 'NIL'])
elif isinstance(i, (DontQuoteMe, int, long)):
pieces.extend([' ', str(i)])
elif isinstance(i, types.StringTypes):
if _needsLiteral(i):
pieces.extend([' ', '{', str(len(i)), '}', IMAP4Server.delimiter, i])
else:
pieces.extend([' ', _quote(i)])
elif hasattr(i, 'read'):
d = i.read()
pieces.extend([' ', '{', str(len(d)), '}', IMAP4Server.delimiter, d])
else:
pieces.extend([' ', '(%s)' % (collapseNestedLists(i),)])
return ''.join(pieces[1:])
class IClientAuthentication(Interface):
def getName():
"""Return an identifier associated with this authentication scheme.
@rtype: C{str}
"""
def challengeResponse(secret, challenge):
"""Generate a challenge response string"""
class CramMD5ClientAuthenticator:
implements(IClientAuthentication)
def __init__(self, user):
self.user = user
def getName(self):
return "CRAM-MD5"
def challengeResponse(self, secret, chal):
response = hmac.HMAC(secret, chal).hexdigest()
return '%s %s' % (self.user, response)
class LOGINAuthenticator:
implements(IClientAuthentication)
def __init__(self, user):
self.user = user
self.challengeResponse = self.challengeUsername
def getName(self):
return "LOGIN"
def challengeUsername(self, secret, chal):
# Respond to something like "Username:"
self.challengeResponse = self.challengeSecret
return self.user
def challengeSecret(self, secret, chal):
# Respond to something like "Password:"
return secret
class PLAINAuthenticator:
implements(IClientAuthentication)
def __init__(self, user):
self.user = user
def getName(self):
return "PLAIN"
def challengeResponse(self, secret, chal):
return '%s\0%s\0' % (self.user, secret)
class MailboxException(IMAP4Exception): pass
class MailboxCollision(MailboxException):
def __str__(self):
return 'Mailbox named %s already exists' % self.args
class NoSuchMailbox(MailboxException):
def __str__(self):
return 'No mailbox named %s exists' % self.args
class ReadOnlyMailbox(MailboxException):
def __str__(self):
return 'Mailbox open in read-only state'
class IAccount(Interface):
"""Interface for Account classes
Implementors of this interface should consider implementing
C{INamespacePresenter}.
"""
def addMailbox(name, mbox = None):
"""Add a new mailbox to this account
@type name: C{str}
@param name: The name associated with this mailbox. It may not
contain multiple hierarchical parts.
@type mbox: An object implementing C{IMailbox}
@param mbox: The mailbox to associate with this name. If C{None},
a suitable default is created and used.
@rtype: C{Deferred} or C{bool}
@return: A true value if the creation succeeds, or a deferred whose
callback will be invoked when the creation succeeds.
@raise MailboxException: Raised if this mailbox cannot be added for
some reason. This may also be raised asynchronously, if a C{Deferred}
is returned.
"""
def create(pathspec):
"""Create a new mailbox from the given hierarchical name.
@type pathspec: C{str}
@param pathspec: The full hierarchical name of a new mailbox to create.
If any of the inferior hierarchical names to this one do not exist,
they are created as well.
@rtype: C{Deferred} or C{bool}
@return: A true value if the creation succeeds, or a deferred whose
callback will be invoked when the creation succeeds.
@raise MailboxException: Raised if this mailbox cannot be added.
This may also be raised asynchronously, if a C{Deferred} is
returned.
"""
def select(name, rw=True):
"""Acquire a mailbox, given its name.
@type name: C{str}
@param name: The mailbox to acquire
@type rw: C{bool}
@param rw: If a true value, request a read-write version of this
mailbox. If a false value, request a read-only version.
@rtype: Any object implementing C{IMailbox} or C{Deferred}
@return: The mailbox object, or a C{Deferred} whose callback will
be invoked with the mailbox object. None may be returned if the
specified mailbox may not be selected for any reason.
"""
def delete(name):
"""Delete the mailbox with the specified name.
@type name: C{str}
@param name: The mailbox to delete.
@rtype: C{Deferred} or C{bool}
@return: A true value if the mailbox is successfully deleted, or a
C{Deferred} whose callback will be invoked when the deletion
completes.
@raise MailboxException: Raised if this mailbox cannot be deleted.
This may also be raised asynchronously, if a C{Deferred} is returned.
"""
def rename(oldname, newname):
"""Rename a mailbox
@type oldname: C{str}
@param oldname: The current name of the mailbox to rename.
@type newname: C{str}
@param newname: The new name to associate with the mailbox.
@rtype: C{Deferred} or C{bool}
@return: A true value if the mailbox is successfully renamed, or a
C{Deferred} whose callback will be invoked when the rename operation
is completed.
@raise MailboxException: Raised if this mailbox cannot be
renamed. This may also be raised asynchronously, if a C{Deferred}
is returned.
"""
def isSubscribed(name):
"""Check the subscription status of a mailbox
@type name: C{str}
@param name: The name of the mailbox to check
@rtype: C{Deferred} or C{bool}
@return: A true value if the given mailbox is currently subscribed
to, a false value otherwise. A C{Deferred} may also be returned
whose callback will be invoked with one of these values.
"""
def subscribe(name):
"""Subscribe to a mailbox
@type name: C{str}
@param name: The name of the mailbox to subscribe to
@rtype: C{Deferred} or C{bool}
@return: A true value if the mailbox is subscribed to successfully,
or a Deferred whose callback will be invoked with this value when
the subscription is successful.
@raise MailboxException: Raised if this mailbox cannot be
subscribed to. This may also be raised asynchronously, if a
C{Deferred} is returned.
"""
def unsubscribe(name):
"""Unsubscribe from a mailbox
@type name: C{str}
@param name: The name of the mailbox to unsubscribe from
@rtype: C{Deferred} or C{bool}
@return: A true value if the mailbox is unsubscribed from successfully,
or a Deferred whose callback will be invoked with this value when
the unsubscription is successful.
@raise MailboxException: Raised if this mailbox cannot be
unsubscribed from. This may also be raised asynchronously, if a
C{Deferred} is returned.
"""
def listMailboxes(ref, wildcard):
"""List all the mailboxes that meet a certain criteria
@type ref: C{str}
@param ref: The context in which to apply the wildcard
@type wildcard: C{str}
@param wildcard: An expression against which to match mailbox names.
'*' matches any number of characters in a mailbox name, and '%'
matches similarly, but will not match across hierarchical boundaries.
@rtype: C{list} of C{tuple}
@return: A list of C{(mailboxName, mailboxObject)} which meet the
given criteria. C{mailboxObject} should implement either
C{IMailboxInfo} or C{IMailbox}. A Deferred may also be returned.
"""
class INamespacePresenter(Interface):
def getPersonalNamespaces():
"""Report the available personal namespaces.
Typically there should be only one personal namespace. A common
name for it is \"\", and its hierarchical delimiter is usually
\"/\".
@rtype: iterable of two-tuples of strings
@return: The personal namespaces and their hierarchical delimiters.
If no namespaces of this type exist, None should be returned.
"""
def getSharedNamespaces():
"""Report the available shared namespaces.
Shared namespaces do not belong to any individual user but are
usually to one or more of them. Examples of shared namespaces
might be \"#news\" for a usenet gateway.
@rtype: iterable of two-tuples of strings
@return: The shared namespaces and their hierarchical delimiters.
If no namespaces of this type exist, None should be returned.
"""
def getUserNamespaces():
"""Report the available user namespaces.
These are namespaces that contain folders belonging to other users
access to which this account has been granted.
@rtype: iterable of two-tuples of strings
@return: The user namespaces and their hierarchical delimiters.
If no namespaces of this type exist, None should be returned.
"""
class MemoryAccount(object):
implements(IAccount, INamespacePresenter)
mailboxes = None
subscriptions = None
top_id = 0
def __init__(self, name):
self.name = name
self.mailboxes = {}
self.subscriptions = []
def allocateID(self):
id = self.top_id
self.top_id += 1
return id
##
## IAccount
##
def addMailbox(self, name, mbox = None):
name = name.upper()
if self.mailboxes.has_key(name):
raise MailboxCollision, name
if mbox is None:
mbox = self._emptyMailbox(name, self.allocateID())
self.mailboxes[name] = mbox
return 1
def create(self, pathspec):
paths = filter(None, pathspec.split('/'))
for accum in range(1, len(paths)):
try:
self.addMailbox('/'.join(paths[:accum]))
except MailboxCollision:
pass
try:
self.addMailbox('/'.join(paths))
except MailboxCollision:
if not pathspec.endswith('/'):
return False
return True
def _emptyMailbox(self, name, id):
raise NotImplementedError
def select(self, name, readwrite=1):
return self.mailboxes.get(name.upper())
def delete(self, name):
name = name.upper()
# See if this mailbox exists at all
mbox = self.mailboxes.get(name)
if not mbox:
raise MailboxException("No such mailbox")
# See if this box is flagged \Noselect
if r'\Noselect' in mbox.getFlags():
# Check for hierarchically inferior mailboxes with this one
# as part of their root.
for others in self.mailboxes.keys():
if others != name and others.startswith(name):
raise MailboxException, "Hierarchically inferior mailboxes exist and \\Noselect is set"
mbox.destroy()
# iff there are no hierarchically inferior names, we will
# delete it from our ken.
if self._inferiorNames(name) > 1:
del self.mailboxes[name]
def rename(self, oldname, newname):
oldname = oldname.upper()
newname = newname.upper()
if not self.mailboxes.has_key(oldname):
raise NoSuchMailbox, oldname
inferiors = self._inferiorNames(oldname)
inferiors = [(o, o.replace(oldname, newname, 1)) for o in inferiors]
for (old, new) in inferiors:
if self.mailboxes.has_key(new):
raise MailboxCollision, new
for (old, new) in inferiors:
self.mailboxes[new] = self.mailboxes[old]
del self.mailboxes[old]
def _inferiorNames(self, name):
inferiors = []
for infname in self.mailboxes.keys():
if infname.startswith(name):
inferiors.append(infname)
return inferiors
def isSubscribed(self, name):
return name.upper() in self.subscriptions
def subscribe(self, name):
name = name.upper()
if name not in self.subscriptions:
self.subscriptions.append(name)
def unsubscribe(self, name):
name = name.upper()
if name not in self.subscriptions:
raise MailboxException, "Not currently subscribed to " + name
self.subscriptions.remove(name)
def listMailboxes(self, ref, wildcard):
ref = self._inferiorNames(ref.upper())
wildcard = wildcardToRegexp(wildcard, '/')
return [(i, self.mailboxes[i]) for i in ref if wildcard.match(i)]
##
## INamespacePresenter
##
def getPersonalNamespaces(self):
return [["", "/"]]
def getSharedNamespaces(self):
return None
def getOtherNamespaces(self):
return None
_statusRequestDict = {
'MESSAGES': 'getMessageCount',
'RECENT': 'getRecentCount',
'UIDNEXT': 'getUIDNext',
'UIDVALIDITY': 'getUIDValidity',
'UNSEEN': 'getUnseenCount'
}
def statusRequestHelper(mbox, names):
r = {}
for n in names:
r[n] = getattr(mbox, _statusRequestDict[n.upper()])()
return r
def parseAddr(addr):
if addr is None:
return [(None, None, None),]
addrs = email.Utils.getaddresses([addr])
return [[fn or None, None] + addr.split('@') for fn, addr in addrs]
def getEnvelope(msg):
headers = msg.getHeaders(True)
date = headers.get('date')
subject = headers.get('subject')
from_ = headers.get('from')
sender = headers.get('sender', from_)
reply_to = headers.get('reply-to', from_)
to = headers.get('to')
cc = headers.get('cc')
bcc = headers.get('bcc')
in_reply_to = headers.get('in-reply-to')
mid = headers.get('message-id')
return (date, subject, parseAddr(from_), parseAddr(sender),
reply_to and parseAddr(reply_to), to and parseAddr(to),
cc and parseAddr(cc), bcc and parseAddr(bcc), in_reply_to, mid)
def getLineCount(msg):
# XXX - Super expensive, CACHE THIS VALUE FOR LATER RE-USE
# XXX - This must be the number of lines in the ENCODED version
lines = 0
for _ in msg.getBodyFile():
lines += 1
return lines
def unquote(s):
if s[0] == s[-1] == '"':
return s[1:-1]
return s
def getBodyStructure(msg, extended=False):
# XXX - This does not properly handle multipart messages
# BODYSTRUCTURE is obscenely complex and criminally under-documented.
attrs = {}
headers = 'content-type', 'content-id', 'content-description', 'content-transfer-encoding'
headers = msg.getHeaders(False, *headers)
mm = headers.get('content-type')
if mm:
mm = ''.join(mm.splitlines())
mimetype = mm.split(';')
if mimetype:
type = mimetype[0].split('/', 1)
if len(type) == 1:
major = type[0]
minor = None
elif len(type) == 2:
major, minor = type
else:
major = minor = None
attrs = dict([x.strip().lower().split('=', 1) for x in mimetype[1:]])
else:
major = minor = None
else:
major = minor = None
size = str(msg.getSize())
unquotedAttrs = [(k, unquote(v)) for (k, v) in attrs.iteritems()]
result = [
major, minor, # Main and Sub MIME types
unquotedAttrs, # content-type parameter list
headers.get('content-id'),
headers.get('content-description'),
headers.get('content-transfer-encoding'),
size, # Number of octets total
]
if major is not None:
if major.lower() == 'text':
result.append(str(getLineCount(msg)))
elif (major.lower(), minor.lower()) == ('message', 'rfc822'):
contained = msg.getSubPart(0)
result.append(getEnvelope(contained))
result.append(getBodyStructure(contained, False))
result.append(str(getLineCount(contained)))
if not extended or major is None:
return result
if major.lower() != 'multipart':
headers = 'content-md5', 'content-disposition', 'content-language'
headers = msg.getHeaders(False, *headers)
disp = headers.get('content-disposition')
# XXX - I dunno if this is really right
if disp:
disp = disp.split('; ')
if len(disp) == 1:
disp = (disp[0].lower(), None)
elif len(disp) > 1:
disp = (disp[0].lower(), [x.split('=') for x in disp[1:]])
result.append(headers.get('content-md5'))
result.append(disp)
result.append(headers.get('content-language'))
else:
result = [result]
try:
i = 0
while True:
submsg = msg.getSubPart(i)
result.append(getBodyStructure(submsg))
i += 1
except IndexError:
result.append(minor)
result.append(attrs.items())
# XXX - I dunno if this is really right
headers = msg.getHeaders(False, 'content-disposition', 'content-language')
disp = headers.get('content-disposition')
if disp:
disp = disp.split('; ')
if len(disp) == 1:
disp = (disp[0].lower(), None)
elif len(disp) > 1:
disp = (disp[0].lower(), [x.split('=') for x in disp[1:]])
result.append(disp)
result.append(headers.get('content-language'))
return result
class IMessagePart(Interface):
def getHeaders(negate, *names):
"""Retrieve a group of message headers.
@type names: C{tuple} of C{str}
@param names: The names of the headers to retrieve or omit.
@type negate: C{bool}
@param negate: If True, indicates that the headers listed in C{names}
should be omitted from the return value, rather than included.
@rtype: C{dict}
@return: A mapping of header field names to header field values
"""
def getBodyFile():
"""Retrieve a file object containing only the body of this message.
"""
def getSize():
"""Retrieve the total size, in octets, of this message.
@rtype: C{int}
"""
def isMultipart():
"""Indicate whether this message has subparts.
@rtype: C{bool}
"""
def getSubPart(part):
"""Retrieve a MIME sub-message
@type part: C{int}
@param part: The number of the part to retrieve, indexed from 0.
@raise IndexError: Raised if the specified part does not exist.
@raise TypeError: Raised if this message is not multipart.
@rtype: Any object implementing C{IMessagePart}.
@return: The specified sub-part.
"""
class IMessage(IMessagePart):
def getUID():
"""Retrieve the unique identifier associated with this message.
"""
def getFlags():
"""Retrieve the flags associated with this message.
@rtype: C{iterable}
@return: The flags, represented as strings.
"""
def getInternalDate():
"""Retrieve the date internally associated with this message.
@rtype: C{str}
@return: An RFC822-formatted date string.
"""
class IMessageFile(Interface):
"""Optional message interface for representing messages as files.
If provided by message objects, this interface will be used instead
the more complex MIME-based interface.
"""
def open():
"""Return an file-like object opened for reading.
Reading from the returned file will return all the bytes
of which this message consists.
"""
class ISearchableMailbox(Interface):
def search(query, uid):
"""Search for messages that meet the given query criteria.
If this interface is not implemented by the mailbox, L{IMailbox.fetch}
and various methods of L{IMessage} will be used instead.
Implementations which wish to offer better performance than the
default implementation should implement this interface.
@type query: C{list}
@param query: The search criteria
@type uid: C{bool}
@param uid: If true, the IDs specified in the query are UIDs;
otherwise they are message sequence IDs.
@rtype: C{list} or C{Deferred}
@return: A list of message sequence numbers or message UIDs which
match the search criteria or a C{Deferred} whose callback will be
invoked with such a list.
"""
class IMessageCopier(Interface):
def copy(messageObject):
"""Copy the given message object into this mailbox.
The message object will be one which was previously returned by
L{IMailbox.fetch}.
Implementations which wish to offer better performance than the
default implementation should implement this interface.
If this interface is not implemented by the mailbox, IMailbox.addMessage
will be used instead.
@rtype: C{Deferred} or C{int}
@return: Either the UID of the message or a Deferred which fires
with the UID when the copy finishes.
"""
class IMailboxInfo(Interface):
"""Interface specifying only the methods required for C{listMailboxes}.
Implementations can return objects implementing only these methods for
return to C{listMailboxes} if it can allow them to operate more
efficiently.
"""
def getFlags():
"""Return the flags defined in this mailbox
Flags with the \\ prefix are reserved for use as system flags.
@rtype: C{list} of C{str}
@return: A list of the flags that can be set on messages in this mailbox.
"""
def getHierarchicalDelimiter():
"""Get the character which delimits namespaces for in this mailbox.
@rtype: C{str}
"""
class IMailbox(IMailboxInfo):
def getUIDValidity():
"""Return the unique validity identifier for this mailbox.
@rtype: C{int}
"""
def getUIDNext():
"""Return the likely UID for the next message added to this mailbox.
@rtype: C{int}
"""
def getUID(message):
"""Return the UID of a message in the mailbox
@type message: C{int}
@param message: The message sequence number
@rtype: C{int}
@return: The UID of the message.
"""
def getMessageCount():
"""Return the number of messages in this mailbox.
@rtype: C{int}
"""
def getRecentCount():
"""Return the number of messages with the 'Recent' flag.
@rtype: C{int}
"""
def getUnseenCount():
"""Return the number of messages with the 'Unseen' flag.
@rtype: C{int}
"""
def isWriteable():
"""Get the read/write status of the mailbox.
@rtype: C{int}
@return: A true value if write permission is allowed, a false value otherwise.
"""
def destroy():
"""Called before this mailbox is deleted, permanently.
If necessary, all resources held by this mailbox should be cleaned
up here. This function _must_ set the \\Noselect flag on this
mailbox.
"""
def requestStatus(names):
"""Return status information about this mailbox.
Mailboxes which do not intend to do any special processing to
generate the return value, C{statusRequestHelper} can be used
to build the dictionary by calling the other interface methods
which return the data for each name.
@type names: Any iterable
@param names: The status names to return information regarding.
The possible values for each name are: MESSAGES, RECENT, UIDNEXT,
UIDVALIDITY, UNSEEN.
@rtype: C{dict} or C{Deferred}
@return: A dictionary containing status information about the
requested names is returned. If the process of looking this
information up would be costly, a deferred whose callback will
eventually be passed this dictionary is returned instead.
"""
def addListener(listener):
"""Add a mailbox change listener
@type listener: Any object which implements C{IMailboxListener}
@param listener: An object to add to the set of those which will
be notified when the contents of this mailbox change.
"""
def removeListener(listener):
"""Remove a mailbox change listener
@type listener: Any object previously added to and not removed from
this mailbox as a listener.
@param listener: The object to remove from the set of listeners.
@raise ValueError: Raised when the given object is not a listener for
this mailbox.
"""
def addMessage(message, flags = (), date = None):
"""Add the given message to this mailbox.
@type message: A file-like object
@param message: The RFC822 formatted message
@type flags: Any iterable of C{str}
@param flags: The flags to associate with this message
@type date: C{str}
@param date: If specified, the date to associate with this
message.
@rtype: C{Deferred}
@return: A deferred whose callback is invoked with the message
id if the message is added successfully and whose errback is
invoked otherwise.
@raise ReadOnlyMailbox: Raised if this Mailbox is not open for
read-write.
"""
def expunge():
"""Remove all messages flagged \\Deleted.
@rtype: C{list} or C{Deferred}
@return: The list of message sequence numbers which were deleted,
or a C{Deferred} whose callback will be invoked with such a list.
@raise ReadOnlyMailbox: Raised if this Mailbox is not open for
read-write.
"""
def fetch(messages, uid):
"""Retrieve one or more messages.
@type messages: C{MessageSet}
@param messages: The identifiers of messages to retrieve information
about
@type uid: C{bool}
@param uid: If true, the IDs specified in the query are UIDs;
otherwise they are message sequence IDs.
@rtype: Any iterable of two-tuples of message sequence numbers and
implementors of C{IMessage}.
"""
def store(messages, flags, mode, uid):
"""Set the flags of one or more messages.
@type messages: A MessageSet object with the list of messages requested
@param messages: The identifiers of the messages to set the flags of.
@type flags: sequence of C{str}
@param flags: The flags to set, unset, or add.
@type mode: -1, 0, or 1
@param mode: If mode is -1, these flags should be removed from the
specified messages. If mode is 1, these flags should be added to
the specified messages. If mode is 0, all existing flags should be
cleared and these flags should be added.
@type uid: C{bool}
@param uid: If true, the IDs specified in the query are UIDs;
otherwise they are message sequence IDs.
@rtype: C{dict} or C{Deferred}
@return: A C{dict} mapping message sequence numbers to sequences of C{str}
representing the flags set on the message after this operation has
been performed, or a C{Deferred} whose callback will be invoked with
such a C{dict}.
@raise ReadOnlyMailbox: Raised if this mailbox is not open for
read-write.
"""
class ICloseableMailbox(Interface):
"""A supplementary interface for mailboxes which require cleanup on close.
Implementing this interface is optional. If it is implemented, the protocol
code will call the close method defined whenever a mailbox is closed.
"""
def close():
"""Close this mailbox.
@return: A C{Deferred} which fires when this mailbox
has been closed, or None if the mailbox can be closed
immediately.
"""
def _formatHeaders(headers):
hdrs = [': '.join((k.title(), '\r\n'.join(v.splitlines()))) for (k, v)
in headers.iteritems()]
hdrs = '\r\n'.join(hdrs) + '\r\n'
return hdrs
def subparts(m):
i = 0
try:
while True:
yield m.getSubPart(i)
i += 1
except IndexError:
pass
def iterateInReactor(i):
"""Consume an interator at most a single iteration per reactor iteration.
If the iterator produces a Deferred, the next iteration will not occur
until the Deferred fires, otherwise the next iteration will be taken
in the next reactor iteration.
@rtype: C{Deferred}
@return: A deferred which fires (with None) when the iterator is
exhausted or whose errback is called if there is an exception.
"""
from twisted.internet import reactor
d = defer.Deferred()
def go(last):
try:
r = i.next()
except StopIteration:
d.callback(last)
except:
d.errback()
else:
if isinstance(r, defer.Deferred):
r.addCallback(go)
else:
reactor.callLater(0, go, r)
go(None)
return d
class MessageProducer:
CHUNK_SIZE = 2 ** 2 ** 2 ** 2
def __init__(self, msg, buffer = None, scheduler = None):
"""Produce this message.
@param msg: The message I am to produce.
@type msg: L{IMessage}
@param buffer: A buffer to hold the message in. If None, I will
use a L{tempfile.TemporaryFile}.
@type buffer: file-like
"""
self.msg = msg
if buffer is None:
buffer = tempfile.TemporaryFile()
self.buffer = buffer
if scheduler is None:
scheduler = iterateInReactor
self.scheduler = scheduler
self.write = self.buffer.write
def beginProducing(self, consumer):
self.consumer = consumer
return self.scheduler(self._produce())
def _produce(self):
headers = self.msg.getHeaders(True)
boundary = None
if self.msg.isMultipart():
content = headers.get('content-type')
parts = [x.split('=', 1) for x in content.split(';')[1:]]
parts = dict([(k.lower().strip(), v) for (k, v) in parts])
boundary = parts.get('boundary')
if boundary is None:
# Bastards
boundary = '----=_%f_boundary_%f' % (time.time(), random.random())
headers['content-type'] += '; boundary="%s"' % (boundary,)
else:
if boundary.startswith('"') and boundary.endswith('"'):
boundary = boundary[1:-1]
self.write(_formatHeaders(headers))
self.write('\r\n')
if self.msg.isMultipart():
for p in subparts(self.msg):
self.write('\r\n--%s\r\n' % (boundary,))
yield MessageProducer(p, self.buffer, self.scheduler
).beginProducing(None
)
self.write('\r\n--%s--\r\n' % (boundary,))
else:
f = self.msg.getBodyFile()
while True:
b = f.read(self.CHUNK_SIZE)
if b:
self.buffer.write(b)
yield None
else:
break
if self.consumer:
self.buffer.seek(0, 0)
yield FileProducer(self.buffer
).beginProducing(self.consumer
).addCallback(lambda _: self
)
class _FetchParser:
class Envelope:
# Response should be a list of fields from the message:
# date, subject, from, sender, reply-to, to, cc, bcc, in-reply-to,
# and message-id.
#
# from, sender, reply-to, to, cc, and bcc are themselves lists of
# address information:
# personal name, source route, mailbox name, host name
#
# reply-to and sender must not be None. If not present in a message
# they should be defaulted to the value of the from field.
type = 'envelope'
__str__ = lambda self: 'envelope'
class Flags:
type = 'flags'
__str__ = lambda self: 'flags'
class InternalDate:
type = 'internaldate'
__str__ = lambda self: 'internaldate'
class RFC822Header:
type = 'rfc822header'
__str__ = lambda self: 'rfc822.header'
class RFC822Text:
type = 'rfc822text'
__str__ = lambda self: 'rfc822.text'
class RFC822Size:
type = 'rfc822size'
__str__ = lambda self: 'rfc822.size'
class RFC822:
type = 'rfc822'
__str__ = lambda self: 'rfc822'
class UID:
type = 'uid'
__str__ = lambda self: 'uid'
class Body:
type = 'body'
peek = False
header = None
mime = None
text = None
part = ()
empty = False
partialBegin = None
partialLength = None
def __str__(self):
base = 'BODY'
part = ''
separator = ''
if self.part:
part = '.'.join([str(x + 1) for x in self.part])
separator = '.'
# if self.peek:
# base += '.PEEK'
if self.header:
base += '[%s%s%s]' % (part, separator, self.header,)
elif self.text:
base += '[%s%sTEXT]' % (part, separator)
elif self.mime:
base += '[%s%sMIME]' % (part, separator)
elif self.empty:
base += '[%s]' % (part,)
if self.partialBegin is not None:
base += '<%d.%d>' % (self.partialBegin, self.partialLength)
return base
class BodyStructure:
type = 'bodystructure'
__str__ = lambda self: 'bodystructure'
# These three aren't top-level, they don't need type indicators
class Header:
negate = False
fields = None
part = None
def __str__(self):
base = 'HEADER'
if self.fields:
base += '.FIELDS'
if self.negate:
base += '.NOT'
fields = []
for f in self.fields:
f = f.title()
if _needsQuote(f):
f = _quote(f)
fields.append(f)
base += ' (%s)' % ' '.join(fields)
if self.part:
base = '.'.join([str(x + 1) for x in self.part]) + '.' + base
return base
class Text:
pass
class MIME:
pass
parts = None
_simple_fetch_att = [
('envelope', Envelope),
('flags', Flags),
('internaldate', InternalDate),
('rfc822.header', RFC822Header),
('rfc822.text', RFC822Text),
('rfc822.size', RFC822Size),
('rfc822', RFC822),
('uid', UID),
('bodystructure', BodyStructure),
]
def __init__(self):
self.state = ['initial']
self.result = []
self.remaining = ''
def parseString(self, s):
s = self.remaining + s
try:
while s or self.state:
# print 'Entering state_' + self.state[-1] + ' with', repr(s)
state = self.state.pop()
try:
used = getattr(self, 'state_' + state)(s)
except:
self.state.append(state)
raise
else:
# print state, 'consumed', repr(s[:used])
s = s[used:]
finally:
self.remaining = s
def state_initial(self, s):
# In the initial state, the literals "ALL", "FULL", and "FAST"
# are accepted, as is a ( indicating the beginning of a fetch_att
# token, as is the beginning of a fetch_att token.
if s == '':
return 0
l = s.lower()
if l.startswith('all'):
self.result.extend((
self.Flags(), self.InternalDate(),
self.RFC822Size(), self.Envelope()
))
return 3
if l.startswith('full'):
self.result.extend((
self.Flags(), self.InternalDate(),
self.RFC822Size(), self.Envelope(),
self.Body()
))
return 4
if l.startswith('fast'):
self.result.extend((
self.Flags(), self.InternalDate(), self.RFC822Size(),
))
return 4
if l.startswith('('):
self.state.extend(('close_paren', 'maybe_fetch_att', 'fetch_att'))
return 1
self.state.append('fetch_att')
return 0
def state_close_paren(self, s):
if s.startswith(')'):
return 1
raise Exception("Missing )")
def state_whitespace(self, s):
# Eat up all the leading whitespace
if not s or not s[0].isspace():
raise Exception("Whitespace expected, none found")
i = 0
for i in range(len(s)):
if not s[i].isspace():
break
return i
def state_maybe_fetch_att(self, s):
if not s.startswith(')'):
self.state.extend(('maybe_fetch_att', 'fetch_att', 'whitespace'))
return 0
def state_fetch_att(self, s):
# Allowed fetch_att tokens are "ENVELOPE", "FLAGS", "INTERNALDATE",
# "RFC822", "RFC822.HEADER", "RFC822.SIZE", "RFC822.TEXT", "BODY",
# "BODYSTRUCTURE", "UID",
# "BODY [".PEEK"] [<section>] ["<" <number> "." <nz_number> ">"]
l = s.lower()
for (name, cls) in self._simple_fetch_att:
if l.startswith(name):
self.result.append(cls())
return len(name)
b = self.Body()
if l.startswith('body.peek'):
b.peek = True
used = 9
elif l.startswith('body'):
used = 4
else:
raise Exception("Nothing recognized in fetch_att: %s" % (l,))
self.pending_body = b
self.state.extend(('got_body', 'maybe_partial', 'maybe_section'))
return used
def state_got_body(self, s):
self.result.append(self.pending_body)
del self.pending_body
return 0
def state_maybe_section(self, s):
if not s.startswith("["):
return 0
self.state.extend(('section', 'part_number'))
return 1
_partExpr = re.compile(r'(\d+(?:\.\d+)*)\.?')
def state_part_number(self, s):
m = self._partExpr.match(s)
if m is not None:
self.parts = [int(p) - 1 for p in m.groups()[0].split('.')]
return m.end()
else:
self.parts = []
return 0
def state_section(self, s):
# Grab "HEADER]" or "HEADER.FIELDS (Header list)]" or
# "HEADER.FIELDS.NOT (Header list)]" or "TEXT]" or "MIME]" or
# just "]".
l = s.lower()
used = 0
if l.startswith(']'):
self.pending_body.empty = True
used += 1
elif l.startswith('header]'):
h = self.pending_body.header = self.Header()
h.negate = True
h.fields = ()
used += 7
elif l.startswith('text]'):
self.pending_body.text = self.Text()
used += 5
elif l.startswith('mime]'):
self.pending_body.mime = self.MIME()
used += 5
else:
h = self.Header()
if l.startswith('header.fields.not'):
h.negate = True
used += 17
elif l.startswith('header.fields'):
used += 13
else:
raise Exception("Unhandled section contents: %r" % (l,))
self.pending_body.header = h
self.state.extend(('finish_section', 'header_list', 'whitespace'))
self.pending_body.part = tuple(self.parts)
self.parts = None
return used
def state_finish_section(self, s):
if not s.startswith(']'):
raise Exception("section must end with ]")
return 1
def state_header_list(self, s):
if not s.startswith('('):
raise Exception("Header list must begin with (")
end = s.find(')')
if end == -1:
raise Exception("Header list must end with )")
headers = s[1:end].split()
self.pending_body.header.fields = map(str.upper, headers)
return end + 1
def state_maybe_partial(self, s):
# Grab <number.number> or nothing at all
if not s.startswith('<'):
return 0
end = s.find('>')
if end == -1:
raise Exception("Found < but not >")
partial = s[1:end]
parts = partial.split('.', 1)
if len(parts) != 2:
raise Exception("Partial specification did not include two .-delimited integers")
begin, length = map(int, parts)
self.pending_body.partialBegin = begin
self.pending_body.partialLength = length
return end + 1
class FileProducer:
CHUNK_SIZE = 2 ** 2 ** 2 ** 2
firstWrite = True
def __init__(self, f):
self.f = f
def beginProducing(self, consumer):
self.consumer = consumer
self.produce = consumer.write
d = self._onDone = defer.Deferred()
self.consumer.registerProducer(self, False)
return d
def resumeProducing(self):
b = ''
if self.firstWrite:
b = '{%d}\r\n' % self._size()
self.firstWrite = False
if not self.f:
return
b = b + self.f.read(self.CHUNK_SIZE)
if not b:
self.consumer.unregisterProducer()
self._onDone.callback(self)
self._onDone = self.f = self.consumer = None
else:
self.produce(b)
def pauseProducing(self):
pass
def stopProducing(self):
pass
def _size(self):
b = self.f.tell()
self.f.seek(0, 2)
e = self.f.tell()
self.f.seek(b, 0)
return e - b
def parseTime(s):
# XXX - This may require localization :(
months = [
'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct',
'nov', 'dec', 'january', 'february', 'march', 'april', 'may', 'june',
'july', 'august', 'september', 'october', 'november', 'december'
]
expr = {
'day': r"(?P<day>3[0-1]|[1-2]\d|0[1-9]|[1-9]| [1-9])",
'mon': r"(?P<mon>\w+)",
'year': r"(?P<year>\d\d\d\d)"
}
m = re.match('%(day)s-%(mon)s-%(year)s' % expr, s)
if not m:
raise ValueError, "Cannot parse time string %r" % (s,)
d = m.groupdict()
try:
d['mon'] = 1 + (months.index(d['mon'].lower()) % 12)
d['year'] = int(d['year'])
d['day'] = int(d['day'])
except ValueError:
raise ValueError, "Cannot parse time string %r" % (s,)
else:
return time.struct_time(
(d['year'], d['mon'], d['day'], 0, 0, 0, -1, -1, -1)
)
import codecs
def modified_base64(s):
s_utf7 = s.encode('utf-7')
return s_utf7[1:-1].replace('/', ',')
def modified_unbase64(s):
s_utf7 = '+' + s.replace(',', '/') + '-'
return s_utf7.decode('utf-7')
def encoder(s):
r = []
_in = []
for c in s:
if ord(c) in (range(0x20, 0x26) + range(0x27, 0x7f)):
if _in:
r.extend(['&', modified_base64(''.join(_in)), '-'])
del _in[:]
r.append(str(c))
elif c == '&':
if _in:
r.extend(['&', modified_base64(''.join(_in)), '-'])
del _in[:]
r.append('&-')
else:
_in.append(c)
if _in:
r.extend(['&', modified_base64(''.join(_in)), '-'])
return (''.join(r), len(s))
def decoder(s):
r = []
decode = []
for c in s:
if c == '&' and not decode:
decode.append('&')
elif c == '-' and decode:
if len(decode) == 1:
r.append('&')
else:
r.append(modified_unbase64(''.join(decode[1:])))
decode = []
elif decode:
decode.append(c)
else:
r.append(c)
if decode:
r.append(modified_unbase64(''.join(decode[1:])))
return (''.join(r), len(s))
class StreamReader(codecs.StreamReader):
def decode(self, s, errors='strict'):
return decoder(s)
class StreamWriter(codecs.StreamWriter):
def decode(self, s, errors='strict'):
return encoder(s)
def imap4_utf_7(name):
if name == 'imap4-utf-7':
return (encoder, decoder, StreamReader, StreamWriter)
codecs.register(imap4_utf_7)
__all__ = [
# Protocol classes
'IMAP4Server', 'IMAP4Client',
# Interfaces
'IMailboxListener', 'IClientAuthentication', 'IAccount', 'IMailbox',
'INamespacePresenter', 'ICloseableMailbox', 'IMailboxInfo',
'IMessage', 'IMessageCopier', 'IMessageFile', 'ISearchableMailbox',
# Exceptions
'IMAP4Exception', 'IllegalClientResponse', 'IllegalOperation',
'IllegalMailboxEncoding', 'UnhandledResponse', 'NegativeResponse',
'NoSupportedAuthentication', 'IllegalServerResponse',
'IllegalIdentifierError', 'IllegalQueryError', 'MismatchedNesting',
'MismatchedQuoting', 'MailboxException', 'MailboxCollision',
'NoSuchMailbox', 'ReadOnlyMailbox',
# Auth objects
'CramMD5ClientAuthenticator', 'PLAINAuthenticator', 'LOGINAuthenticator',
'PLAINCredentials', 'LOGINCredentials',
# Simple query interface
'Query', 'Not', 'Or',
# Miscellaneous
'MemoryAccount',
'statusRequestHelper',
] | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/mail/imap4.py | imap4.py |
import os
import tempfile
from twisted.mail import smtp
from twisted.internet import protocol
from twisted.internet import defer
from twisted.internet import error
from twisted.python import failure
from twisted.python import log
from zope.interface import implements, Interface
def handle(result, line, filename, lineNo):
parts = [p.strip() for p in line.split(':', 1)]
if len(parts) != 2:
fmt = "Invalid format on line %d of alias file %s."
arg = (lineNo, filename)
log.err(fmt % arg)
else:
user, alias = parts
result.setdefault(user.strip(), []).extend(map(str.strip, alias.split(',')))
def loadAliasFile(domains, filename=None, fp=None):
"""Load a file containing email aliases.
Lines in the file should be formatted like so::
username: alias1,alias2,...,aliasN
Aliases beginning with a | will be treated as programs, will be run, and
the message will be written to their stdin.
Aliases without a host part will be assumed to be addresses on localhost.
If a username is specified multiple times, the aliases for each are joined
together as if they had all been on one line.
@type domains: C{dict} of implementor of C{IDomain}
@param domains: The domains to which these aliases will belong.
@type filename: C{str}
@param filename: The filename from which to load aliases.
@type fp: Any file-like object.
@param fp: If specified, overrides C{filename}, and aliases are read from
it.
@rtype: C{dict}
@return: A dictionary mapping usernames to C{AliasGroup} objects.
"""
result = {}
if fp is None:
fp = file(filename)
else:
filename = getattr(fp, 'name', '<unknown>')
i = 0
prev = ''
for line in fp:
i += 1
line = line.rstrip()
if line.lstrip().startswith('#'):
continue
elif line.startswith(' ') or line.startswith('\t'):
prev = prev + line
else:
if prev:
handle(result, prev, filename, i)
prev = line
if prev:
handle(result, prev, filename, i)
for (u, a) in result.items():
addr = smtp.Address(u)
result[u] = AliasGroup(a, domains, u)
return result
class IAlias(Interface):
def createMessageReceiver():
pass
class AliasBase:
def __init__(self, domains, original):
self.domains = domains
self.original = smtp.Address(original)
def domain(self):
return self.domains[self.original.domain]
def resolve(self, aliasmap, memo=None):
if memo is None:
memo = {}
if str(self) in memo:
return None
memo[str(self)] = None
return self.createMessageReceiver()
class AddressAlias(AliasBase):
"""The simplest alias, translating one email address into another."""
implements(IAlias)
def __init__(self, alias, *args):
AliasBase.__init__(self, *args)
self.alias = smtp.Address(alias)
def __str__(self):
return '<Address %s>' % (self.alias,)
def createMessageReceiver(self):
return self.domain().startMessage(str(self.alias))
def resolve(self, aliasmap, memo=None):
if memo is None:
memo = {}
if str(self) in memo:
return None
memo[str(self)] = None
try:
return self.domain().exists(smtp.User(self.alias, None, None, None), memo)()
except smtp.SMTPBadRcpt:
pass
if self.alias.local in aliasmap:
return aliasmap[self.alias.local].resolve(aliasmap, memo)
return None
class FileWrapper:
implements(smtp.IMessage)
def __init__(self, filename):
self.fp = tempfile.TemporaryFile()
self.finalname = filename
def lineReceived(self, line):
self.fp.write(line + '\n')
def eomReceived(self):
self.fp.seek(0, 0)
try:
f = file(self.finalname, 'a')
except:
return defer.fail(failure.Failure())
f.write(self.fp.read())
self.fp.close()
f.close()
return defer.succeed(self.finalname)
def connectionLost(self):
self.fp.close()
self.fp = None
def __str__(self):
return '<FileWrapper %s>' % (self.finalname,)
class FileAlias(AliasBase):
implements(IAlias)
def __init__(self, filename, *args):
AliasBase.__init__(self, *args)
self.filename = filename
def __str__(self):
return '<File %s>' % (self.filename,)
def createMessageReceiver(self):
return FileWrapper(self.filename)
class MessageWrapper:
implements(smtp.IMessage)
done = False
def __init__(self, protocol, process=None):
self.processName = process
self.protocol = protocol
self.completion = defer.Deferred()
self.protocol.onEnd = self.completion
self.completion.addCallback(self._processEnded)
def _processEnded(self, result, err=0):
self.done = True
if err:
raise result.value
def lineReceived(self, line):
if self.done:
return
self.protocol.transport.write(line + '\n')
def eomReceived(self):
if not self.done:
self.protocol.transport.loseConnection()
self.completion.setTimeout(60)
return self.completion
def connectionLost(self):
# Heh heh
pass
def __str__(self):
return '<ProcessWrapper %s>' % (self.processName,)
class ProcessAliasProtocol(protocol.ProcessProtocol):
def processEnded(self, reason):
if reason.check(error.ProcessDone):
self.onEnd.callback("Complete")
else:
self.onEnd.errback(reason)
class ProcessAlias(AliasBase):
"""An alias for a program."""
implements(IAlias)
def __init__(self, path, *args):
AliasBase.__init__(self, *args)
self.path = path.split()
self.program = self.path[0]
def __str__(self):
return '<Process %s>' % (self.path,)
def createMessageReceiver(self):
from twisted.internet import reactor
p = ProcessAliasProtocol()
m = MessageWrapper(p, self.program)
fd = reactor.spawnProcess(p, self.program, self.path)
return m
class MultiWrapper:
"""Wrapper to deliver a single message to multiple recipients"""
implements(smtp.IMessage)
def __init__(self, objs):
self.objs = objs
def lineReceived(self, line):
for o in self.objs:
o.lineReceived(line)
def eomReceived(self):
return defer.DeferredList([
o.eomReceived() for o in self.objs
])
def connectionLost(self):
for o in self.objs:
o.connectionLost()
def __str__(self):
return '<GroupWrapper %r>' % (map(str, self.objs),)
class AliasGroup(AliasBase):
"""An alias which points to more than one recipient"""
implements(IAlias)
def __init__(self, items, *args):
AliasBase.__init__(self, *args)
self.aliases = []
while items:
addr = items.pop().strip()
if addr.startswith(':'):
try:
f = file(addr[1:])
except:
log.err("Invalid filename in alias file %r" % (addr[1:],))
else:
addr = ' '.join([l.strip() for l in f])
items.extend(addr.split(','))
elif addr.startswith('|'):
self.aliases.append(ProcessAlias(addr[1:], *args))
elif addr.startswith('/'):
if os.path.isdir(addr):
log.err("Directory delivery not supported")
else:
self.aliases.append(FileAlias(addr, *args))
else:
self.aliases.append(AddressAlias(addr, *args))
def __len__(self):
return len(self.aliases)
def __str__(self):
return '<AliasGroup [%s]>' % (', '.join(map(str, self.aliases)))
def createMessageReceiver(self):
return MultiWrapper([a.createMessageReceiver() for a in self.aliases])
def resolve(self, aliasmap, memo=None):
if memo is None:
memo = {}
r = []
for a in self.aliases:
r.append(a.resolve(aliasmap, memo))
return MultiWrapper(filter(None, r)) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/mail/alias.py | alias.py |
from twisted.python import log
from twisted.python import util
from twisted.mail import relay
from twisted.mail import bounce
from twisted.internet import protocol
from twisted.internet.defer import Deferred, DeferredList
from twisted.internet.error import DNSLookupError
from twisted.mail import smtp
from twisted.application import internet
import rfc822
import os
import time
try:
import cPickle as pickle
except ImportError:
import pickle
class ManagedRelayerMixin:
"""SMTP Relayer which notifies a manager
Notify the manager about successful mail, failed mail
and broken connections
"""
def __init__(self, manager):
self.manager = manager
def sentMail(self, code, resp, numOk, addresses, log):
"""called when e-mail has been sent
we will always get 0 or 1 addresses.
"""
message = self.names[0]
if code in smtp.SUCCESS:
self.manager.notifySuccess(self.factory, message)
else:
self.manager.notifyFailure(self.factory, message)
del self.messages[0]
del self.names[0]
def connectionLost(self, reason):
"""called when connection is broken
notify manager we will try to send no more e-mail
"""
self.manager.notifyDone(self.factory)
class SMTPManagedRelayer(ManagedRelayerMixin, relay.SMTPRelayer):
def __init__(self, messages, manager, *args, **kw):
"""
@type messages: C{list} of C{str}
@param messages: Filenames of messages to relay
manager should support .notifySuccess, .notifyFailure
and .notifyDone
"""
ManagedRelayerMixin.__init__(self, manager)
relay.SMTPRelayer.__init__(self, messages, *args, **kw)
class ESMTPManagedRelayer(ManagedRelayerMixin, relay.ESMTPRelayer):
def __init__(self, messages, manager, *args, **kw):
"""
@type messages: C{list} of C{str}
@param messages: Filenames of messages to relay
manager should support .notifySuccess, .notifyFailure
and .notifyDone
"""
ManagedRelayerMixin.__init__(self, manager)
relay.ESMTPRelayer.__init__(self, messages, *args, **kw)
class SMTPManagedRelayerFactory(protocol.ClientFactory):
protocol = SMTPManagedRelayer
def __init__(self, messages, manager, *args, **kw):
self.messages = messages
self.manager = manager
self.pArgs = args
self.pKwArgs = kw
def buildProtocol(self, addr):
protocol = self.protocol(self.messages, self.manager, *self.pArgs,
**self.pKwArgs)
protocol.factory = self
return protocol
def clientConnectionFailed(self, connector, reason):
"""called when connection could not be made
our manager should be notified that this happened,
it might prefer some other host in that case"""
self.manager.notifyNoConnection(self)
self.manager.notifyDone(self)
class ESMTPManagedRelayerFactory(SMTPManagedRelayerFactory):
protocol = ESMTPManagedRelayer
def __init__(self, messages, manager, secret, contextFactory, *args, **kw):
self.secret = secret
self.contextFactory = contextFactory
SMTPManagedRelayerFactory.__init__(self, messages, manager, *args, **kw)
def buildProtocol(self, addr):
s = self.secret and self.secret(addr)
protocol = self.protocol(self.messages, self.manager, s,
self.contextFactory, *self.pArgs, **self.pKwArgs)
protocol.factory = self
return protocol
class Queue:
"""A queue of ougoing emails."""
noisy = True
def __init__(self, directory):
self.directory = directory
self._init()
def _init(self):
self.n = 0
self.waiting = {}
self.relayed = {}
self.readDirectory()
def __getstate__(self):
"""(internal) delete volatile state"""
return {'directory' : self.directory}
def __setstate__(self, state):
"""(internal) restore volatile state"""
self.__dict__.update(state)
self._init()
def readDirectory(self):
"""Read the messages directory.
look for new messages.
"""
for message in os.listdir(self.directory):
# Skip non data files
if message[-2:]!='-D':
continue
self.addMessage(message[:-2])
def getWaiting(self):
return self.waiting.keys()
def hasWaiting(self):
return len(self.waiting) > 0
def getRelayed(self):
return self.relayed.keys()
def setRelaying(self, message):
del self.waiting[message]
self.relayed[message] = 1
def setWaiting(self, message):
del self.relayed[message]
self.waiting[message] = 1
def addMessage(self, message):
if message not in self.relayed:
self.waiting[message] = 1
if self.noisy:
log.msg('Set ' + message + ' waiting')
def done(self, message):
"""Remove message to from queue."""
message = os.path.basename(message)
os.remove(self.getPath(message) + '-D')
os.remove(self.getPath(message) + '-H')
del self.relayed[message]
def getPath(self, message):
"""Get the path in the filesystem of a message."""
return os.path.join(self.directory, message)
def getEnvelope(self, message):
return pickle.load(self.getEnvelopeFile(message))
def getEnvelopeFile(self, message):
return open(os.path.join(self.directory, message+'-H'), 'rb')
def createNewMessage(self):
"""Create a new message in the queue.
Return a tuple - file-like object for headers, and ISMTPMessage.
"""
fname = "%s_%s_%s_%s" % (os.getpid(), time.time(), self.n, id(self))
self.n = self.n + 1
headerFile = open(os.path.join(self.directory, fname+'-H'), 'wb')
tempFilename = os.path.join(self.directory, fname+'-C')
finalFilename = os.path.join(self.directory, fname+'-D')
messageFile = open(tempFilename, 'wb')
from twisted.mail.mail import FileMessage
return headerFile,FileMessage(messageFile, tempFilename, finalFilename)
class _AttemptManager(object):
"""
Manage the state of a single attempt to flush the relay queue.
"""
def __init__(self, manager):
self.manager = manager
self._completionDeferreds = []
def getCompletionDeferred(self):
self._completionDeferreds.append(Deferred())
return self._completionDeferreds[-1]
def _finish(self, relay, message):
self.manager.managed[relay].remove(os.path.basename(message))
self.manager.queue.done(message)
def notifySuccess(self, relay, message):
"""a relay sent a message successfully
Mark it as sent in our lists
"""
if self.manager.queue.noisy:
log.msg("success sending %s, removing from queue" % message)
self._finish(relay, message)
def notifyFailure(self, relay, message):
"""Relaying the message has failed."""
if self.manager.queue.noisy:
log.msg("could not relay "+message)
# Moshe - Bounce E-mail here
# Be careful: if it's a bounced bounce, silently
# discard it
message = os.path.basename(message)
fp = self.manager.queue.getEnvelopeFile(message)
from_, to = pickle.load(fp)
fp.close()
from_, to, bounceMessage = bounce.generateBounce(open(self.manager.queue.getPath(message)+'-D'), from_, to)
fp, outgoingMessage = self.manager.queue.createNewMessage()
pickle.dump([from_, to], fp)
fp.close()
for line in bounceMessage.splitlines():
outgoingMessage.lineReceived(line)
outgoingMessage.eomReceived()
self._finish(relay, self.manager.queue.getPath(message))
def notifyDone(self, relay):
"""A relaying SMTP client is disconnected.
unmark all pending messages under this relay's responsibility
as being relayed, and remove the relay.
"""
for message in self.manager.managed.get(relay, ()):
if self.manager.queue.noisy:
log.msg("Setting " + message + " waiting")
self.manager.queue.setWaiting(message)
try:
del self.manager.managed[relay]
except KeyError:
pass
notifications = self._completionDeferreds
self._completionDeferreds = None
for d in notifications:
d.callback(None)
def notifyNoConnection(self, relay):
"""Relaying SMTP client couldn't connect.
Useful because it tells us our upstream server is unavailable.
"""
# Back off a bit
try:
msgs = self.manager.managed[relay]
except KeyError:
log.msg("notifyNoConnection passed unknown relay!")
return
if self.manager.queue.noisy:
log.msg("Backing off on delivery of " + str(msgs))
def setWaiting(queue, messages):
map(queue.setWaiting, messages)
from twisted.internet import reactor
reactor.callLater(30, setWaiting, self.manager.queue, msgs)
del self.manager.managed[relay]
class SmartHostSMTPRelayingManager:
"""Manage SMTP Relayers
Manage SMTP relayers, keeping track of the existing connections,
each connection's responsibility in term of messages. Create
more relayers if the need arises.
Someone should press .checkState periodically
@ivar fArgs: Additional positional arguments used to instantiate
C{factory}.
@ivar fKwArgs: Additional keyword arguments used to instantiate
C{factory}.
@ivar factory: A callable which returns a ClientFactory suitable for
making SMTP connections.
"""
factory = SMTPManagedRelayerFactory
PORT = 25
mxcalc = None
def __init__(self, queue, maxConnections=2, maxMessagesPerConnection=10):
"""
@type queue: Any implementor of C{IQueue}
@param queue: The object used to queue messages on their way to
delivery.
@type maxConnections: C{int}
@param maxConnections: The maximum number of SMTP connections to
allow to be opened at any given time.
@type maxMessagesPerConnection: C{int}
@param maxMessagesPerConnection: The maximum number of messages a
relayer will be given responsibility for.
Default values are meant for a small box with 1-5 users.
"""
self.maxConnections = maxConnections
self.maxMessagesPerConnection = maxMessagesPerConnection
self.managed = {} # SMTP clients we're managing
self.queue = queue
self.fArgs = ()
self.fKwArgs = {}
def __getstate__(self):
"""(internal) delete volatile state"""
dct = self.__dict__.copy()
del dct['managed']
return dct
def __setstate__(self, state):
"""(internal) restore volatile state"""
self.__dict__.update(state)
self.managed = {}
def checkState(self):
"""
Synchronize with the state of the world, and maybe launch a new
relay.
Call me periodically to check I am still up to date.
@return: None or a Deferred which fires when all of the SMTP clients
started by this call have disconnected.
"""
self.queue.readDirectory()
if (len(self.managed) >= self.maxConnections):
return
if not self.queue.hasWaiting():
return
return self._checkStateMX()
def _checkStateMX(self):
nextMessages = self.queue.getWaiting()
nextMessages.reverse()
exchanges = {}
for msg in nextMessages:
from_, to = self.queue.getEnvelope(msg)
name, addr = rfc822.parseaddr(to)
parts = addr.split('@', 1)
if len(parts) != 2:
log.err("Illegal message destination: " + to)
continue
domain = parts[1]
self.queue.setRelaying(msg)
exchanges.setdefault(domain, []).append(self.queue.getPath(msg))
if len(exchanges) >= (self.maxConnections - len(self.managed)):
break
if self.mxcalc is None:
self.mxcalc = MXCalculator()
relays = []
for (domain, msgs) in exchanges.iteritems():
manager = _AttemptManager(self)
factory = self.factory(msgs, manager, *self.fArgs, **self.fKwArgs)
self.managed[factory] = map(os.path.basename, msgs)
relayAttemptDeferred = manager.getCompletionDeferred()
connectSetupDeferred = self.mxcalc.getMX(domain)
connectSetupDeferred.addCallback(lambda mx: str(mx.name))
connectSetupDeferred.addCallback(self._cbExchange, self.PORT, factory)
connectSetupDeferred.addErrback(lambda err: (relayAttemptDeferred.errback(err), err)[1])
connectSetupDeferred.addErrback(self._ebExchange, factory, domain)
relays.append(relayAttemptDeferred)
return DeferredList(relays)
def _cbExchange(self, address, port, factory):
from twisted.internet import reactor
reactor.connectTCP(address, port, factory)
def _ebExchange(self, failure, factory, domain):
log.err('Error setting up managed relay factory for ' + domain)
log.err(failure)
def setWaiting(queue, messages):
map(queue.setWaiting, messages)
from twisted.internet import reactor
reactor.callLater(30, setWaiting, self.queue, self.managed[factory])
del self.managed[factory]
class SmartHostESMTPRelayingManager(SmartHostSMTPRelayingManager):
factory = ESMTPManagedRelayerFactory
def _checkState(manager):
manager.checkState()
def RelayStateHelper(manager, delay):
return internet.TimerService(delay, _checkState, manager)
class MXCalculator:
timeOutBadMX = 60 * 60 # One hour
fallbackToDomain = True
def __init__(self, resolver = None):
self.badMXs = {}
if resolver is None:
from twisted.names.client import createResolver
resolver = createResolver()
self.resolver = resolver
def markBad(self, mx):
"""Indicate a given mx host is not currently functioning.
@type mx: C{str}
@param mx: The hostname of the host which is down.
"""
self.badMXs[str(mx)] = time.time() + self.timeOutBadMX
def markGood(self, mx):
"""Indicate a given mx host is back online.
@type mx: C{str}
@param mx: The hostname of the host which is up.
"""
try:
del self.badMXs[mx]
except KeyError:
pass
def getMX(self, domain):
return self.resolver.lookupMailExchange(domain
).addCallback(self._filterRecords
).addCallback(self._cbMX, domain
).addErrback(self._ebMX, domain
)
def _filterRecords(self, records):
answers = records[0]
return [a.payload for a in answers]
def _cbMX(self, answers, domain):
answers = util.dsu(answers, lambda e: e.preference)
for answer in answers:
host = str(answer.name)
if host not in self.badMXs:
return answer
t = time.time() - self.badMXs[host]
if t > 0:
del self.badMXs[host]
return answer
return answers[0]
def _ebMX(self, failure, domain):
from twisted.names import error, dns
if self.fallbackToDomain:
failure.trap(error.DNSNameError)
log.msg("MX lookup failed; attempting to use hostname (%s) directly" % (domain,))
# Alright, I admit, this is a bit icky.
d = self.resolver.getHostByName(domain)
def cbResolved(addr):
return dns.Record_MX(name=addr)
def ebResolved(err):
err.trap(error.DNSNameError)
raise DNSLookupError()
d.addCallbacks(cbResolved, ebResolved)
return d
elif failure.check(error.DNSNameError):
raise IOError("No MX found for %r" % (domain,))
return failure | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/mail/relaymanager.py | relaymanager.py |
# twisted imports
from twisted.mail import pop3
from twisted.mail import smtp
from twisted.internet import protocol
from twisted.internet import defer
from twisted.copyright import longversion
from twisted.python import log
from twisted import cred
import twisted.cred.error
import twisted.cred.credentials
from twisted.mail import relay
from zope.interface import implements
class DomainDeliveryBase:
"""A server that uses twisted.mail service's domains."""
implements(smtp.IMessageDelivery)
service = None
protocolName = None
def __init__(self, service, user, host=smtp.DNSNAME):
self.service = service
self.user = user
self.host = host
def receivedHeader(self, helo, origin, recipients):
authStr = heloStr = ""
if self.user:
authStr = " auth=%s" % (self.user.encode('xtext'),)
if helo[0]:
heloStr = " helo=%s" % (helo[0],)
from_ = "from %s ([%s]%s%s)" % (helo[0], helo[1], heloStr, authStr)
by = "by %s with %s (%s)" % (
self.host, self.protocolName, longversion
)
for_ = "for <%s>; %s" % (' '.join(map(str, recipients)), smtp.rfc822date())
return "Received: %s\n\t%s\n\t%s" % (from_, by, for_)
def validateTo(self, user):
# XXX - Yick. This needs cleaning up.
if self.user and self.service.queue:
d = self.service.domains.get(user.dest.domain, None)
if d is None:
d = relay.DomainQueuer(self.service, True)
else:
d = self.service.domains[user.dest.domain]
return defer.maybeDeferred(d.exists, user)
def validateFrom(self, helo, origin):
if not helo:
raise smtp.SMTPBadSender(origin, 503, "Who are you? Say HELO first.")
if origin.local != '' and origin.domain == '':
raise smtp.SMTPBadSender(origin, 501, "Sender address must contain domain.")
return origin
def startMessage(self, users):
ret = []
for user in users:
ret.append(self.service.domains[user.dest.domain].startMessage(user))
return ret
class SMTPDomainDelivery(DomainDeliveryBase):
protocolName = 'smtp'
class ESMTPDomainDelivery(DomainDeliveryBase):
protocolName = 'esmtp'
class DomainSMTP(SMTPDomainDelivery, smtp.SMTP):
service = user = None
def __init__(self, *args, **kw):
import warnings
warnings.warn(
"DomainSMTP is deprecated. Use IMessageDelivery objects instead.",
DeprecationWarning, stacklevel=2,
)
smtp.SMTP.__init__(self, *args, **kw)
if self.delivery is None:
self.delivery = self
class DomainESMTP(ESMTPDomainDelivery, smtp.ESMTP):
service = user = None
def __init__(self, *args, **kw):
import warnings
warnings.warn(
"DomainESMTP is deprecated. Use IMessageDelivery objects instead.",
DeprecationWarning, stacklevel=2,
)
smtp.ESMTP.__init__(self, *args, **kw)
if self.delivery is None:
self.delivery = self
class SMTPFactory(smtp.SMTPFactory):
"""A protocol factory for SMTP."""
protocol = smtp.SMTP
portal = None
def __init__(self, service, portal = None):
smtp.SMTPFactory.__init__(self)
self.service = service
self.portal = portal
def buildProtocol(self, addr):
log.msg('Connection from %s' % (addr,))
p = smtp.SMTPFactory.buildProtocol(self, addr)
p.service = self.service
p.portal = self.portal
return p
class ESMTPFactory(SMTPFactory):
protocol = smtp.ESMTP
context = None
def __init__(self, *args):
SMTPFactory.__init__(self, *args)
self.challengers = {
'CRAM-MD5': cred.credentials.CramMD5Credentials
}
def buildProtocol(self, addr):
p = SMTPFactory.buildProtocol(self, addr)
p.challengers = self.challengers
p.ctx = self.context
return p
class VirtualPOP3(pop3.POP3):
"""Virtual hosting POP3."""
service = None
domainSpecifier = '@' # Gaagh! I hate POP3. No standardized way
# to indicate user@host. '@' doesn't work
# with NS, e.g.
def authenticateUserAPOP(self, user, digest):
# Override the default lookup scheme to allow virtual domains
user, domain = self.lookupDomain(user)
try:
portal = self.service.lookupPortal(domain)
except KeyError:
return defer.fail(cred.error.UnauthorizedLogin())
else:
return portal.login(
pop3.APOPCredentials(self.magic, user, digest),
None,
pop3.IMailbox
)
def authenticateUserPASS(self, user, password):
user, domain = self.lookupDomain(user)
try:
portal = self.service.lookupPortal(domain)
except KeyError:
return defer.fail(cred.error.UnauthorizedLogin())
else:
return portal.login(
cred.credentials.UsernamePassword(user, password),
None,
pop3.IMailbox
)
def lookupDomain(self, user):
try:
user, domain = user.split(self.domainSpecifier, 1)
except ValueError:
domain = ''
if domain not in self.service.domains:
raise pop3.POP3Error("no such domain %s" % domain)
return user, domain
class POP3Factory(protocol.ServerFactory):
"""POP3 protocol factory."""
protocol = VirtualPOP3
service = None
def __init__(self, service):
self.service = service
def buildProtocol(self, addr):
p = protocol.ServerFactory.buildProtocol(self, addr)
p.service = self.service
return p
#
# It is useful to know, perhaps, that the required file for this to work can
# be created thusly:
#
# openssl req -x509 -newkey rsa:2048 -keyout file.key -out file.crt \
# -days 365 -nodes
#
# And then cat file.key and file.crt together. The number of days and bits
# can be changed, of course.
#
class SSLContextFactory:
"""An SSL Context Factory
This loads a certificate and private key from a specified file.
"""
def __init__(self, filename):
self.filename = filename
def getContext(self):
"""Create an SSL context."""
from OpenSSL import SSL
ctx = SSL.Context(SSL.SSLv23_METHOD)
ctx.use_certificate_file(self.filename)
ctx.use_privatekey_file(self.filename)
return ctx | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/mail/protocols.py | protocols.py |
# Twisted imports
from twisted.internet import defer
from twisted.application import service, internet
from twisted.python import util
from twisted.python import log
from twisted import cred
import twisted.cred.portal
# Sibling imports
from twisted.mail import protocols, smtp
# System imports
import os
from zope.interface import implements, Interface
class DomainWithDefaultDict:
'''Simulate a dictionary with a default value for non-existing keys.
'''
def __init__(self, domains, default):
self.domains = domains
self.default = default
def setDefaultDomain(self, domain):
self.default = domain
def has_key(self, name):
return 1
def fromkeys(klass, keys, value=None):
d = klass()
for k in keys:
d[k] = value
return d
fromkeys = classmethod(fromkeys)
def __contains__(self, name):
return 1
def __getitem__(self, name):
return self.domains.get(name, self.default)
def __setitem__(self, name, value):
self.domains[name] = value
def __delitem__(self, name):
del self.domains[name]
def __iter__(self):
return iter(self.domains)
def __len__(self):
return len(self.domains)
def __str__(self):
return '<DomainWithDefaultsDict %s>' % (self.domains,)
def __repr__(self):
return 'DomainWithDefaultsDict(%s)>' % (self.domains,)
def get(self, key, default=None):
return self.domains.get(key, default)
def copy(self):
return DomainWithDefaultsDict(self.domains.copy(), self.default)
def iteritems(self):
return self.domains.iteritems()
def iterkeys(self):
return self.domains.iterkeys()
def itervalues(self):
return self.domains.itervalues()
def keys(self):
return self.domains.keys()
def values(self):
return self.domains.values()
def items(self):
return self.domains.items()
def popitem(self):
return self.domains.popitem()
def update(self, other):
return self.domains.update(other)
def clear(self):
return self.domains.clear()
def setdefault(self, key, default):
return self.domains.setdefault(key, default)
class IDomain(Interface):
"""An email domain."""
def exists(user):
"""
Check whether or not the specified user exists in this domain.
@type user: C{twisted.protocols.smtp.User}
@param user: The user to check
@rtype: No-argument callable
@return: A C{Deferred} which becomes, or a callable which
takes no arguments and returns an object implementing C{IMessage}.
This will be called and the returned object used to deliver the
message when it arrives.
@raise twisted.protocols.smtp.SMTPBadRcpt: Raised if the given
user does not exist in this domain.
"""
def addUser(user, password):
"""Add a username/password to this domain."""
def startMessage(user):
"""Create and return a new message to be delivered to the given user.
DEPRECATED. Implement validateTo() correctly instead.
"""
def getCredentialsCheckers():
"""Return a list of ICredentialsChecker implementors for this domain.
"""
class IAliasableDomain(IDomain):
def setAliasGroup(aliases):
"""Set the group of defined aliases for this domain
@type aliases: C{dict}
@param aliases: Mapping of domain names to objects implementing
C{IAlias}
"""
def exists(user, memo=None):
"""
Check whether or not the specified user exists in this domain.
@type user: C{twisted.protocols.smtp.User}
@param user: The user to check
@type memo: C{dict}
@param memo: A record of the addresses already considered while
resolving aliases. The default value should be used by all
external code.
@rtype: No-argument callable
@return: A C{Deferred} which becomes, or a callable which
takes no arguments and returns an object implementing C{IMessage}.
This will be called and the returned object used to deliver the
message when it arrives.
@raise twisted.protocols.smtp.SMTPBadRcpt: Raised if the given
user does not exist in this domain.
"""
class BounceDomain:
"""A domain in which no user exists.
This can be used to block off certain domains.
"""
implements(IDomain)
def exists(self, user):
raise smtp.SMTPBadRcpt(user)
def willRelay(self, user, protocol):
return False
def addUser(self, user, password):
pass
def startMessage(self, user):
raise AssertionError, "No code should ever call this method for any reason"
def getCredentialsCheckers(self):
return []
class FileMessage:
"""A file we can write an email too."""
implements(smtp.IMessage)
def __init__(self, fp, name, finalName):
self.fp = fp
self.name = name
self.finalName = finalName
def lineReceived(self, line):
self.fp.write(line+'\n')
def eomReceived(self):
self.fp.close()
os.rename(self.name, self.finalName)
return defer.succeed(self.finalName)
def connectionLost(self):
self.fp.close()
os.remove(self.name)
class MailService(service.MultiService):
"""An email service."""
queue = None
domains = None
portals = None
aliases = None
smtpPortal = None
def __init__(self):
service.MultiService.__init__(self)
# Domains and portals for "client" protocols - POP3, IMAP4, etc
self.domains = DomainWithDefaultDict({}, BounceDomain())
self.portals = {}
self.monitor = FileMonitoringService()
self.monitor.setServiceParent(self)
self.smtpPortal = cred.portal.Portal(self)
def getPOP3Factory(self):
return protocols.POP3Factory(self)
def getSMTPFactory(self):
return protocols.SMTPFactory(self, self.smtpPortal)
def getESMTPFactory(self):
return protocols.ESMTPFactory(self, self.smtpPortal)
def addDomain(self, name, domain):
portal = cred.portal.Portal(domain)
map(portal.registerChecker, domain.getCredentialsCheckers())
self.domains[name] = domain
self.portals[name] = portal
if self.aliases and IAliasableDomain.providedBy(domain):
domain.setAliasGroup(self.aliases)
def setQueue(self, queue):
"""Set the queue for outgoing emails."""
self.queue = queue
def requestAvatar(self, avatarId, mind, *interfaces):
if smtp.IMessageDelivery in interfaces:
a = protocols.ESMTPDomainDelivery(self, avatarId)
return smtp.IMessageDelivery, a, lambda: None
raise NotImplementedError()
def lookupPortal(self, name):
return self.portals[name]
def defaultPortal(self):
return self.portals['']
class FileMonitoringService(internet.TimerService):
def __init__(self):
self.files = []
self.intervals = iter(util.IntervalDifferential([], 60))
def startService(self):
service.Service.startService(self)
self._setupMonitor()
def _setupMonitor(self):
from twisted.internet import reactor
t, self.index = self.intervals.next()
self._call = reactor.callLater(t, self._monitor)
def stopService(self):
service.Service.stopService(self)
if self._call:
self._call.cancel()
self._call = None
def monitorFile(self, name, callback, interval=10):
try:
mtime = os.path.getmtime(name)
except:
mtime = 0
self.files.append([interval, name, callback, mtime])
self.intervals.addInterval(interval)
def unmonitorFile(self, name):
for i in range(len(self.files)):
if name == self.files[i][1]:
self.intervals.removeInterval(self.files[i][0])
del self.files[i]
break
def _monitor(self):
self._call = None
if self.index is not None:
name, callback, mtime = self.files[self.index][1:]
try:
now = os.path.getmtime(name)
except:
now = 0
if now > mtime:
log.msg("%s changed, notifying listener" % (name,))
self.files[self.index][3] = now
callback(name)
self._setupMonitor() | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/mail/mail.py | mail.py |
from twisted.mail import smtp
from twisted.python import log
from twisted.internet.address import UNIXAddress
import os
try:
import cPickle as pickle
except ImportError:
import pickle
class DomainQueuer:
"""An SMTP domain which add messages to a queue intended for relaying."""
def __init__(self, service, authenticated=False):
self.service = service
self.authed = authenticated
def exists(self, user):
"""Check whether we will relay
Call overridable willRelay method
"""
if self.willRelay(user.dest, user.protocol):
# The most cursor form of verification of the addresses
orig = filter(None, str(user.orig).split('@', 1))
dest = filter(None, str(user.dest).split('@', 1))
if len(orig) == 2 and len(dest) == 2:
return lambda: self.startMessage(user)
raise smtp.SMTPBadRcpt(user)
def willRelay(self, address, protocol):
"""Check whether we agree to relay
The default is to relay for all connections over UNIX
sockets and all connections from localhost.
"""
peer = protocol.transport.getPeer()
return self.authed or isinstance(peer, UNIXAddress) or peer.host == '127.0.0.1'
def startMessage(self, user):
"""Add envelope to queue and returns ISMTPMessage."""
queue = self.service.queue
envelopeFile, smtpMessage = queue.createNewMessage()
try:
log.msg('Queueing mail %r -> %r' % (str(user.orig), str(user.dest)))
pickle.dump([str(user.orig), str(user.dest)], envelopeFile)
finally:
envelopeFile.close()
return smtpMessage
class RelayerMixin:
# XXX - This is -totally- bogus
# It opens about a -hundred- -billion- files
# and -leaves- them open!
def loadMessages(self, messagePaths):
self.messages = []
self.names = []
for message in messagePaths:
fp = open(message+'-H')
try:
messageContents = pickle.load(fp)
finally:
fp.close()
fp = open(message+'-D')
messageContents.append(fp)
self.messages.append(messageContents)
self.names.append(message)
def getMailFrom(self):
if not self.messages:
return None
return self.messages[0][0]
def getMailTo(self):
if not self.messages:
return None
return [self.messages[0][1]]
def getMailData(self):
if not self.messages:
return None
return self.messages[0][2]
def sentMail(self, code, resp, numOk, addresses, log):
"""Since we only use one recipient per envelope, this
will be called with 0 or 1 addresses. We probably want
to do something with the error message if we failed.
"""
if code in smtp.SUCCESS:
# At least one, i.e. all, recipients successfully delivered
os.remove(self.names[0]+'-D')
os.remove(self.names[0]+'-H')
del self.messages[0]
del self.names[0]
class SMTPRelayer(RelayerMixin, smtp.SMTPClient):
def __init__(self, messagePaths, *args, **kw):
smtp.SMTPClient.__init__(self, *args, **kw)
self.loadMessages(messagePaths)
class ESMTPRelayer(RelayerMixin, smtp.ESMTPClient):
def __init__(self, messagePaths, *args, **kw):
smtp.ESMTPClient.__init__(self, *args, **kw)
self.loadMessages(messagePaths) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/mail/relay.py | relay.py |
import string
import base64
import binascii
import md5
import warnings
from zope.interface import implements, Interface
from twisted.mail import smtp
from twisted.protocols import basic
from twisted.protocols import policies
from twisted.internet import task
from twisted.internet import defer
from twisted.internet import interfaces
from twisted.python import log
from twisted import cred
import twisted.cred.error
import twisted.cred.credentials
##
## Authentication
##
class APOPCredentials:
implements(cred.credentials.IUsernamePassword)
def __init__(self, magic, username, digest):
self.magic = magic
self.username = username
self.digest = digest
def checkPassword(self, password):
seed = self.magic + password
myDigest = md5.new(seed).hexdigest()
return myDigest == self.digest
class _HeadersPlusNLines:
def __init__(self, f, n):
self.f = f
self.n = n
self.linecount = 0
self.headers = 1
self.done = 0
self.buf = ''
def read(self, bytes):
if self.done:
return ''
data = self.f.read(bytes)
if not data:
return data
if self.headers:
df, sz = data.find('\r\n\r\n'), 4
if df == -1:
df, sz = data.find('\n\n'), 2
if df != -1:
df += sz
val = data[:df]
data = data[df:]
self.linecount = 1
self.headers = 0
else:
val = ''
if self.linecount > 0:
dsplit = (self.buf+data).split('\n')
self.buf = dsplit[-1]
for ln in dsplit[:-1]:
if self.linecount > self.n:
self.done = 1
return val
val += (ln + '\n')
self.linecount += 1
return val
else:
return data
class _POP3MessageDeleted(Exception):
"""
Internal control-flow exception. Indicates the file of a deleted message
was requested.
"""
class POP3Error(Exception):
pass
class _IteratorBuffer(object):
bufSize = 0
def __init__(self, write, iterable, memoryBufferSize=None):
"""
Create a _IteratorBuffer.
@param write: A one-argument callable which will be invoked with a list
of strings which have been buffered.
@param iterable: The source of input strings as any iterable.
@param memoryBufferSize: The upper limit on buffered string length,
beyond which the buffer will be flushed to the writer.
"""
self.lines = []
self.write = write
self.iterator = iter(iterable)
if memoryBufferSize is None:
memoryBufferSize = 2 ** 16
self.memoryBufferSize = memoryBufferSize
def __iter__(self):
return self
def next(self):
try:
v = self.iterator.next()
except StopIteration:
if self.lines:
self.write(self.lines)
# Drop some references, in case they're edges in a cycle.
del self.iterator, self.lines, self.write
raise
else:
if v is not None:
self.lines.append(v)
self.bufSize += len(v)
if self.bufSize > self.memoryBufferSize:
self.write(self.lines)
self.lines = []
self.bufSize = 0
def iterateLineGenerator(proto, gen):
"""
Hook the given protocol instance up to the given iterator with an
_IteratorBuffer and schedule the result to be exhausted via the protocol.
@type proto: L{POP3}
@type gen: iterator
@rtype: L{twisted.internet.defer.Deferred}
"""
coll = _IteratorBuffer(proto.transport.writeSequence, gen)
return proto.schedule(coll)
def successResponse(response):
"""
Format the given object as a positive response.
"""
response = str(response)
return '+OK %s\r\n' % (response,)
def formatStatResponse(msgs):
"""
Format the list of message sizes appropriately for a STAT response.
Yields None until it finishes computing a result, then yields a str
instance that is suitable for use as a response to the STAT command.
Intended to be used with a L{twisted.internet.task.Cooperator}.
"""
i = 0
bytes = 0
for size in msgs:
i += 1
bytes += size
yield None
yield successResponse('%d %d' % (i, bytes))
def formatListLines(msgs):
"""
Format a list of message sizes appropriately for the lines of a LIST
response.
Yields str instances formatted appropriately for use as lines in the
response to the LIST command. Does not include the trailing '.'.
"""
i = 0
for size in msgs:
i += 1
yield '%d %d\r\n' % (i, size)
def formatListResponse(msgs):
"""
Format a list of message sizes appropriately for a complete LIST response.
Yields str instances formatted appropriately for use as a LIST command
response.
"""
yield successResponse(len(msgs))
for ele in formatListLines(msgs):
yield ele
yield '.\r\n'
def formatUIDListLines(msgs, getUidl):
"""
Format the list of message sizes appropriately for the lines of a UIDL
response.
Yields str instances formatted appropriately for use as lines in the
response to the UIDL command. Does not include the trailing '.'.
"""
for i, m in enumerate(msgs):
if m is not None:
uid = getUidl(i)
yield '%d %s\r\n' % (i + 1, uid)
def formatUIDListResponse(msgs, getUidl):
"""
Format a list of message sizes appropriately for a complete UIDL response.
Yields str instances formatted appropriately for use as a UIDL command
response.
"""
yield successResponse('')
for ele in formatUIDListLines(msgs, getUidl):
yield ele
yield '.\r\n'
class POP3(basic.LineOnlyReceiver, policies.TimeoutMixin):
"""
POP3 server protocol implementation.
@ivar portal: A reference to the L{twisted.cred.portal.Portal} instance we
will authenticate through.
@ivar factory: A L{twisted.mail.pop3.IServerFactory} which will be used to
determine some extended behavior of the server.
@ivar timeOut: An integer which defines the minimum amount of time which
may elapse without receiving any traffic after which the client will be
disconnected.
@ivar schedule: A one-argument callable which should behave like
L{twisted.internet.task.coiterate}.
"""
implements(interfaces.IProducer)
magic = None
_userIs = None
_onLogout = None
AUTH_CMDS = ['CAPA', 'USER', 'PASS', 'APOP', 'AUTH', 'RPOP', 'QUIT']
portal = None
factory = None
# The mailbox we're serving
mbox = None
# Set this pretty low -- POP3 clients are expected to log in, download
# everything, and log out.
timeOut = 300
# Current protocol state
state = "COMMAND"
# PIPELINE
blocked = None
# Cooperate and suchlike.
schedule = staticmethod(task.coiterate)
# Message index of the highest retrieved message.
_highest = 0
def connectionMade(self):
if self.magic is None:
self.magic = self.generateMagic()
self.successResponse(self.magic)
self.setTimeout(self.timeOut)
if getattr(self.factory, 'noisy', True):
log.msg("New connection from " + str(self.transport.getPeer()))
def connectionLost(self, reason):
if self._onLogout is not None:
self._onLogout()
self._onLogout = None
self.setTimeout(None)
def generateMagic(self):
return smtp.messageid()
def successResponse(self, message=''):
self.transport.write(successResponse(message))
def failResponse(self, message=''):
self.sendLine('-ERR ' + str(message))
# def sendLine(self, line):
# print 'S:', repr(line)
# basic.LineOnlyReceiver.sendLine(self, line)
def lineReceived(self, line):
# print 'C:', repr(line)
self.resetTimeout()
getattr(self, 'state_' + self.state)(line)
def _unblock(self, _):
commands = self.blocked
self.blocked = None
while commands and self.blocked is None:
cmd, args = commands.pop(0)
self.processCommand(cmd, *args)
if self.blocked is not None:
self.blocked.extend(commands)
def state_COMMAND(self, line):
try:
return self.processCommand(*line.split(' '))
except (ValueError, AttributeError, POP3Error, TypeError), e:
log.err()
self.failResponse('bad protocol or server: %s: %s' % (e.__class__.__name__, e))
def processCommand(self, command, *args):
if self.blocked is not None:
self.blocked.append((command, args))
return
command = string.upper(command)
authCmd = command in self.AUTH_CMDS
if not self.mbox and not authCmd:
raise POP3Error("not authenticated yet: cannot do " + command)
f = getattr(self, 'do_' + command, None)
if f:
return f(*args)
raise POP3Error("Unknown protocol command: " + command)
def listCapabilities(self):
baseCaps = [
"TOP",
"USER",
"UIDL",
"PIPELINE",
"CELERITY",
"AUSPEX",
"POTENCE",
]
if IServerFactory.providedBy(self.factory):
# Oh my god. We can't just loop over a list of these because
# each has spectacularly different return value semantics!
try:
v = self.factory.cap_IMPLEMENTATION()
except NotImplementedError:
pass
except:
log.err()
else:
baseCaps.append("IMPLEMENTATION " + str(v))
try:
v = self.factory.cap_EXPIRE()
except NotImplementedError:
pass
except:
log.err()
else:
if v is None:
v = "NEVER"
if self.factory.perUserExpiration():
if self.mbox:
v = str(self.mbox.messageExpiration)
else:
v = str(v) + " USER"
v = str(v)
baseCaps.append("EXPIRE " + v)
try:
v = self.factory.cap_LOGIN_DELAY()
except NotImplementedError:
pass
except:
log.err()
else:
if self.factory.perUserLoginDelay():
if self.mbox:
v = str(self.mbox.loginDelay)
else:
v = str(v) + " USER"
v = str(v)
baseCaps.append("LOGIN-DELAY " + v)
try:
v = self.factory.challengers
except AttributeError:
pass
except:
log.err()
else:
baseCaps.append("SASL " + ' '.join(v.keys()))
return baseCaps
def do_CAPA(self):
self.successResponse("I can do the following:")
for cap in self.listCapabilities():
self.sendLine(cap)
self.sendLine(".")
def do_AUTH(self, args=None):
if not getattr(self.factory, 'challengers', None):
self.failResponse("AUTH extension unsupported")
return
if args is None:
self.successResponse("Supported authentication methods:")
for a in self.factory.challengers:
self.sendLine(a.upper())
self.sendLine(".")
return
auth = self.factory.challengers.get(args.strip().upper())
if not self.portal or not auth:
self.failResponse("Unsupported SASL selected")
return
self._auth = auth()
chal = self._auth.getChallenge()
self.sendLine('+ ' + base64.encodestring(chal).rstrip('\n'))
self.state = 'AUTH'
def state_AUTH(self, line):
self.state = "COMMAND"
try:
parts = base64.decodestring(line).split(None, 1)
except binascii.Error:
self.failResponse("Invalid BASE64 encoding")
else:
if len(parts) != 2:
self.failResponse("Invalid AUTH response")
return
self._auth.username = parts[0]
self._auth.response = parts[1]
d = self.portal.login(self._auth, None, IMailbox)
d.addCallback(self._cbMailbox, parts[0])
d.addErrback(self._ebMailbox)
d.addErrback(self._ebUnexpected)
def do_APOP(self, user, digest):
d = defer.maybeDeferred(self.authenticateUserAPOP, user, digest)
d.addCallbacks(self._cbMailbox, self._ebMailbox, callbackArgs=(user,)
).addErrback(self._ebUnexpected)
def _cbMailbox(self, (interface, avatar, logout), user):
if interface is not IMailbox:
self.failResponse('Authentication failed')
log.err("_cbMailbox() called with an interface other than IMailbox")
return
self.mbox = avatar
self._onLogout = logout
self.successResponse('Authentication succeeded')
if getattr(self.factory, 'noisy', True):
log.msg("Authenticated login for " + user)
def _ebMailbox(self, failure):
failure = failure.trap(cred.error.LoginDenied, cred.error.LoginFailed)
if issubclass(failure, cred.error.LoginDenied):
self.failResponse("Access denied: " + str(failure))
elif issubclass(failure, cred.error.LoginFailed):
self.failResponse('Authentication failed')
if getattr(self.factory, 'noisy', True):
log.msg("Denied login attempt from " + str(self.transport.getPeer()))
def _ebUnexpected(self, failure):
self.failResponse('Server error: ' + failure.getErrorMessage())
log.err(failure)
def do_USER(self, user):
self._userIs = user
self.successResponse('USER accepted, send PASS')
def do_PASS(self, password):
if self._userIs is None:
self.failResponse("USER required before PASS")
return
user = self._userIs
self._userIs = None
d = defer.maybeDeferred(self.authenticateUserPASS, user, password)
d.addCallbacks(self._cbMailbox, self._ebMailbox, callbackArgs=(user,)
).addErrback(self._ebUnexpected)
def _longOperation(self, d):
# Turn off timeouts and block further processing until the Deferred
# fires, then reverse those changes.
timeOut = self.timeOut
self.setTimeout(None)
self.blocked = []
d.addCallback(self._unblock)
d.addCallback(lambda ign: self.setTimeout(timeOut))
return d
def _coiterate(self, gen):
return self.schedule(_IteratorBuffer(self.transport.writeSequence, gen))
def do_STAT(self):
d = defer.maybeDeferred(self.mbox.listMessages)
def cbMessages(msgs):
return self._coiterate(formatStatResponse(msgs))
def ebMessages(err):
self.failResponse(err.getErrorMessage())
log.msg("Unexpected do_STAT failure:")
log.err(err)
return self._longOperation(d.addCallbacks(cbMessages, ebMessages))
def do_LIST(self, i=None):
if i is None:
d = defer.maybeDeferred(self.mbox.listMessages)
def cbMessages(msgs):
return self._coiterate(formatListResponse(msgs))
def ebMessages(err):
self.failResponse(err.getErrorMessage())
log.msg("Unexpected do_LIST failure:")
log.err(err)
return self._longOperation(d.addCallbacks(cbMessages, ebMessages))
else:
try:
i = int(i)
if i < 1:
raise ValueError()
except ValueError:
self.failResponse("Invalid message-number: %r" % (i,))
else:
d = defer.maybeDeferred(self.mbox.listMessages, i - 1)
def cbMessage(msg):
self.successResponse('%d %d' % (i, msg))
def ebMessage(err):
errcls = err.check(ValueError, IndexError)
if errcls is not None:
if errcls is IndexError:
# IndexError was supported for a while, but really
# shouldn't be. One error condition, one exception
# type.
warnings.warn(
"twisted.mail.pop3.IMailbox.listMessages may not "
"raise IndexError for out-of-bounds message numbers: "
"raise ValueError instead.",
PendingDeprecationWarning)
self.failResponse("Invalid message-number: %r" % (i,))
else:
self.failResponse(err.getErrorMessage())
log.msg("Unexpected do_LIST failure:")
log.err(err)
return self._longOperation(d.addCallbacks(cbMessage, ebMessage))
def do_UIDL(self, i=None):
if i is None:
d = defer.maybeDeferred(self.mbox.listMessages)
def cbMessages(msgs):
return self._coiterate(formatUIDListResponse(msgs, self.mbox.getUidl))
def ebMessages(err):
self.failResponse(err.getErrorMessage())
log.msg("Unexpected do_UIDL failure:")
log.err(err)
return self._longOperation(d.addCallbacks(cbMessages, ebMessages))
else:
try:
i = int(i)
if i < 1:
raise ValueError()
except ValueError:
self.failResponse("Bad message number argument")
else:
try:
msg = self.mbox.getUidl(i - 1)
except IndexError:
# XXX TODO See above comment regarding IndexError.
warnings.warn(
"twisted.mail.pop3.IMailbox.getUidl may not "
"raise IndexError for out-of-bounds message numbers: "
"raise ValueError instead.",
PendingDeprecationWarning)
self.failResponse("Bad message number argument")
except ValueError:
self.failResponse("Bad message number argument")
else:
self.successResponse(str(msg))
def _getMessageFile(self, i):
"""
Retrieve the size and contents of a given message, as a two-tuple.
@param i: The number of the message to operate on. This is a base-ten
string representation starting at 1.
@return: A Deferred which fires with a two-tuple of an integer and a
file-like object.
"""
try:
msg = int(i) - 1
if msg < 0:
raise ValueError()
except ValueError:
self.failResponse("Bad message number argument")
return defer.succeed(None)
sizeDeferred = defer.maybeDeferred(self.mbox.listMessages, msg)
def cbMessageSize(size):
if not size:
return defer.fail(_POP3MessageDeleted())
fileDeferred = defer.maybeDeferred(self.mbox.getMessage, msg)
fileDeferred.addCallback(lambda fObj: (size, fObj))
return fileDeferred
def ebMessageSomething(err):
errcls = err.check(_POP3MessageDeleted, ValueError, IndexError)
if errcls is _POP3MessageDeleted:
self.failResponse("message deleted")
elif errcls in (ValueError, IndexError):
if errcls is IndexError:
# XXX TODO See above comment regarding IndexError.
warnings.warn(
"twisted.mail.pop3.IMailbox.listMessages may not "
"raise IndexError for out-of-bounds message numbers: "
"raise ValueError instead.",
PendingDeprecationWarning)
self.failResponse("Bad message number argument")
else:
log.msg("Unexpected _getMessageFile failure:")
log.err(err)
return None
sizeDeferred.addCallback(cbMessageSize)
sizeDeferred.addErrback(ebMessageSomething)
return sizeDeferred
def _sendMessageContent(self, i, fpWrapper, successResponse):
d = self._getMessageFile(i)
def cbMessageFile(info):
if info is None:
# Some error occurred - a failure response has been sent
# already, just give up.
return
self._highest = max(self._highest, int(i))
resp, fp = info
fp = fpWrapper(fp)
self.successResponse(successResponse(resp))
s = basic.FileSender()
d = s.beginFileTransfer(fp, self.transport, self.transformChunk)
def cbFileTransfer(lastsent):
if lastsent != '\n':
line = '\r\n.'
else:
line = '.'
self.sendLine(line)
def ebFileTransfer(err):
self.transport.loseConnection()
log.msg("Unexpected error in _sendMessageContent:")
log.err(err)
d.addCallback(cbFileTransfer)
d.addErrback(ebFileTransfer)
return d
return self._longOperation(d.addCallback(cbMessageFile))
def do_TOP(self, i, size):
try:
size = int(size)
if size < 0:
raise ValueError
except ValueError:
self.failResponse("Bad line count argument")
else:
return self._sendMessageContent(
i,
lambda fp: _HeadersPlusNLines(fp, size),
lambda size: "Top of message follows")
def do_RETR(self, i):
return self._sendMessageContent(
i,
lambda fp: fp,
lambda size: "%d" % (size,))
def transformChunk(self, chunk):
return chunk.replace('\n', '\r\n').replace('\r\n.', '\r\n..')
def finishedFileTransfer(self, lastsent):
if lastsent != '\n':
line = '\r\n.'
else:
line = '.'
self.sendLine(line)
def do_DELE(self, i):
i = int(i)-1
self.mbox.deleteMessage(i)
self.successResponse()
def do_NOOP(self):
"""Perform no operation. Return a success code"""
self.successResponse()
def do_RSET(self):
"""Unset all deleted message flags"""
try:
self.mbox.undeleteMessages()
except:
log.err()
self.failResponse()
else:
self._highest = 0
self.successResponse()
def do_LAST(self):
"""
Return the index of the highest message yet downloaded.
"""
self.successResponse(self._highest)
def do_RPOP(self, user):
self.failResponse('permission denied, sucker')
def do_QUIT(self):
if self.mbox:
self.mbox.sync()
self.successResponse()
self.transport.loseConnection()
def authenticateUserAPOP(self, user, digest):
"""Perform authentication of an APOP login.
@type user: C{str}
@param user: The name of the user attempting to log in.
@type digest: C{str}
@param digest: The response string with which the user replied.
@rtype: C{Deferred}
@return: A deferred whose callback is invoked if the login is
successful, and whose errback will be invoked otherwise. The
callback will be passed a 3-tuple consisting of IMailbox,
an object implementing IMailbox, and a zero-argument callable
to be invoked when this session is terminated.
"""
if self.portal is not None:
return self.portal.login(
APOPCredentials(self.magic, user, digest),
None,
IMailbox
)
raise cred.error.UnauthorizedLogin()
def authenticateUserPASS(self, user, password):
"""Perform authentication of a username/password login.
@type user: C{str}
@param user: The name of the user attempting to log in.
@type password: C{str}
@param password: The password to attempt to authenticate with.
@rtype: C{Deferred}
@return: A deferred whose callback is invoked if the login is
successful, and whose errback will be invoked otherwise. The
callback will be passed a 3-tuple consisting of IMailbox,
an object implementing IMailbox, and a zero-argument callable
to be invoked when this session is terminated.
"""
if self.portal is not None:
return self.portal.login(
cred.credentials.UsernamePassword(user, password),
None,
IMailbox
)
raise cred.error.UnauthorizedLogin()
class IServerFactory(Interface):
"""Interface for querying additional parameters of this POP3 server.
Any cap_* method may raise NotImplementedError if the particular
capability is not supported. If cap_EXPIRE() does not raise
NotImplementedError, perUserExpiration() must be implemented, otherwise
they are optional. If cap_LOGIN_DELAY() is implemented,
perUserLoginDelay() must be implemented, otherwise they are optional.
@ivar challengers: A dictionary mapping challenger names to classes
implementing C{IUsernameHashedPassword}.
"""
def cap_IMPLEMENTATION():
"""Return a string describing this POP3 server implementation."""
def cap_EXPIRE():
"""Return the minimum number of days messages are retained."""
def perUserExpiration():
"""Indicate whether message expiration is per-user.
@return: True if it is, false otherwise.
"""
def cap_LOGIN_DELAY():
"""Return the minimum number of seconds between client logins."""
def perUserLoginDelay():
"""Indicate whether the login delay period is per-user.
@return: True if it is, false otherwise.
"""
class IMailbox(Interface):
"""
@type loginDelay: C{int}
@ivar loginDelay: The number of seconds between allowed logins for the
user associated with this mailbox. None
@type messageExpiration: C{int}
@ivar messageExpiration: The number of days messages in this mailbox will
remain on the server before being deleted.
"""
def listMessages(index=None):
"""Retrieve the size of one or more messages.
@type index: C{int} or C{None}
@param index: The number of the message for which to retrieve the
size (starting at 0), or None to retrieve the size of all messages.
@rtype: C{int} or any iterable of C{int} or a L{Deferred} which fires
with one of these.
@return: The number of octets in the specified message, or an iterable
of integers representing the number of octets in all the messages. Any
value which would have referred to a deleted message should be set to
0.
@raise ValueError: if C{index} is greater than the index of any message
in the mailbox.
"""
def getMessage(index):
"""Retrieve a file-like object for a particular message.
@type index: C{int}
@param index: The number of the message to retrieve
@rtype: A file-like object
@return: A file containing the message data with lines delimited by
C{\n}.
"""
def getUidl(index):
"""Get a unique identifier for a particular message.
@type index: C{int}
@param index: The number of the message for which to retrieve a UIDL
@rtype: C{str}
@return: A string of printable characters uniquely identifying for all
time the specified message.
@raise ValueError: if C{index} is greater than the index of any message
in the mailbox.
"""
def deleteMessage(index):
"""Delete a particular message.
This must not change the number of messages in this mailbox. Further
requests for the size of deleted messages should return 0. Further
requests for the message itself may raise an exception.
@type index: C{int}
@param index: The number of the message to delete.
"""
def undeleteMessages():
"""
Undelete any messages which have been marked for deletion since the
most recent L{sync} call.
Any message which can be undeleted should be returned to its
original position in the message sequence and retain its original
UID.
"""
def sync():
"""Perform checkpointing.
This method will be called to indicate the mailbox should attempt to
clean up any remaining deleted messages.
"""
class Mailbox:
implements(IMailbox)
def listMessages(self, i=None):
return []
def getMessage(self, i):
raise ValueError
def getUidl(self, i):
raise ValueError
def deleteMessage(self, i):
raise ValueError
def undeleteMessages(self):
pass
def sync(self):
pass
NONE, SHORT, FIRST_LONG, LONG = range(4)
NEXT = {}
NEXT[NONE] = NONE
NEXT[SHORT] = NONE
NEXT[FIRST_LONG] = LONG
NEXT[LONG] = NONE
class POP3Client(basic.LineOnlyReceiver):
mode = SHORT
command = 'WELCOME'
import re
welcomeRe = re.compile('<(.*)>')
def __init__(self):
import warnings
warnings.warn("twisted.mail.pop3.POP3Client is deprecated, "
"please use twisted.mail.pop3.AdvancedPOP3Client "
"instead.", DeprecationWarning,
stacklevel=3)
def sendShort(self, command, params=None):
if params is not None:
self.sendLine('%s %s' % (command, params))
else:
self.sendLine(command)
self.command = command
self.mode = SHORT
def sendLong(self, command, params):
if params:
self.sendLine('%s %s' % (command, params))
else:
self.sendLine(command)
self.command = command
self.mode = FIRST_LONG
def handle_default(self, line):
if line[:-4] == '-ERR':
self.mode = NONE
def handle_WELCOME(self, line):
code, data = line.split(' ', 1)
if code != '+OK':
self.transport.loseConnection()
else:
m = self.welcomeRe.match(line)
if m:
self.welcomeCode = m.group(1)
def _dispatch(self, command, default, *args):
try:
method = getattr(self, 'handle_'+command, default)
if method is not None:
method(*args)
except:
log.err()
def lineReceived(self, line):
if self.mode == SHORT or self.mode == FIRST_LONG:
self.mode = NEXT[self.mode]
self._dispatch(self.command, self.handle_default, line)
elif self.mode == LONG:
if line == '.':
self.mode = NEXT[self.mode]
self._dispatch(self.command+'_end', None)
return
if line[:1] == '.':
line = line[1:]
self._dispatch(self.command+"_continue", None, line)
def apopAuthenticate(self, user, password, magic):
digest = md5.new(magic + password).hexdigest()
self.apop(user, digest)
def apop(self, user, digest):
self.sendLong('APOP', ' '.join((user, digest)))
def retr(self, i):
self.sendLong('RETR', i)
def dele(self, i):
self.sendShort('DELE', i)
def list(self, i=''):
self.sendLong('LIST', i)
def uidl(self, i=''):
self.sendLong('UIDL', i)
def user(self, name):
self.sendShort('USER', name)
def pass_(self, pass_):
self.sendShort('PASS', pass_)
def quit(self):
self.sendShort('QUIT')
from twisted.mail.pop3client import POP3Client as AdvancedPOP3Client
from twisted.mail.pop3client import POP3ClientError
from twisted.mail.pop3client import InsecureAuthenticationDisallowed
from twisted.mail.pop3client import ServerErrorResponse
from twisted.mail.pop3client import LineTooLong
__all__ = [
# Interfaces
'IMailbox', 'IServerFactory',
# Exceptions
'POP3Error', 'POP3ClientError', 'InsecureAuthenticationDisallowed',
'ServerErrorResponse', 'LineTooLong',
# Protocol classes
'POP3', 'POP3Client', 'AdvancedPOP3Client',
# Misc
'APOPCredentials', 'Mailbox'] | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/mail/pop3.py | pop3.py |
from __future__ import generators
# Twisted imports
from twisted.copyright import longversion
from twisted.protocols import basic
from twisted.protocols import policies
from twisted.internet import protocol
from twisted.internet import defer
from twisted.internet import error
from twisted.internet import reactor
from twisted.internet.interfaces import ITLSTransport
from twisted.python import log
from twisted.python import util
from twisted.python import failure
from twisted import cred
import twisted.cred.checkers
import twisted.cred.credentials
from twisted.python.runtime import platform
# System imports
import time, re, base64, types, socket, os, random, hmac
import MimeWriter, tempfile, rfc822
import warnings
import binascii
from zope.interface import implements, Interface
try:
from email.base64MIME import encode as encode_base64
except ImportError:
def encode_base64(s, eol='\n'):
return s.encode('base64').rstrip() + eol
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
# Cache the hostname (XXX Yes - this is broken)
if platform.isMacOSX():
# On OS X, getfqdn() is ridiculously slow - use the
# probably-identical-but-sometimes-not gethostname() there.
DNSNAME = socket.gethostname()
else:
DNSNAME = socket.getfqdn()
# Used for fast success code lookup
SUCCESS = dict(map(None, range(200, 300), []))
class IMessageDelivery(Interface):
def receivedHeader(helo, origin, recipients):
"""
Generate the Received header for a message
@type helo: C{(str, str)}
@param helo: The argument to the HELO command and the client's IP
address.
@type origin: C{Address}
@param origin: The address the message is from
@type recipients: C{list} of L{User}
@param recipients: A list of the addresses for which this message
is bound.
@rtype: C{str}
@return: The full \"Received\" header string.
"""
def validateTo(user):
"""
Validate the address for which the message is destined.
@type user: C{User}
@param user: The address to validate.
@rtype: no-argument callable
@return: A C{Deferred} which becomes, or a callable which
takes no arguments and returns an object implementing C{IMessage}.
This will be called and the returned object used to deliver the
message when it arrives.
@raise SMTPBadRcpt: Raised if messages to the address are
not to be accepted.
"""
def validateFrom(helo, origin):
"""
Validate the address from which the message originates.
@type helo: C{(str, str)}
@param helo: The argument to the HELO command and the client's IP
address.
@type origin: C{Address}
@param origin: The address the message is from
@rtype: C{Deferred} or C{Address}
@return: C{origin} or a C{Deferred} whose callback will be
passed C{origin}.
@raise SMTPBadSender: Raised of messages from this address are
not to be accepted.
"""
class IMessageDeliveryFactory(Interface):
"""An alternate interface to implement for handling message delivery.
It is useful to implement this interface instead of L{IMessageDelivery}
directly because it allows the implementor to distinguish between
different messages delivery over the same connection. This can be
used to optimize delivery of a single message to multiple recipients,
something which cannot be done by L{IMessageDelivery} implementors
due to their lack of information.
"""
def getMessageDelivery():
"""Return an L{IMessageDelivery} object.
This will be called once per message.
"""
class SMTPError(Exception):
pass
class SMTPClientError(SMTPError):
"""Base class for SMTP client errors.
"""
def __init__(self, code, resp, log=None, addresses=None, isFatal=False, retry=False):
"""
@param code: The SMTP response code associated with this error.
@param resp: The string response associated with this error.
@param log: A string log of the exchange leading up to and including the error.
@param isFatal: A boolean indicating whether this connection can proceed
or not. If True, the connection will be dropped.
@param retry: A boolean indicating whether the delivery should be retried.
If True and the factory indicates further retries are desirable, they will
be attempted, otherwise the delivery will be failed.
"""
self.code = code
self.resp = resp
self.log = log
self.addresses = addresses
self.isFatal = isFatal
self.retry = retry
def __str__(self):
if self.code > 0:
res = ["%.3d %s" % (self.code, self.resp)]
else:
res = [self.resp]
if self.log:
res.append('')
res.append(self.log)
return '\n'.join(res)
class ESMTPClientError(SMTPClientError):
"""Base class for ESMTP client errors.
"""
class EHLORequiredError(ESMTPClientError):
"""The server does not support EHLO.
This is considered a non-fatal error (the connection will not be
dropped).
"""
class AUTHRequiredError(ESMTPClientError):
"""Authentication was required but the server does not support it.
This is considered a non-fatal error (the connection will not be
dropped).
"""
class TLSRequiredError(ESMTPClientError):
"""Transport security was required but the server does not support it.
This is considered a non-fatal error (the connection will not be
dropped).
"""
class AUTHDeclinedError(ESMTPClientError):
"""The server rejected our credentials.
Either the username, password, or challenge response
given to the server was rejected.
This is considered a non-fatal error (the connection will not be
dropped).
"""
class AuthenticationError(ESMTPClientError):
"""An error ocurred while authenticating.
Either the server rejected our request for authentication or the
challenge received was malformed.
This is considered a non-fatal error (the connection will not be
dropped).
"""
class TLSError(ESMTPClientError):
"""An error occurred while negiotiating for transport security.
This is considered a non-fatal error (the connection will not be
dropped).
"""
class SMTPConnectError(SMTPClientError):
"""Failed to connect to the mail exchange host.
This is considered a fatal error. A retry will be made.
"""
def __init__(self, code, resp, log=None, addresses=None, isFatal=True, retry=True):
SMTPClientError.__init__(self, code, resp, log, addresses, isFatal, retry)
class SMTPTimeoutError(SMTPClientError):
"""Failed to receive a response from the server in the expected time period.
This is considered a fatal error. A retry will be made.
"""
def __init__(self, code, resp, log=None, addresses=None, isFatal=True, retry=True):
SMTPClientError.__init__(self, code, resp, log, addresses, isFatal, retry)
class SMTPProtocolError(SMTPClientError):
"""The server sent a mangled response.
This is considered a fatal error. A retry will not be made.
"""
def __init__(self, code, resp, log=None, addresses=None, isFatal=True, retry=False):
SMTPClientError.__init__(self, code, resp, log, addresses, isFatal, retry)
class SMTPDeliveryError(SMTPClientError):
"""Indicates that a delivery attempt has had an error.
"""
class SMTPServerError(SMTPError):
def __init__(self, code, resp):
self.code = code
self.resp = resp
def __str__(self):
return "%.3d %s" % (self.code, self.resp)
class SMTPAddressError(SMTPServerError):
def __init__(self, addr, code, resp):
SMTPServerError.__init__(self, code, resp)
self.addr = Address(addr)
def __str__(self):
return "%.3d <%s>... %s" % (self.code, self.addr, self.resp)
class SMTPBadRcpt(SMTPAddressError):
def __init__(self, addr, code=550,
resp='Cannot receive for specified address'):
SMTPAddressError.__init__(self, addr, code, resp)
class SMTPBadSender(SMTPAddressError):
def __init__(self, addr, code=550, resp='Sender not acceptable'):
SMTPAddressError.__init__(self, addr, code, resp)
def rfc822date(timeinfo=None,local=1):
"""
Format an RFC-2822 compliant date string.
@param timeinfo: (optional) A sequence as returned by C{time.localtime()}
or C{time.gmtime()}. Default is now.
@param local: (optional) Indicates if the supplied time is local or
universal time, or if no time is given, whether now should be local or
universal time. Default is local, as suggested (SHOULD) by rfc-2822.
@returns: A string representing the time and date in RFC-2822 format.
"""
if not timeinfo:
if local:
timeinfo = time.localtime()
else:
timeinfo = time.gmtime()
if local:
if timeinfo[8]:
# DST
tz = -time.altzone
else:
tz = -time.timezone
(tzhr, tzmin) = divmod(abs(tz), 3600)
if tz:
tzhr *= int(abs(tz)/tz)
(tzmin, tzsec) = divmod(tzmin, 60)
else:
(tzhr, tzmin) = (0,0)
return "%s, %02d %s %04d %02d:%02d:%02d %+03d%02d" % (
['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][timeinfo[6]],
timeinfo[2],
['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][timeinfo[1] - 1],
timeinfo[0], timeinfo[3], timeinfo[4], timeinfo[5],
tzhr, tzmin)
def idGenerator():
i = 0
while True:
yield i
i += 1
def messageid(uniq=None, N=idGenerator().next):
"""Return a globally unique random string in RFC 2822 Message-ID format
<[email protected]>
Optional uniq string will be added to strenghten uniqueness if given.
"""
datetime = time.strftime('%Y%m%d%H%M%S', time.gmtime())
pid = os.getpid()
rand = random.randrange(2**31L-1)
if uniq is None:
uniq = ''
else:
uniq = '.' + uniq
return '<%s.%s.%s%s.%s@%s>' % (datetime, pid, rand, uniq, N(), DNSNAME)
def quoteaddr(addr):
"""Turn an email address, possibly with realname part etc, into
a form suitable for and SMTP envelope.
"""
if isinstance(addr, Address):
return '<%s>' % str(addr)
res = rfc822.parseaddr(addr)
if res == (None, None):
# It didn't parse, use it as-is
return '<%s>' % str(addr)
else:
return '<%s>' % str(res[1])
COMMAND, DATA, AUTH = 'COMMAND', 'DATA', 'AUTH'
class AddressError(SMTPError):
"Parse error in address"
# Character classes for parsing addresses
atom = r"[-A-Za-z0-9!\#$%&'*+/=?^_`{|}~]"
class Address:
"""Parse and hold an RFC 2821 address.
Source routes are stipped and ignored, UUCP-style bang-paths
and %-style routing are not parsed.
@type domain: C{str}
@ivar domain: The domain within which this address resides.
@type local: C{str}
@ivar local: The local (\"user\") portion of this address.
"""
tstring = re.compile(r'''( # A string of
(?:"[^"]*" # quoted string
|\\. # backslash-escaped characted
|''' + atom + r''' # atom character
)+|.) # or any single character''',re.X)
atomre = re.compile(atom) # match any one atom character
def __init__(self, addr, defaultDomain=None):
if isinstance(addr, User):
addr = addr.dest
if isinstance(addr, Address):
self.__dict__ = addr.__dict__.copy()
return
elif not isinstance(addr, types.StringTypes):
addr = str(addr)
self.addrstr = addr
# Tokenize
atl = filter(None,self.tstring.split(addr))
local = []
domain = []
while atl:
if atl[0] == '<':
if atl[-1] != '>':
raise AddressError, "Unbalanced <>"
atl = atl[1:-1]
elif atl[0] == '@':
atl = atl[1:]
if not local:
# Source route
while atl and atl[0] != ':':
# remove it
atl = atl[1:]
if not atl:
raise AddressError, "Malformed source route"
atl = atl[1:] # remove :
elif domain:
raise AddressError, "Too many @"
else:
# Now in domain
domain = ['']
elif len(atl[0]) == 1 and not self.atomre.match(atl[0]) and atl[0] != '.':
raise AddressError, "Parse error at %r of %r" % (atl[0], (addr, atl))
else:
if not domain:
local.append(atl[0])
else:
domain.append(atl[0])
atl = atl[1:]
self.local = ''.join(local)
self.domain = ''.join(domain)
if self.local != '' and self.domain == '':
if defaultDomain is None:
defaultDomain = DNSNAME
self.domain = defaultDomain
dequotebs = re.compile(r'\\(.)')
def dequote(self,addr):
"""Remove RFC-2821 quotes from address."""
res = []
atl = filter(None,self.tstring.split(str(addr)))
for t in atl:
if t[0] == '"' and t[-1] == '"':
res.append(t[1:-1])
elif '\\' in t:
res.append(self.dequotebs.sub(r'\1',t))
else:
res.append(t)
return ''.join(res)
def __str__(self):
if self.local or self.domain:
return '@'.join((self.local, self.domain))
else:
return ''
def __repr__(self):
return "%s.%s(%s)" % (self.__module__, self.__class__.__name__,
repr(str(self)))
class User:
"""Hold information about and SMTP message recipient,
including information on where the message came from
"""
def __init__(self, destination, helo, protocol, orig):
host = getattr(protocol, 'host', None)
self.dest = Address(destination, host)
self.helo = helo
self.protocol = protocol
if isinstance(orig, Address):
self.orig = orig
else:
self.orig = Address(orig, host)
def __getstate__(self):
"""Helper for pickle.
protocol isn't picklabe, but we want User to be, so skip it in
the pickle.
"""
return { 'dest' : self.dest,
'helo' : self.helo,
'protocol' : None,
'orig' : self.orig }
def __str__(self):
return str(self.dest)
class IMessage(Interface):
"""Interface definition for messages that can be sent via SMTP."""
def lineReceived(line):
"""handle another line"""
def eomReceived():
"""handle end of message
return a deferred. The deferred should be called with either:
callback(string) or errback(error)
"""
def connectionLost():
"""handle message truncated
semantics should be to discard the message
"""
class SMTP(basic.LineOnlyReceiver, policies.TimeoutMixin):
"""SMTP server-side protocol."""
timeout = 600
host = DNSNAME
portal = None
# Control whether we log SMTP events
noisy = True
# A factory for IMessageDelivery objects. If an
# avatar implementing IMessageDeliveryFactory can
# be acquired from the portal, it will be used to
# create a new IMessageDelivery object for each
# message which is received.
deliveryFactory = None
# An IMessageDelivery object. A new instance is
# used for each message received if we can get an
# IMessageDeliveryFactory from the portal. Otherwise,
# a single instance is used throughout the lifetime
# of the connection.
delivery = None
# Cred cleanup function.
_onLogout = None
def __init__(self, delivery=None, deliveryFactory=None):
self.mode = COMMAND
self._from = None
self._helo = None
self._to = []
self.delivery = delivery
self.deliveryFactory = deliveryFactory
def timeoutConnection(self):
msg = '%s Timeout. Try talking faster next time!' % (self.host,)
self.sendCode(421, msg)
self.transport.loseConnection()
def greeting(self):
return '%s NO UCE NO UBE NO RELAY PROBES' % (self.host,)
def connectionMade(self):
# Ensure user-code always gets something sane for _helo
peer = self.transport.getPeer()
try:
host = peer.host
except AttributeError: # not an IPv4Address
host = str(peer)
self._helo = (None, host)
self.sendCode(220, self.greeting())
self.setTimeout(self.timeout)
def sendCode(self, code, message=''):
"Send an SMTP code with a message."
lines = message.splitlines()
lastline = lines[-1:]
for line in lines[:-1]:
self.sendLine('%3.3d-%s' % (code, line))
self.sendLine('%3.3d %s' % (code,
lastline and lastline[0] or ''))
def lineReceived(self, line):
self.resetTimeout()
return getattr(self, 'state_' + self.mode)(line)
def state_COMMAND(self, line):
# Ignore leading and trailing whitespace, as well as an arbitrary
# amount of whitespace between the command and its argument, though
# it is not required by the protocol, for it is a nice thing to do.
line = line.strip()
parts = line.split(None, 1)
if parts:
method = self.lookupMethod(parts[0]) or self.do_UNKNOWN
if len(parts) == 2:
method(parts[1])
else:
method('')
else:
self.sendSyntaxError()
def sendSyntaxError(self):
self.sendCode(500, 'Error: bad syntax')
def lookupMethod(self, command):
return getattr(self, 'do_' + command.upper(), None)
def lineLengthExceeded(self, line):
if self.mode is DATA:
for message in self.__messages:
message.connectionLost()
self.mode = COMMAND
del self.__messages
self.sendCode(500, 'Line too long')
def do_UNKNOWN(self, rest):
self.sendCode(500, 'Command not implemented')
def do_HELO(self, rest):
peer = self.transport.getPeer()
try:
host = peer.host
except AttributeError:
host = str(peer)
self._helo = (rest, host)
self._from = None
self._to = []
self.sendCode(250, '%s Hello %s, nice to meet you' % (self.host, host))
def do_QUIT(self, rest):
self.sendCode(221, 'See you later')
self.transport.loseConnection()
# A string of quoted strings, backslash-escaped character or
# atom characters + '@.,:'
qstring = r'("[^"]*"|\\.|' + atom + r'|[@.,:])+'
mail_re = re.compile(r'''\s*FROM:\s*(?P<path><> # Empty <>
|<''' + qstring + r'''> # <addr>
|''' + qstring + r''' # addr
)\s*(\s(?P<opts>.*))? # Optional WS + ESMTP options
$''',re.I|re.X)
rcpt_re = re.compile(r'\s*TO:\s*(?P<path><' + qstring + r'''> # <addr>
|''' + qstring + r''' # addr
)\s*(\s(?P<opts>.*))? # Optional WS + ESMTP options
$''',re.I|re.X)
def do_MAIL(self, rest):
if self._from:
self.sendCode(503,"Only one sender per message, please")
return
# Clear old recipient list
self._to = []
m = self.mail_re.match(rest)
if not m:
self.sendCode(501, "Syntax error")
return
try:
addr = Address(m.group('path'), self.host)
except AddressError, e:
self.sendCode(553, str(e))
return
validated = defer.maybeDeferred(self.validateFrom, self._helo, addr)
validated.addCallbacks(self._cbFromValidate, self._ebFromValidate)
def _cbFromValidate(self, from_, code=250, msg='Sender address accepted'):
self._from = from_
self.sendCode(code, msg)
def _ebFromValidate(self, failure):
if failure.check(SMTPBadSender):
self.sendCode(failure.value.code,
'Cannot receive from specified address %s: %s'
% (quoteaddr(failure.value.addr), failure.value.resp))
elif failure.check(SMTPServerError):
self.sendCode(failure.value.code, failure.value.resp)
else:
log.err(failure, "SMTP sender validation failure")
self.sendCode(
451,
'Requested action aborted: local error in processing')
def do_RCPT(self, rest):
if not self._from:
self.sendCode(503, "Must have sender before recipient")
return
m = self.rcpt_re.match(rest)
if not m:
self.sendCode(501, "Syntax error")
return
try:
user = User(m.group('path'), self._helo, self, self._from)
except AddressError, e:
self.sendCode(553, str(e))
return
d = defer.maybeDeferred(self.validateTo, user)
d.addCallbacks(
self._cbToValidate,
self._ebToValidate,
callbackArgs=(user,)
)
def _cbToValidate(self, to, user=None, code=250, msg='Recipient address accepted'):
if user is None:
user = to
self._to.append((user, to))
self.sendCode(code, msg)
def _ebToValidate(self, failure):
if failure.check(SMTPBadRcpt, SMTPServerError):
self.sendCode(failure.value.code, failure.value.resp)
else:
log.err(failure)
self.sendCode(
451,
'Requested action aborted: local error in processing'
)
def _disconnect(self, msgs):
for msg in msgs:
try:
msg.connectionLost()
except:
log.msg("msg raised exception from connectionLost")
log.err()
def do_DATA(self, rest):
if self._from is None or (not self._to):
self.sendCode(503, 'Must have valid receiver and originator')
return
self.mode = DATA
helo, origin = self._helo, self._from
recipients = self._to
self._from = None
self._to = []
self.datafailed = None
msgs = []
for (user, msgFunc) in recipients:
try:
msg = msgFunc()
rcvdhdr = self.receivedHeader(helo, origin, [user])
if rcvdhdr:
msg.lineReceived(rcvdhdr)
msgs.append(msg)
except SMTPServerError, e:
self.sendCode(e.code, e.resp)
self.mode = COMMAND
self._disconnect(msgs)
return
except:
log.err()
self.sendCode(550, "Internal server error")
self.mode = COMMAND
self._disconnect(msgs)
return
self.__messages = msgs
self.__inheader = self.__inbody = 0
self.sendCode(354, 'Continue')
if self.noisy:
fmt = 'Receiving message for delivery: from=%s to=%s'
log.msg(fmt % (origin, [str(u) for (u, f) in recipients]))
def connectionLost(self, reason):
# self.sendCode(421, 'Dropping connection.') # This does nothing...
# Ideally, if we (rather than the other side) lose the connection,
# we should be able to tell the other side that we are going away.
# RFC-2821 requires that we try.
if self.mode is DATA:
try:
for message in self.__messages:
try:
message.connectionLost()
except:
log.err()
del self.__messages
except AttributeError:
pass
if self._onLogout:
self._onLogout()
self._onLogout = None
self.setTimeout(None)
def do_RSET(self, rest):
self._from = None
self._to = []
self.sendCode(250, 'I remember nothing.')
def dataLineReceived(self, line):
if line[:1] == '.':
if line == '.':
self.mode = COMMAND
if self.datafailed:
self.sendCode(self.datafailed.code,
self.datafailed.resp)
return
if not self.__messages:
self._messageHandled("thrown away")
return
defer.DeferredList([
m.eomReceived() for m in self.__messages
], consumeErrors=True).addCallback(self._messageHandled
)
del self.__messages
return
line = line[1:]
if self.datafailed:
return
try:
# Add a blank line between the generated Received:-header
# and the message body if the message comes in without any
# headers
if not self.__inheader and not self.__inbody:
if ':' in line:
self.__inheader = 1
elif line:
for message in self.__messages:
message.lineReceived('')
self.__inbody = 1
if not line:
self.__inbody = 1
for message in self.__messages:
message.lineReceived(line)
except SMTPServerError, e:
self.datafailed = e
for message in self.__messages:
message.connectionLost()
state_DATA = dataLineReceived
def _messageHandled(self, resultList):
failures = 0
for (success, result) in resultList:
if not success:
failures += 1
log.err(result)
if failures:
msg = 'Could not send e-mail'
L = len(resultList)
if L > 1:
msg += ' (%d failures out of %d recipients)' % (failures, L)
self.sendCode(550, msg)
else:
self.sendCode(250, 'Delivery in progress')
def _cbAnonymousAuthentication(self, (iface, avatar, logout)):
"""
Save the state resulting from a successful anonymous cred login.
"""
if issubclass(iface, IMessageDeliveryFactory):
self.deliveryFactory = avatar
self.delivery = None
elif issubclass(iface, IMessageDelivery):
self.deliveryFactory = None
self.delivery = avatar
else:
raise RuntimeError("%s is not a supported interface" % (iface.__name__,))
self._onLogout = logout
self.challenger = None
# overridable methods:
def validateFrom(self, helo, origin):
"""
Validate the address from which the message originates.
@type helo: C{(str, str)}
@param helo: The argument to the HELO command and the client's IP
address.
@type origin: C{Address}
@param origin: The address the message is from
@rtype: C{Deferred} or C{Address}
@return: C{origin} or a C{Deferred} whose callback will be
passed C{origin}.
@raise SMTPBadSender: Raised of messages from this address are
not to be accepted.
"""
if self.deliveryFactory is not None:
self.delivery = self.deliveryFactory.getMessageDelivery()
if self.delivery is not None:
return defer.maybeDeferred(self.delivery.validateFrom,
helo, origin)
# No login has been performed, no default delivery object has been
# provided: try to perform an anonymous login and then invoke this
# method again.
if self.portal:
result = self.portal.login(
cred.credentials.Anonymous(),
None,
IMessageDeliveryFactory, IMessageDelivery)
def ebAuthentication(err):
"""
Translate cred exceptions into SMTP exceptions so that the
protocol code which invokes C{validateFrom} can properly report
the failure.
"""
if err.check(cred.error.UnauthorizedLogin):
exc = SMTPBadSender(origin)
elif err.check(cred.error.UnhandledCredentials):
exc = SMTPBadSender(
origin, resp="Unauthenticated senders not allowed")
else:
return err
return defer.fail(exc)
result.addCallbacks(
self._cbAnonymousAuthentication, ebAuthentication)
def continueValidation(ignored):
"""
Re-attempt from address validation.
"""
return self.validateFrom(helo, origin)
result.addCallback(continueValidation)
return result
raise SMTPBadSender(origin)
def validateTo(self, user):
"""
Validate the address for which the message is destined.
@type user: C{User}
@param user: The address to validate.
@rtype: no-argument callable
@return: A C{Deferred} which becomes, or a callable which
takes no arguments and returns an object implementing C{IMessage}.
This will be called and the returned object used to deliver the
message when it arrives.
@raise SMTPBadRcpt: Raised if messages to the address are
not to be accepted.
"""
if self.delivery is not None:
return self.delivery.validateTo(user)
raise SMTPBadRcpt(user)
def receivedHeader(self, helo, origin, recipients):
if self.delivery is not None:
return self.delivery.receivedHeader(helo, origin, recipients)
heloStr = ""
if helo[0]:
heloStr = " helo=%s" % (helo[0],)
domain = self.transport.getHost().host
from_ = "from %s ([%s]%s)" % (helo[0], helo[1], heloStr)
by = "by %s with %s (%s)" % (domain,
self.__class__.__name__,
longversion)
for_ = "for %s; %s" % (' '.join(map(str, recipients)),
rfc822date())
return "Received: %s\n\t%s\n\t%s" % (from_, by, for_)
def startMessage(self, recipients):
if self.delivery:
return self.delivery.startMessage(recipients)
return []
class SMTPFactory(protocol.ServerFactory):
"""Factory for SMTP."""
# override in instances or subclasses
domain = DNSNAME
timeout = 600
protocol = SMTP
portal = None
def __init__(self, portal = None):
self.portal = portal
def buildProtocol(self, addr):
p = protocol.ServerFactory.buildProtocol(self, addr)
p.portal = self.portal
p.host = self.domain
return p
class SMTPClient(basic.LineReceiver, policies.TimeoutMixin):
"""SMTP client for sending emails."""
# If enabled then log SMTP client server communication
debug = True
# Number of seconds to wait before timing out a connection. If
# None, perform no timeout checking.
timeout = None
def __init__(self, identity, logsize=10):
self.identity = identity or ''
self.toAddressesResult = []
self.successAddresses = []
self._from = None
self.resp = []
self.code = -1
self.log = util.LineLog(logsize)
def sendLine(self, line):
# Log sendLine only if you are in debug mode for performance
if self.debug:
self.log.append('>>> ' + line)
basic.LineReceiver.sendLine(self,line)
def connectionMade(self):
self.setTimeout(self.timeout)
self._expected = [ 220 ]
self._okresponse = self.smtpState_helo
self._failresponse = self.smtpConnectionFailed
def connectionLost(self, reason=protocol.connectionDone):
"""We are no longer connected"""
self.setTimeout(None)
self.mailFile = None
def timeoutConnection(self):
self.sendError(
SMTPTimeoutError(-1,
"Timeout waiting for SMTP server response",
self.log))
def lineReceived(self, line):
self.resetTimeout()
# Log lineReceived only if you are in debug mode for performance
if self.debug:
self.log.append('<<< ' + line)
why = None
try:
self.code = int(line[:3])
except ValueError:
# This is a fatal error and will disconnect the transport lineReceived will not be called again
self.sendError(SMTPProtocolError(-1, "Invalid response from SMTP server: %s" % line, self.log.str()))
return
if line[0] == '0':
# Verbose informational message, ignore it
return
self.resp.append(line[4:])
if line[3:4] == '-':
# continuation
return
if self.code in self._expected:
why = self._okresponse(self.code,'\n'.join(self.resp))
else:
why = self._failresponse(self.code,'\n'.join(self.resp))
self.code = -1
self.resp = []
return why
def smtpConnectionFailed(self, code, resp):
self.sendError(SMTPConnectError(code, resp, self.log.str()))
def smtpTransferFailed(self, code, resp):
if code < 0:
self.sendError(SMTPProtocolError(code, resp, self.log.str()))
else:
self.smtpState_msgSent(code, resp)
def smtpState_helo(self, code, resp):
self.sendLine('HELO ' + self.identity)
self._expected = SUCCESS
self._okresponse = self.smtpState_from
def smtpState_from(self, code, resp):
self._from = self.getMailFrom()
self._failresponse = self.smtpTransferFailed
if self._from is not None:
self.sendLine('MAIL FROM:%s' % quoteaddr(self._from))
self._expected = [250]
self._okresponse = self.smtpState_to
else:
# All messages have been sent, disconnect
self._disconnectFromServer()
def smtpState_disconnect(self, code, resp):
self.transport.loseConnection()
def smtpState_to(self, code, resp):
self.toAddresses = iter(self.getMailTo())
self.toAddressesResult = []
self.successAddresses = []
self._okresponse = self.smtpState_toOrData
self._expected = xrange(0,1000)
self.lastAddress = None
return self.smtpState_toOrData(0, '')
def smtpState_toOrData(self, code, resp):
if self.lastAddress is not None:
self.toAddressesResult.append((self.lastAddress, code, resp))
if code in SUCCESS:
self.successAddresses.append(self.lastAddress)
try:
self.lastAddress = self.toAddresses.next()
except StopIteration:
if self.successAddresses:
self.sendLine('DATA')
self._expected = [ 354 ]
self._okresponse = self.smtpState_data
else:
return self.smtpState_msgSent(code,'No recipients accepted')
else:
self.sendLine('RCPT TO:%s' % quoteaddr(self.lastAddress))
def smtpState_data(self, code, resp):
s = basic.FileSender()
s.beginFileTransfer(
self.getMailData(), self.transport, self.transformChunk
).addCallback(self.finishedFileTransfer)
self._expected = SUCCESS
self._okresponse = self.smtpState_msgSent
def smtpState_msgSent(self, code, resp):
if self._from is not None:
self.sentMail(code, resp, len(self.successAddresses),
self.toAddressesResult, self.log)
self.toAddressesResult = []
self._from = None
self.sendLine('RSET')
self._expected = SUCCESS
self._okresponse = self.smtpState_from
##
## Helpers for FileSender
##
def transformChunk(self, chunk):
return chunk.replace('\n', '\r\n').replace('\r\n.', '\r\n..')
def finishedFileTransfer(self, lastsent):
if lastsent != '\n':
line = '\r\n.'
else:
line = '.'
self.sendLine(line)
##
# these methods should be overriden in subclasses
def getMailFrom(self):
"""Return the email address the mail is from."""
raise NotImplementedError
def getMailTo(self):
"""Return a list of emails to send to."""
raise NotImplementedError
def getMailData(self):
"""Return file-like object containing data of message to be sent.
Lines in the file should be delimited by '\\n'.
"""
raise NotImplementedError
def sendError(self, exc):
"""
If an error occurs before a mail message is sent sendError will be
called. This base class method sends a QUIT if the error is
non-fatal and disconnects the connection.
@param exc: The SMTPClientError (or child class) raised
@type exc: C{SMTPClientError}
"""
assert isinstance(exc, SMTPClientError)
if exc.isFatal:
# If the error was fatal then the communication channel with the SMTP Server is
# broken so just close the transport connection
self.smtpState_disconnect(-1, None)
else:
self._disconnectFromServer()
def sentMail(self, code, resp, numOk, addresses, log):
"""Called when an attempt to send an email is completed.
If some addresses were accepted, code and resp are the response
to the DATA command. If no addresses were accepted, code is -1
and resp is an informative message.
@param code: the code returned by the SMTP Server
@param resp: The string response returned from the SMTP Server
@param numOK: the number of addresses accepted by the remote host.
@param addresses: is a list of tuples (address, code, resp) listing
the response to each RCPT command.
@param log: is the SMTP session log
"""
raise NotImplementedError
def _disconnectFromServer(self):
self._expected = xrange(0, 1000)
self._okresponse = self.smtpState_disconnect
self.sendLine('QUIT')
class ESMTPClient(SMTPClient):
# Fall back to HELO if the server does not support EHLO
heloFallback = True
# Refuse to proceed if authentication cannot be performed
requireAuthentication = False
# Refuse to proceed if TLS is not available
requireTransportSecurity = False
# Indicate whether or not our transport can be considered secure.
tlsMode = False
# ClientContextFactory to use for STARTTLS
context = None
def __init__(self, secret, contextFactory=None, *args, **kw):
SMTPClient.__init__(self, *args, **kw)
self.authenticators = []
self.secret = secret
self.context = contextFactory
self.tlsMode = False
def esmtpEHLORequired(self, code=-1, resp=None):
self.sendError(EHLORequiredError(502, "Server does not support ESMTP Authentication", self.log.str()))
def esmtpAUTHRequired(self, code=-1, resp=None):
tmp = []
for a in self.authenticators:
tmp.append(a.getName().upper())
auth = "[%s]" % ', '.join(tmp)
self.sendError(AUTHRequiredError(502, "Server does not support Client Authentication schemes %s" % auth,
self.log.str()))
def esmtpTLSRequired(self, code=-1, resp=None):
self.sendError(TLSRequiredError(502, "Server does not support secure communication via TLS / SSL",
self.log.str()))
def esmtpTLSFailed(self, code=-1, resp=None):
self.sendError(TLSError(code, "Could not complete the SSL/TLS handshake", self.log.str()))
def esmtpAUTHDeclined(self, code=-1, resp=None):
self.sendError(AUTHDeclinedError(code, resp, self.log.str()))
def esmtpAUTHMalformedChallenge(self, code=-1, resp=None):
str = "Login failed because the SMTP Server returned a malformed Authentication Challenge"
self.sendError(AuthenticationError(501, str, self.log.str()))
def esmtpAUTHServerError(self, code=-1, resp=None):
self.sendError(AuthenticationError(code, resp, self.log.str()))
def registerAuthenticator(self, auth):
"""Registers an Authenticator with the ESMTPClient. The ESMTPClient
will attempt to login to the SMTP Server in the order the
Authenticators are registered. The most secure Authentication
mechanism should be registered first.
@param auth: The Authentication mechanism to register
@type auth: class implementing C{IClientAuthentication}
"""
self.authenticators.append(auth)
def connectionMade(self):
SMTPClient.connectionMade(self)
self._okresponse = self.esmtpState_ehlo
def esmtpState_ehlo(self, code, resp):
self._expected = SUCCESS
self._okresponse = self.esmtpState_serverConfig
self._failresponse = self.esmtpEHLORequired
if self.heloFallback:
self._failresponse = self.smtpState_helo
self.sendLine('EHLO ' + self.identity)
def esmtpState_serverConfig(self, code, resp):
items = {}
for line in resp.splitlines():
e = line.split(None, 1)
if len(e) > 1:
items[e[0]] = e[1]
else:
items[e[0]] = None
if self.tlsMode:
self.authenticate(code, resp, items)
else:
self.tryTLS(code, resp, items)
def tryTLS(self, code, resp, items):
if self.context and 'STARTTLS' in items:
self._expected = [220]
self._okresponse = self.esmtpState_starttls
self._failresponse = self.esmtpTLSFailed
self.sendLine('STARTTLS')
elif self.requireTransportSecurity:
self.tlsMode = False
self.esmtpTLSRequired()
else:
self.tlsMode = False
self.authenticate(code, resp, items)
def esmtpState_starttls(self, code, resp):
try:
self.transport.startTLS(self.context)
self.tlsMode = True
except:
log.err()
self.esmtpTLSFailed(451)
# Send another EHLO once TLS has been started to
# get the TLS / AUTH schemes. Some servers only allow AUTH in TLS mode.
self.esmtpState_ehlo(code, resp)
def authenticate(self, code, resp, items):
if self.secret and items.get('AUTH'):
schemes = items['AUTH'].split()
tmpSchemes = {}
#XXX: May want to come up with a more efficient way to do this
for s in schemes:
tmpSchemes[s.upper()] = 1
for a in self.authenticators:
auth = a.getName().upper()
if auth in tmpSchemes:
self._authinfo = a
# Special condition handled
if auth == "PLAIN":
self._okresponse = self.smtpState_from
self._failresponse = self._esmtpState_plainAuth
self._expected = [235]
challenge = encode_base64(self._authinfo.challengeResponse(self.secret, 1), eol="")
self.sendLine('AUTH ' + auth + ' ' + challenge)
else:
self._expected = [334]
self._okresponse = self.esmtpState_challenge
# If some error occurs here, the server declined the AUTH
# before the user / password phase. This would be
# a very rare case
self._failresponse = self.esmtpAUTHServerError
self.sendLine('AUTH ' + auth)
return
if self.requireAuthentication:
self.esmtpAUTHRequired()
else:
self.smtpState_from(code, resp)
def _esmtpState_plainAuth(self, code, resp):
self._okresponse = self.smtpState_from
self._failresponse = self.esmtpAUTHDeclined
self._expected = [235]
challenge = encode_base64(self._authinfo.challengeResponse(self.secret, 2), eol="")
self.sendLine('AUTH PLAIN ' + challenge)
def esmtpState_challenge(self, code, resp):
auth = self._authinfo
del self._authinfo
self._authResponse(auth, resp)
def _authResponse(self, auth, challenge):
self._failresponse = self.esmtpAUTHDeclined
try:
challenge = base64.decodestring(challenge)
except binascii.Error, e:
# Illegal challenge, give up, then quit
self.sendLine('*')
self._okresponse = self.esmtpAUTHMalformedChallenge
self._failresponse = self.esmtpAUTHMalformedChallenge
else:
resp = auth.challengeResponse(self.secret, challenge)
self._expected = [235]
self._okresponse = self.smtpState_from
self.sendLine(encode_base64(resp, eol=""))
if auth.getName() == "LOGIN" and challenge == "Username:":
self._expected = [334]
self._authinfo = auth
self._okresponse = self.esmtpState_challenge
class ESMTP(SMTP):
ctx = None
canStartTLS = False
startedTLS = False
authenticated = False
def __init__(self, chal = None, contextFactory = None):
SMTP.__init__(self)
if chal is None:
chal = {}
self.challengers = chal
self.authenticated = False
self.ctx = contextFactory
def connectionMade(self):
SMTP.connectionMade(self)
self.canStartTLS = ITLSTransport.providedBy(self.transport)
self.canStartTLS = self.canStartTLS and (self.ctx is not None)
def greeting(self):
return SMTP.greeting(self) + ' ESMTP'
def extensions(self):
ext = {'AUTH': self.challengers.keys()}
if self.canStartTLS and not self.startedTLS:
ext['STARTTLS'] = None
return ext
def lookupMethod(self, command):
m = SMTP.lookupMethod(self, command)
if m is None:
m = getattr(self, 'ext_' + command.upper(), None)
return m
def listExtensions(self):
r = []
for (c, v) in self.extensions().iteritems():
if v is not None:
if v:
# Intentionally omit extensions with empty argument lists
r.append('%s %s' % (c, ' '.join(v)))
else:
r.append(c)
return '\n'.join(r)
def do_EHLO(self, rest):
peer = self.transport.getPeer().host
self._helo = (rest, peer)
self._from = None
self._to = []
self.sendCode(
250,
'%s Hello %s, nice to meet you\n%s' % (
self.host, peer,
self.listExtensions(),
)
)
def ext_STARTTLS(self, rest):
if self.startedTLS:
self.sendCode(503, 'TLS already negotiated')
elif self.ctx and self.canStartTLS:
self.sendCode(220, 'Begin TLS negotiation now')
self.transport.startTLS(self.ctx)
self.startedTLS = True
else:
self.sendCode(454, 'TLS not available')
def ext_AUTH(self, rest):
if self.authenticated:
self.sendCode(503, 'Already authenticated')
return
parts = rest.split(None, 1)
chal = self.challengers.get(parts[0].upper(), lambda: None)()
if not chal:
self.sendCode(504, 'Unrecognized authentication type')
return
self.mode = AUTH
self.challenger = chal
if len(parts) > 1:
chal.getChallenge() # Discard it, apparently the client does not
# care about it.
rest = parts[1]
else:
rest = ''
self.state_AUTH(rest)
def _cbAuthenticated(self, loginInfo):
"""
Save the state resulting from a successful cred login and mark this
connection as authenticated.
"""
result = SMTP._cbAnonymousAuthentication(self, loginInfo)
self.authenticated = True
return result
def _ebAuthenticated(self, reason):
"""
Handle cred login errors by translating them to the SMTP authenticate
failed. Translate all other errors into a generic SMTP error code and
log the failure for inspection. Stop all errors from propagating.
"""
self.challenge = None
if reason.check(cred.error.UnauthorizedLogin):
self.sendCode(535, 'Authentication failed')
else:
log.err(failure, "SMTP authentication failure")
self.sendCode(
451,
'Requested action aborted: local error in processing')
def state_AUTH(self, response):
"""
Handle one step of challenge/response authentication.
"""
if self.portal is None:
self.sendCode(454, 'Temporary authentication failure')
self.mode = COMMAND
return
if response == '':
challenge = self.challenger.getChallenge()
encoded = challenge.encode('base64')
self.sendCode(334, encoded)
return
if response == '*':
self.sendCode(501, 'Authentication aborted')
self.challenger = None
self.mode = COMMAND
return
try:
uncoded = response.decode('base64')
except binascii.Error:
self.sendCode(501, 'Syntax error in parameters or arguments')
self.challenger = None
self.mode = COMMAND
return
self.challenger.setResponse(uncoded)
if self.challenger.moreChallenges():
challenge = self.challenger.getChallenge()
coded = challenge.encode('base64')[:-1]
self.sendCode(334, coded)
return
self.mode = COMMAND
result = self.portal.login(
self.challenger, None,
IMessageDeliveryFactory, IMessageDelivery)
result.addCallback(self._cbAuthenticated)
result.addCallback(lambda ign: self.sendCode(235, 'Authentication successful.'))
result.addErrback(self._ebAuthenticated)
class SenderMixin:
"""Utility class for sending emails easily.
Use with SMTPSenderFactory or ESMTPSenderFactory.
"""
done = 0
def getMailFrom(self):
if not self.done:
self.done = 1
return str(self.factory.fromEmail)
else:
return None
def getMailTo(self):
return self.factory.toEmail
def getMailData(self):
return self.factory.file
def sendError(self, exc):
# Call the base class to close the connection with the SMTP server
SMTPClient.sendError(self, exc)
# Do not retry to connect to SMTP Server if:
# 1. No more retries left (This allows the correct error to be returned to the errorback)
# 2. retry is false
# 3. The error code is not in the 4xx range (Communication Errors)
if (self.factory.retries >= 0 or
(not exc.retry and not (exc.code >= 400 and exc.code < 500))):
self.factory.sendFinished = 1
self.factory.result.errback(exc)
def sentMail(self, code, resp, numOk, addresses, log):
# Do not retry, the SMTP server acknowledged the request
self.factory.sendFinished = 1
if code not in SUCCESS:
errlog = []
for addr, acode, aresp in addresses:
if code not in SUCCESS:
errlog.append("%s: %03d %s" % (addr, acode, aresp))
errlog.append(log.str())
exc = SMTPDeliveryError(code, resp, '\n'.join(errlog), addresses)
self.factory.result.errback(exc)
else:
self.factory.result.callback((numOk, addresses))
class SMTPSender(SenderMixin, SMTPClient):
pass
class SMTPSenderFactory(protocol.ClientFactory):
"""
Utility factory for sending emails easily.
"""
domain = DNSNAME
protocol = SMTPSender
def __init__(self, fromEmail, toEmail, file, deferred, retries=5,
timeout=None):
"""
@param fromEmail: The RFC 2821 address from which to send this
message.
@param toEmail: A sequence of RFC 2821 addresses to which to
send this message.
@param file: A file-like object containing the message to send.
@param deferred: A Deferred to callback or errback when sending
of this message completes.
@param retries: The number of times to retry delivery of this
message.
@param timeout: Period, in seconds, for which to wait for
server responses, or None to wait forever.
"""
assert isinstance(retries, (int, long))
if isinstance(toEmail, types.StringTypes):
toEmail = [toEmail]
self.fromEmail = Address(fromEmail)
self.nEmails = len(toEmail)
self.toEmail = iter(toEmail)
self.file = file
self.result = deferred
self.result.addBoth(self._removeDeferred)
self.sendFinished = 0
self.retries = -retries
self.timeout = timeout
def _removeDeferred(self, argh):
del self.result
return argh
def clientConnectionFailed(self, connector, err):
self._processConnectionError(connector, err)
def clientConnectionLost(self, connector, err):
self._processConnectionError(connector, err)
def _processConnectionError(self, connector, err):
if self.retries < self.sendFinished <= 0:
log.msg("SMTP Client retrying server. Retry: %s" % -self.retries)
connector.connect()
self.retries += 1
elif self.sendFinished <= 0:
# If we were unable to communicate with the SMTP server a ConnectionDone will be
# returned. We want a more clear error message for debugging
if err.check(error.ConnectionDone):
err.value = SMTPConnectError(-1, "Unable to connect to server.")
self.result.errback(err.value)
def buildProtocol(self, addr):
p = self.protocol(self.domain, self.nEmails*2+2)
p.factory = self
p.timeout = self.timeout
return p
class IClientAuthentication(Interface):
def getName():
"""Return an identifier associated with this authentication scheme.
@rtype: C{str}
"""
def challengeResponse(secret, challenge):
"""Generate a challenge response string"""
class CramMD5ClientAuthenticator:
implements(IClientAuthentication)
def __init__(self, user):
self.user = user
def getName(self):
return "CRAM-MD5"
def challengeResponse(self, secret, chal):
response = hmac.HMAC(secret, chal).hexdigest()
return '%s %s' % (self.user, response)
class LOGINAuthenticator:
implements(IClientAuthentication)
def __init__(self, user):
self.user = user
def getName(self):
return "LOGIN"
def challengeResponse(self, secret, chal):
if chal== "Username:":
return self.user
elif chal == 'Password:':
return secret
class PLAINAuthenticator:
implements(IClientAuthentication)
def __init__(self, user):
self.user = user
def getName(self):
return "PLAIN"
def challengeResponse(self, secret, chal=1):
if chal == 1:
return "%s\0%s\0%s" % (self.user, self.user, secret)
else:
return "%s\0%s" % (self.user, secret)
class ESMTPSender(SenderMixin, ESMTPClient):
requireAuthentication = True
requireTransportSecurity = True
def __init__(self, username, secret, contextFactory=None, *args, **kw):
self.heloFallback = 0
self.username = username
if contextFactory is None:
contextFactory = self._getContextFactory()
ESMTPClient.__init__(self, secret, contextFactory, *args, **kw)
self._registerAuthenticators()
def _registerAuthenticators(self):
# Register Authenticator in order from most secure to least secure
self.registerAuthenticator(CramMD5ClientAuthenticator(self.username))
self.registerAuthenticator(LOGINAuthenticator(self.username))
self.registerAuthenticator(PLAINAuthenticator(self.username))
def _getContextFactory(self):
if self.context is not None:
return self.context
try:
from twisted.internet import ssl
except ImportError:
return None
else:
try:
context = ssl.ClientContextFactory()
context.method = ssl.SSL.TLSv1_METHOD
return context
except AttributeError:
return None
class ESMTPSenderFactory(SMTPSenderFactory):
"""
Utility factory for sending emails easily.
"""
protocol = ESMTPSender
def __init__(self, username, password, fromEmail, toEmail, file,
deferred, retries=5, timeout=None,
contextFactory=None, heloFallback=False,
requireAuthentication=True,
requireTransportSecurity=True):
SMTPSenderFactory.__init__(self, fromEmail, toEmail, file, deferred, retries, timeout)
self.username = username
self.password = password
self._contextFactory = contextFactory
self._heloFallback = heloFallback
self._requireAuthentication = requireAuthentication
self._requireTransportSecurity = requireTransportSecurity
def buildProtocol(self, addr):
p = self.protocol(self.username, self.password, self._contextFactory, self.domain, self.nEmails*2+2)
p.heloFallback = self._heloFallback
p.requireAuthentication = self._requireAuthentication
p.requireTransportSecurity = self._requireTransportSecurity
p.factory = self
p.timeout = self.timeout
return p
def sendmail(smtphost, from_addr, to_addrs, msg, senderDomainName=None, port=25):
"""Send an email
This interface is intended to be a direct replacement for
smtplib.SMTP.sendmail() (with the obvious change that
you specify the smtphost as well). Also, ESMTP options
are not accepted, as we don't do ESMTP yet. I reserve the
right to implement the ESMTP options differently.
@param smtphost: The host the message should be sent to
@param from_addr: The (envelope) address sending this mail.
@param to_addrs: A list of addresses to send this mail to. A string will
be treated as a list of one address
@param msg: The message, including headers, either as a file or a string.
File-like objects need to support read() and close(). Lines must be
delimited by '\\n'. If you pass something that doesn't look like a
file, we try to convert it to a string (so you should be able to
pass an email.Message directly, but doing the conversion with
email.Generator manually will give you more control over the
process).
@param senderDomainName: Name by which to identify. If None, try
to pick something sane (but this depends on external configuration
and may not succeed).
@param port: Remote port to which to connect.
@rtype: L{Deferred}
@returns: A L{Deferred}, its callback will be called if a message is sent
to ANY address, the errback if no message is sent.
The callback will be called with a tuple (numOk, addresses) where numOk
is the number of successful recipient addresses and addresses is a list
of tuples (address, code, resp) giving the response to the RCPT command
for each address.
"""
if not hasattr(msg,'read'):
# It's not a file
msg = StringIO(str(msg))
d = defer.Deferred()
factory = SMTPSenderFactory(from_addr, to_addrs, msg, d)
if senderDomainName is not None:
factory.domain = senderDomainName
reactor.connectTCP(smtphost, port, factory)
return d
def sendEmail(smtphost, fromEmail, toEmail, content, headers = None, attachments = None, multipartbody = "mixed"):
"""Send an email, optionally with attachments.
@type smtphost: str
@param smtphost: hostname of SMTP server to which to connect
@type fromEmail: str
@param fromEmail: email address to indicate this email is from
@type toEmail: str
@param toEmail: email address to which to send this email
@type content: str
@param content: The body if this email.
@type headers: dict
@param headers: Dictionary of headers to include in the email
@type attachments: list of 3-tuples
@param attachments: Each 3-tuple should consist of the name of the
attachment, the mime-type of the attachment, and a string that is
the attachment itself.
@type multipartbody: str
@param multipartbody: The type of MIME multi-part body. Generally
either "mixed" (as in text and images) or "alternative" (html email
with a fallback to text/plain).
@rtype: Deferred
@return: The returned Deferred has its callback or errback invoked when
the mail is successfully sent or when an error occurs, respectively.
"""
warnings.warn("smtp.sendEmail may go away in the future.\n"
" Consider revising your code to use the email module\n"
" and smtp.sendmail.",
category=DeprecationWarning, stacklevel=2)
f = tempfile.TemporaryFile()
writer = MimeWriter.MimeWriter(f)
writer.addheader("Mime-Version", "1.0")
if headers:
# Setup the mail headers
for (header, value) in headers.items():
writer.addheader(header, value)
headkeys = [k.lower() for k in headers.keys()]
else:
headkeys = ()
# Add required headers if not present
if "message-id" not in headkeys:
writer.addheader("Message-ID", messageid())
if "date" not in headkeys:
writer.addheader("Date", rfc822date())
if "from" not in headkeys and "sender" not in headkeys:
writer.addheader("From", fromEmail)
if "to" not in headkeys and "cc" not in headkeys and "bcc" not in headkeys:
writer.addheader("To", toEmail)
writer.startmultipartbody(multipartbody)
# message body
part = writer.nextpart()
body = part.startbody("text/plain")
body.write(content)
if attachments is not None:
# add attachments
for (file, mime, attachment) in attachments:
part = writer.nextpart()
if mime.startswith('text'):
encoding = "7bit"
else:
attachment = base64.encodestring(attachment)
encoding = "base64"
part.addheader("Content-Transfer-Encoding", encoding)
body = part.startbody("%s; name=%s" % (mime, file))
body.write(attachment)
# finish
writer.lastpart()
# send message
f.seek(0, 0)
d = defer.Deferred()
factory = SMTPSenderFactory(fromEmail, toEmail, f, d)
reactor.connectTCP(smtphost, 25, factory)
return d
##
## Yerg. Codecs!
##
import codecs
def xtext_encode(s):
r = []
for ch in s:
o = ord(ch)
if ch == '+' or ch == '=' or o < 33 or o > 126:
r.append('+%02X' % o)
else:
r.append(ch)
return (''.join(r), len(s))
try:
from twisted.protocols._c_urlarg import unquote as _helper_unquote
except ImportError:
def xtext_decode(s):
r = []
i = 0
while i < len(s):
if s[i] == '+':
try:
r.append(chr(int(s[i + 1:i + 3], 16)))
except ValueError:
r.append(s[i:i + 3])
i += 3
else:
r.append(s[i])
i += 1
return (''.join(r), len(s))
else:
def xtext_decode(s):
return (_helper_unquote(s, '+'), len(s))
class xtextStreamReader(codecs.StreamReader):
def decode(self, s, errors='strict'):
return xtext_decode(s)
class xtextStreamWriter(codecs.StreamWriter):
def decode(self, s, errors='strict'):
return xtext_encode(s)
def xtext_codec(name):
if name == 'xtext':
return (xtext_encode, xtext_decode, xtextStreamReader, xtextStreamWriter)
codecs.register(xtext_codec) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/mail/smtp.py | smtp.py |
import re, md5
from twisted.python import log
from twisted.internet import defer
from twisted.protocols import basic
from twisted.protocols import policies
from twisted.internet import error
from twisted.internet import interfaces
OK = '+OK'
ERR = '-ERR'
class POP3ClientError(Exception):
"""Base class for all exceptions raised by POP3Client.
"""
class InsecureAuthenticationDisallowed(POP3ClientError):
"""Secure authentication was required but no mechanism could be found.
"""
class TLSError(POP3ClientError):
"""
Secure authentication was required but either the transport does
not support TLS or no TLS context factory was supplied.
"""
class TLSNotSupportedError(POP3ClientError):
"""
Secure authentication was required but the server does not support
TLS.
"""
class ServerErrorResponse(POP3ClientError):
"""The server returned an error response to a request.
"""
def __init__(self, reason, consumer=None):
POP3ClientError.__init__(self, reason)
self.consumer = consumer
class LineTooLong(POP3ClientError):
"""The server sent an extremely long line.
"""
class _ListSetter:
# Internal helper. POP3 responses sometimes occur in the
# form of a list of lines containing two pieces of data,
# a message index and a value of some sort. When a message
# is deleted, it is omitted from these responses. The
# setitem method of this class is meant to be called with
# these two values. In the cases where indexes are skipped,
# it takes care of padding out the missing values with None.
def __init__(self, L):
self.L = L
def setitem(self, (item, value)):
diff = item - len(self.L) + 1
if diff > 0:
self.L.extend([None] * diff)
self.L[item] = value
def _statXform(line):
# Parse a STAT response
numMsgs, totalSize = line.split(None, 1)
return int(numMsgs), int(totalSize)
def _listXform(line):
# Parse a LIST response
index, size = line.split(None, 1)
return int(index) - 1, int(size)
def _uidXform(line):
# Parse a UIDL response
index, uid = line.split(None, 1)
return int(index) - 1, uid
def _codeStatusSplit(line):
# Parse an +OK or -ERR response
parts = line.split(' ', 1)
if len(parts) == 1:
return parts[0], ''
return parts
def _dotUnquoter(line):
"""
C{'.'} characters which begin a line of a message are doubled to avoid
confusing with the terminating C{'.\\r\\n'} sequence. This function
unquotes them.
"""
if line.startswith('..'):
return line[1:]
return line
class POP3Client(basic.LineOnlyReceiver, policies.TimeoutMixin):
"""POP3 client protocol implementation class
Instances of this class provide a convenient, efficient API for
retrieving and deleting messages from a POP3 server.
@type startedTLS: C{bool}
@ivar startedTLS: Whether TLS has been negotiated successfully.
@type allowInsecureLogin: C{bool}
@ivar allowInsecureLogin: Indicate whether login() should be
allowed if the server offers no authentication challenge and if
our transport does not offer any protection via encryption.
@type serverChallenge: C{str} or C{None}
@ivar serverChallenge: Challenge received from the server
@type timeout: C{int}
@ivar timeout: Number of seconds to wait before timing out a
connection. If the number is <= 0, no timeout checking will be
performed.
"""
startedTLS = False
allowInsecureLogin = False
timeout = 0
serverChallenge = None
# Capabilities are not allowed to change during the session
# (except when TLS is negotiated), so cache the first response and
# use that for all later lookups
_capCache = None
# Regular expression to search for in the challenge string in the server
# greeting line.
_challengeMagicRe = re.compile('(<[^>]+>)')
# List of pending calls.
# We are a pipelining API but don't actually
# support pipelining on the network yet.
_blockedQueue = None
# The Deferred to which the very next result will go.
_waiting = None
# Whether we dropped the connection because of a timeout
_timedOut = False
# If the server sends an initial -ERR, this is the message it sent
# with it.
_greetingError = None
def _blocked(self, f, *a):
# Internal helper. If commands are being blocked, append
# the given command and arguments to a list and return a Deferred
# that will be chained with the return value of the function
# when it eventually runs. Otherwise, set up for commands to be
# blocked and return None.
if self._blockedQueue is not None:
d = defer.Deferred()
self._blockedQueue.append((d, f, a))
return d
self._blockedQueue = []
return None
def _unblock(self):
# Internal helper. Indicate that a function has completed.
# If there are blocked commands, run the next one. If there
# are not, set up for the next command to not be blocked.
if self._blockedQueue == []:
self._blockedQueue = None
elif self._blockedQueue is not None:
_blockedQueue = self._blockedQueue
self._blockedQueue = None
d, f, a = _blockedQueue.pop(0)
d2 = f(*a)
d2.chainDeferred(d)
# f is a function which uses _blocked (otherwise it wouldn't
# have gotten into the blocked queue), which means it will have
# re-set _blockedQueue to an empty list, so we can put the rest
# of the blocked queue back into it now.
self._blockedQueue.extend(_blockedQueue)
def sendShort(self, cmd, args):
# Internal helper. Send a command to which a short response
# is expected. Return a Deferred that fires when the response
# is received. Block all further commands from being sent until
# the response is received. Transition the state to SHORT.
d = self._blocked(self.sendShort, cmd, args)
if d is not None:
return d
if args:
self.sendLine(cmd + ' ' + args)
else:
self.sendLine(cmd)
self.state = 'SHORT'
self._waiting = defer.Deferred()
return self._waiting
def sendLong(self, cmd, args, consumer, xform):
# Internal helper. Send a command to which a multiline
# response is expected. Return a Deferred that fires when
# the entire response is received. Block all further commands
# from being sent until the entire response is received.
# Transition the state to LONG_INITIAL.
d = self._blocked(self.sendLong, cmd, args, consumer, xform)
if d is not None:
return d
if args:
self.sendLine(cmd + ' ' + args)
else:
self.sendLine(cmd)
self.state = 'LONG_INITIAL'
self._xform = xform
self._consumer = consumer
self._waiting = defer.Deferred()
return self._waiting
# Twisted protocol callback
def connectionMade(self):
if self.timeout > 0:
self.setTimeout(self.timeout)
self.state = 'WELCOME'
self._blockedQueue = []
def timeoutConnection(self):
self._timedOut = True
self.transport.loseConnection()
def connectionLost(self, reason):
if self.timeout > 0:
self.setTimeout(None)
if self._timedOut:
reason = error.TimeoutError()
elif self._greetingError:
reason = ServerErrorResponse(self._greetingError)
d = []
if self._waiting is not None:
d.append(self._waiting)
self._waiting = None
if self._blockedQueue is not None:
d.extend([deferred for (deferred, f, a) in self._blockedQueue])
self._blockedQueue = None
for w in d:
w.errback(reason)
def lineReceived(self, line):
if self.timeout > 0:
self.resetTimeout()
state = self.state
self.state = None
state = getattr(self, 'state_' + state)(line) or state
if self.state is None:
self.state = state
def lineLengthExceeded(self, buffer):
# XXX - We need to be smarter about this
if self._waiting is not None:
waiting, self._waiting = self._waiting, None
waiting.errback(LineTooLong())
self.transport.loseConnection()
# POP3 Client state logic - don't touch this.
def state_WELCOME(self, line):
# WELCOME is the first state. The server sends one line of text
# greeting us, possibly with an APOP challenge. Transition the
# state to WAITING.
code, status = _codeStatusSplit(line)
if code != OK:
self._greetingError = status
self.transport.loseConnection()
else:
m = self._challengeMagicRe.search(status)
if m is not None:
self.serverChallenge = m.group(1)
self.serverGreeting(status)
self._unblock()
return 'WAITING'
def state_WAITING(self, line):
# The server isn't supposed to send us anything in this state.
log.msg("Illegal line from server: " + repr(line))
def state_SHORT(self, line):
# This is the state we are in when waiting for a single
# line response. Parse it and fire the appropriate callback
# or errback. Transition the state back to WAITING.
deferred, self._waiting = self._waiting, None
self._unblock()
code, status = _codeStatusSplit(line)
if code == OK:
deferred.callback(status)
else:
deferred.errback(ServerErrorResponse(status))
return 'WAITING'
def state_LONG_INITIAL(self, line):
# This is the state we are in when waiting for the first
# line of a long response. Parse it and transition the
# state to LONG if it is an okay response; if it is an
# error response, fire an errback, clean up the things
# waiting for a long response, and transition the state
# to WAITING.
code, status = _codeStatusSplit(line)
if code == OK:
return 'LONG'
consumer = self._consumer
deferred = self._waiting
self._consumer = self._waiting = self._xform = None
self._unblock()
deferred.errback(ServerErrorResponse(status, consumer))
return 'WAITING'
def state_LONG(self, line):
# This is the state for each line of a long response.
# If it is the last line, finish things, fire the
# Deferred, and transition the state to WAITING.
# Otherwise, pass the line to the consumer.
if line == '.':
consumer = self._consumer
deferred = self._waiting
self._consumer = self._waiting = self._xform = None
self._unblock()
deferred.callback(consumer)
return 'WAITING'
else:
if self._xform is not None:
self._consumer(self._xform(line))
else:
self._consumer(line)
return 'LONG'
# Callbacks - override these
def serverGreeting(self, greeting):
"""Called when the server has sent us a greeting.
@type greeting: C{str} or C{None}
@param greeting: The status message sent with the server
greeting. For servers implementing APOP authentication, this
will be a challenge string. .
"""
# External API - call these (most of 'em anyway)
def startTLS(self, contextFactory=None):
"""
Initiates a 'STLS' request and negotiates the TLS / SSL
Handshake.
@type contextFactory: C{ssl.ClientContextFactory} @param
contextFactory: The context factory with which to negotiate
TLS. If C{None}, try to create a new one.
@return: A Deferred which fires when the transport has been
secured according to the given contextFactory, or which fails
if the transport cannot be secured.
"""
tls = interfaces.ITLSTransport(self.transport, None)
if tls is None:
return defer.fail(TLSError(
"POP3Client transport does not implement "
"interfaces.ITLSTransport"))
if contextFactory is None:
contextFactory = self._getContextFactory()
if contextFactory is None:
return defer.fail(TLSError(
"POP3Client requires a TLS context to "
"initiate the STLS handshake"))
d = self.capabilities()
d.addCallback(self._startTLS, contextFactory, tls)
return d
def _startTLS(self, caps, contextFactory, tls):
assert not self.startedTLS, "Client and Server are currently communicating via TLS"
if 'STLS' not in caps:
return defer.fail(TLSNotSupportedError(
"Server does not support secure communication "
"via TLS / SSL"))
d = self.sendShort('STLS', None)
d.addCallback(self._startedTLS, contextFactory, tls)
d.addCallback(lambda _: self.capabilities())
return d
def _startedTLS(self, result, context, tls):
self.transport = tls
self.transport.startTLS(context)
self._capCache = None
self.startedTLS = True
return result
def _getContextFactory(self):
try:
from twisted.internet import ssl
except ImportError:
return None
else:
context = ssl.ClientContextFactory()
context.method = ssl.SSL.TLSv1_METHOD
return context
def login(self, username, password):
"""Log into the server.
If APOP is available it will be used. Otherwise, if TLS is
available an 'STLS' session will be started and plaintext
login will proceed. Otherwise, if the instance attribute
allowInsecureLogin is set to True, insecure plaintext login
will proceed. Otherwise, InsecureAuthenticationDisallowed
will be raised (asynchronously).
@param username: The username with which to log in.
@param password: The password with which to log in.
@rtype: C{Deferred}
@return: A deferred which fires when login has
completed.
"""
d = self.capabilities()
d.addCallback(self._login, username, password)
return d
def _login(self, caps, username, password):
if self.serverChallenge is not None:
return self._apop(username, password, self.serverChallenge)
tryTLS = 'STLS' in caps
#If our transport supports switching to TLS, we might want to try to switch to TLS.
tlsableTransport = interfaces.ITLSTransport(self.transport, None) is not None
# If our transport is not already using TLS, we might want to try to switch to TLS.
nontlsTransport = interfaces.ISSLTransport(self.transport, None) is None
if not self.startedTLS and tryTLS and tlsableTransport and nontlsTransport:
d = self.startTLS()
d.addCallback(self._loginTLS, username, password)
return d
elif self.startedTLS or not nontlsTransport or self.allowInsecureLogin:
return self._plaintext(username, password)
else:
return defer.fail(InsecureAuthenticationDisallowed())
def _loginTLS(self, res, username, password):
return self._plaintext(username, password)
def _plaintext(self, username, password):
# Internal helper. Send a username/password pair, returning a Deferred
# that fires when both have succeeded or fails when the server rejects
# either.
return self.user(username).addCallback(lambda r: self.password(password))
def _apop(self, username, password, challenge):
# Internal helper. Computes and sends an APOP response. Returns
# a Deferred that fires when the server responds to the response.
digest = md5.new(challenge + password).hexdigest()
return self.apop(username, digest)
def apop(self, username, digest):
"""Perform APOP login.
This should be used in special circumstances only, when it is
known that the server supports APOP authentication, and APOP
authentication is absolutely required. For the common case,
use L{login} instead.
@param username: The username with which to log in.
@param digest: The challenge response to authenticate with.
"""
return self.sendShort('APOP', username + ' ' + digest)
def user(self, username):
"""Send the user command.
This performs the first half of plaintext login. Unless this
is absolutely required, use the L{login} method instead.
@param username: The username with which to log in.
"""
return self.sendShort('USER', username)
def password(self, password):
"""Send the password command.
This performs the second half of plaintext login. Unless this
is absolutely required, use the L{login} method instead.
@param password: The plaintext password with which to authenticate.
"""
return self.sendShort('PASS', password)
def delete(self, index):
"""Delete a message from the server.
@type index: C{int}
@param index: The index of the message to delete.
This is 0-based.
@rtype: C{Deferred}
@return: A deferred which fires when the delete command
is successful, or fails if the server returns an error.
"""
return self.sendShort('DELE', str(index + 1))
def _consumeOrSetItem(self, cmd, args, consumer, xform):
# Internal helper. Send a long command. If no consumer is
# provided, create a consumer that puts results into a list
# and return a Deferred that fires with that list when it
# is complete.
if consumer is None:
L = []
consumer = _ListSetter(L).setitem
return self.sendLong(cmd, args, consumer, xform).addCallback(lambda r: L)
return self.sendLong(cmd, args, consumer, xform)
def _consumeOrAppend(self, cmd, args, consumer, xform):
# Internal helper. Send a long command. If no consumer is
# provided, create a consumer that appends results to a list
# and return a Deferred that fires with that list when it is
# complete.
if consumer is None:
L = []
consumer = L.append
return self.sendLong(cmd, args, consumer, xform).addCallback(lambda r: L)
return self.sendLong(cmd, args, consumer, xform)
def capabilities(self, useCache=True):
"""Retrieve the capabilities supported by this server.
Not all servers support this command. If the server does not
support this, it is treated as though it returned a successful
response listing no capabilities. At some future time, this may be
changed to instead seek out information about a server's
capabilities in some other fashion (only if it proves useful to do
so, and only if there are servers still in use which do not support
CAPA but which do support POP3 extensions that are useful).
@type useCache: C{bool}
@param useCache: If set, and if capabilities have been
retrieved previously, just return the previously retrieved
results.
@return: A Deferred which fires with a C{dict} mapping C{str}
to C{None} or C{list}s of C{str}. For example::
C: CAPA
S: +OK Capability list follows
S: TOP
S: USER
S: SASL CRAM-MD5 KERBEROS_V4
S: RESP-CODES
S: LOGIN-DELAY 900
S: PIPELINING
S: EXPIRE 60
S: UIDL
S: IMPLEMENTATION Shlemazle-Plotz-v302
S: .
will be lead to a result of::
| {'TOP': None,
| 'USER': None,
| 'SASL': ['CRAM-MD5', 'KERBEROS_V4'],
| 'RESP-CODES': None,
| 'LOGIN-DELAY': ['900'],
| 'PIPELINING': None,
| 'EXPIRE': ['60'],
| 'UIDL': None,
| 'IMPLEMENTATION': ['Shlemazle-Plotz-v302']}
"""
if useCache and self._capCache is not None:
return defer.succeed(self._capCache)
cache = {}
def consume(line):
tmp = line.split()
if len(tmp) == 1:
cache[tmp[0]] = None
elif len(tmp) > 1:
cache[tmp[0]] = tmp[1:]
def capaNotSupported(err):
err.trap(ServerErrorResponse)
return None
def gotCapabilities(result):
self._capCache = cache
return cache
d = self._consumeOrAppend('CAPA', None, consume, None)
d.addErrback(capaNotSupported).addCallback(gotCapabilities)
return d
def noop(self):
"""Do nothing, with the help of the server.
No operation is performed. The returned Deferred fires when
the server responds.
"""
return self.sendShort("NOOP", None)
def reset(self):
"""Remove the deleted flag from any messages which have it.
The returned Deferred fires when the server responds.
"""
return self.sendShort("RSET", None)
def retrieve(self, index, consumer=None, lines=None):
"""Retrieve a message from the server.
If L{consumer} is not None, it will be called with
each line of the message as it is received. Otherwise,
the returned Deferred will be fired with a list of all
the lines when the message has been completely received.
"""
idx = str(index + 1)
if lines is None:
return self._consumeOrAppend('RETR', idx, consumer, _dotUnquoter)
return self._consumeOrAppend('TOP', '%s %d' % (idx, lines), consumer, _dotUnquoter)
def stat(self):
"""Get information about the size of this mailbox.
The returned Deferred will be fired with a tuple containing
the number or messages in the mailbox and the size (in bytes)
of the mailbox.
"""
return self.sendShort('STAT', None).addCallback(_statXform)
def listSize(self, consumer=None):
"""Retrieve a list of the size of all messages on the server.
If L{consumer} is not None, it will be called with two-tuples
of message index number and message size as they are received.
Otherwise, a Deferred which will fire with a list of B{only}
message sizes will be returned. For messages which have been
deleted, None will be used in place of the message size.
"""
return self._consumeOrSetItem('LIST', None, consumer, _listXform)
def listUID(self, consumer=None):
"""Retrieve a list of the UIDs of all messages on the server.
If L{consumer} is not None, it will be called with two-tuples
of message index number and message UID as they are received.
Otherwise, a Deferred which will fire with of list of B{only}
message UIDs will be returned. For messages which have been
deleted, None will be used in place of the message UID.
"""
return self._consumeOrSetItem('UIDL', None, consumer, _uidXform)
def quit(self):
"""Disconnect from the server.
"""
return self.sendShort('QUIT', None)
__all__ = [
# Exceptions
'InsecureAuthenticationDisallowed', 'LineTooLong', 'POP3ClientError',
'ServerErrorResponse', 'TLSError', 'TLSNotSupportedError',
# Protocol classes
'POP3Client'] | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/mail/pop3client.py | pop3client.py |
import os
import sys
from twisted.mail import mail
from twisted.mail import maildir
from twisted.mail import relay
from twisted.mail import relaymanager
from twisted.mail import alias
from twisted.python import usage
from twisted.cred import checkers
from twisted.application import internet
class Options(usage.Options):
synopsis = "Usage: mktap mail [options]"
optParameters = [
["pop3", "p", 8110, "Port to start the POP3 server on (0 to disable)."],
["pop3s", "S", 0, "Port to start the POP3-over-SSL server on (0 to disable)."],
["smtp", "s", 8025, "Port to start the SMTP server on (0 to disable)."],
["certificate", "c", None, "Certificate file to use for SSL connections"],
["relay", "R", None,
"Relay messages according to their envelope 'To', using the given"
"path as a queue directory."],
["hostname", "H", None, "The hostname by which to identify this server."],
]
optFlags = [
["esmtp", "E", "Use RFC 1425/1869 SMTP extensions"],
["disable-anonymous", None, "Disallow non-authenticated SMTP connections"],
]
zsh_actions = {"hostname" : "_hosts"}
longdesc = "This creates a mail.tap file that can be used by twistd."
def __init__(self):
usage.Options.__init__(self)
self.service = mail.MailService()
self.last_domain = None
def opt_passwordfile(self, filename):
"""Specify a file containing username:password login info for authenticated ESMTP connections."""
ch = checkers.OnDiskUsernamePasswordDatabase(filename)
self.service.smtpPortal.registerChecker(ch)
opt_P = opt_passwordfile
def opt_default(self):
"""Make the most recently specified domain the default domain."""
if self.last_domain:
self.service.addDomain('', self.last_domain)
else:
raise usage.UsageError("Specify a domain before specifying using --default")
opt_D = opt_default
def opt_maildirdbmdomain(self, domain):
"""generate an SMTP/POP3 virtual domain which saves to \"path\"
"""
try:
name, path = domain.split('=')
except ValueError:
raise usage.UsageError("Argument to --maildirdbmdomain must be of the form 'name=path'")
self.last_domain = maildir.MaildirDirdbmDomain(self.service, os.path.abspath(path))
self.service.addDomain(name, self.last_domain)
opt_d = opt_maildirdbmdomain
def opt_user(self, user_pass):
"""add a user/password to the last specified domains
"""
try:
user, password = user_pass.split('=', 1)
except ValueError:
raise usage.UsageError("Argument to --user must be of the form 'user=password'")
if self.last_domain:
self.last_domain.addUser(user, password)
else:
raise usage.UsageError("Specify a domain before specifying users")
opt_u = opt_user
def opt_bounce_to_postmaster(self):
"""undelivered mails are sent to the postmaster
"""
self.last_domain.postmaster = 1
opt_b = opt_bounce_to_postmaster
def opt_aliases(self, filename):
"""Specify an aliases(5) file to use for this domain"""
if self.last_domain is not None:
if mail.IAliasableDomain.providedBy(self.last_domain):
aliases = alias.loadAliasFile(self.service.domains, filename)
self.last_domain.setAliasGroup(aliases)
self.service.monitor.monitorFile(
filename,
AliasUpdater(self.service.domains, self.last_domain)
)
else:
raise usage.UsageError(
"%s does not support alias files" % (
self.last_domain.__class__.__name__,
)
)
else:
raise usage.UsageError("Specify a domain before specifying aliases")
opt_A = opt_aliases
def postOptions(self):
for f in ('pop3', 'smtp', 'pop3s'):
try:
self[f] = int(self[f])
if not (0 <= self[f] < 2 ** 16):
raise ValueError
except ValueError:
raise usage.UsageError(
'Invalid port specified to --%s: %s' % (f, self[f])
)
if self['pop3s']:
if not self['certificate']:
raise usage.UsageError("Cannot specify --pop3s without "
"--certificate")
elif not os.path.exists(self['certificate']):
raise usage.UsageError("Certificate file %r does not exist."
% self['certificate'])
if not self['disable-anonymous']:
self.service.smtpPortal.registerChecker(checkers.AllowAnonymousAccess())
if not (self['pop3'] or self['smtp'] or self['pop3s']):
raise usage.UsageError("You cannot disable all protocols")
class AliasUpdater:
def __init__(self, domains, domain):
self.domains = domains
self.domain = domain
def __call__(self, new):
self.domain.setAliasGroup(alias.loadAliasFile(self.domains, new))
def makeService(config):
if config['esmtp']:
rmType = relaymanager.SmartHostESMTPRelayingManager
smtpFactory = config.service.getESMTPFactory
else:
rmType = relaymanager.SmartHostSMTPRelayingManager
smtpFactory = config.service.getSMTPFactory
if config['relay']:
dir = config['relay']
if not os.path.isdir(dir):
os.mkdir(dir)
config.service.setQueue(relaymanager.Queue(dir))
default = relay.DomainQueuer(config.service)
manager = rmType(config.service.queue)
if config['esmtp']:
manager.fArgs += (None, None)
manager.fArgs += (config['hostname'],)
helper = relaymanager.RelayStateHelper(manager, 1)
helper.setServiceParent(config.service)
config.service.domains.setDefaultDomain(default)
ctx = None
if config['certificate']:
from twisted.mail.protocols import SSLContextFactory
ctx = SSLContextFactory(config['certificate'])
if config['pop3']:
s = internet.TCPServer(config['pop3'], config.service.getPOP3Factory())
s.setServiceParent(config.service)
if config['pop3s']:
s = internet.SSLServer(config['pop3s'],
config.service.getPOP3Factory(), ctx)
s.setServiceParent(config.service)
if config['smtp']:
f = smtpFactory()
f.context = ctx
if config['hostname']:
f.domain = config['hostname']
f.fArgs = (f.domain,)
if config['esmtp']:
f.fArgs = (None, None) + f.fArgs
s = internet.TCPServer(config['smtp'], f)
s.setServiceParent(config.service)
return config.service | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/mail/tap.py | tap.py |
from __future__ import generators
import os
import stat
import socket
import time
import md5
import cStringIO
from zope.interface import implements
try:
import cStringIO as StringIO
except ImportError:
import StringIO
from twisted.mail import pop3
from twisted.mail import smtp
from twisted.protocols import basic
from twisted.persisted import dirdbm
from twisted.python import log, failure
from twisted.mail import mail
from twisted.mail import alias
from twisted.internet import interfaces, defer, reactor
from twisted import cred
import twisted.cred.portal
import twisted.cred.credentials
import twisted.cred.checkers
import twisted.cred.error
INTERNAL_ERROR = '''\
From: Twisted.mail Internals
Subject: An Error Occurred
An internal server error has occurred. Please contact the
server administrator.
'''
class _MaildirNameGenerator:
"""Utility class to generate a unique maildir name
"""
n = 0
p = os.getpid()
s = socket.gethostname().replace('/', r'\057').replace(':', r'\072')
def generate(self):
self.n = self.n + 1
t = time.time()
seconds = str(int(t))
microseconds = str(int((t-int(t))*10e6))
return '%s.M%sP%sQ%s.%s' % (seconds, microseconds,
self.p, self.n, self.s)
_generateMaildirName = _MaildirNameGenerator().generate
def initializeMaildir(dir):
if not os.path.isdir(dir):
os.mkdir(dir, 0700)
for subdir in ['new', 'cur', 'tmp', '.Trash']:
os.mkdir(os.path.join(dir, subdir), 0700)
for subdir in ['new', 'cur', 'tmp']:
os.mkdir(os.path.join(dir, '.Trash', subdir), 0700)
# touch
open(os.path.join(dir, '.Trash', 'maildirfolder'), 'w').close()
class MaildirMessage(mail.FileMessage):
size = None
def __init__(self, address, fp, *a, **kw):
header = "Delivered-To: %s\n" % address
fp.write(header)
self.size = len(header)
mail.FileMessage.__init__(self, fp, *a, **kw)
def lineReceived(self, line):
mail.FileMessage.lineReceived(self, line)
self.size += len(line)+1
def eomReceived(self):
self.finalName = self.finalName+',S=%d' % self.size
return mail.FileMessage.eomReceived(self)
class AbstractMaildirDomain:
"""Abstract maildir-backed domain.
"""
alias = None
root = None
def __init__(self, service, root):
"""Initialize.
"""
self.root = root
def userDirectory(self, user):
"""Get the maildir directory for a given user
Override to specify where to save mails for users.
Return None for non-existing users.
"""
return None
##
## IAliasableDomain
##
def setAliasGroup(self, alias):
self.alias = alias
##
## IDomain
##
def exists(self, user, memo=None):
"""Check for existence of user in the domain
"""
if self.userDirectory(user.dest.local) is not None:
return lambda: self.startMessage(user)
try:
a = self.alias[user.dest.local]
except:
raise smtp.SMTPBadRcpt(user)
else:
aliases = a.resolve(self.alias, memo)
if aliases:
return lambda: aliases
log.err("Bad alias configuration: " + str(user))
raise smtp.SMTPBadRcpt(user)
def startMessage(self, user):
"""Save a message for a given user
"""
if isinstance(user, str):
name, domain = user.split('@', 1)
else:
name, domain = user.dest.local, user.dest.domain
dir = self.userDirectory(name)
fname = _generateMaildirName()
filename = os.path.join(dir, 'tmp', fname)
fp = open(filename, 'w')
return MaildirMessage('%s@%s' % (name, domain), fp, filename,
os.path.join(dir, 'new', fname))
def willRelay(self, user, protocol):
return False
def addUser(self, user, password):
raise NotImplementedError
def getCredentialsCheckers(self):
raise NotImplementedError
##
## end of IDomain
##
class _MaildirMailboxAppendMessageTask:
implements(interfaces.IConsumer)
osopen = staticmethod(os.open)
oswrite = staticmethod(os.write)
osclose = staticmethod(os.close)
osrename = staticmethod(os.rename)
def __init__(self, mbox, msg):
self.mbox = mbox
self.defer = defer.Deferred()
self.openCall = None
if not hasattr(msg, "read"):
msg = StringIO.StringIO(msg)
self.msg = msg
# This is needed, as this startup phase might call defer.errback and zero out self.defer
# By doing it on the reactor iteration appendMessage is able to use .defer without problems.
reactor.callLater(0, self.startUp)
def startUp(self):
self.createTempFile()
if self.fh != -1:
self.filesender = basic.FileSender()
self.filesender.beginFileTransfer(self.msg, self)
def registerProducer(self, producer, streaming):
self.myproducer = producer
self.streaming = streaming
if not streaming:
self.prodProducer()
def prodProducer(self):
self.openCall = None
if self.myproducer is not None:
self.openCall = reactor.callLater(0, self.prodProducer)
self.myproducer.resumeProducing()
def unregisterProducer(self):
self.myproducer = None
self.streaming = None
self.osclose(self.fh)
self.moveFileToNew()
def write(self, data):
try:
self.oswrite(self.fh, data)
except:
self.fail()
def fail(self, err=None):
if err is None:
err = failure.Failure()
if self.openCall is not None:
self.openCall.cancel()
self.defer.errback(err)
self.defer = None
def moveFileToNew(self):
while True:
newname = os.path.join(self.mbox.path, "new", _generateMaildirName())
try:
self.osrename(self.tmpname, newname)
break
except OSError, (err, estr):
import errno
# if the newname exists, retry with a new newname.
if err != errno.EEXIST:
self.fail()
newname = None
break
if newname is not None:
self.mbox.list.append(newname)
self.defer.callback(None)
self.defer = None
def createTempFile(self):
attr = (os.O_RDWR | os.O_CREAT | os.O_EXCL
| getattr(os, "O_NOINHERIT", 0)
| getattr(os, "O_NOFOLLOW", 0))
tries = 0
self.fh = -1
while True:
self.tmpname = os.path.join(self.mbox.path, "tmp", _generateMaildirName())
try:
self.fh = self.osopen(self.tmpname, attr, 0600)
return None
except OSError:
tries += 1
if tries > 500:
self.defer.errback(RuntimeError("Could not create tmp file for %s" % self.mbox.path))
self.defer = None
return None
class MaildirMailbox(pop3.Mailbox):
"""Implement the POP3 mailbox semantics for a Maildir mailbox
"""
AppendFactory = _MaildirMailboxAppendMessageTask
def __init__(self, path):
"""Initialize with name of the Maildir mailbox
"""
self.path = path
self.list = []
self.deleted = {}
initializeMaildir(path)
for name in ('cur', 'new'):
for file in os.listdir(os.path.join(path, name)):
self.list.append((file, os.path.join(path, name, file)))
self.list.sort()
self.list = [e[1] for e in self.list]
def listMessages(self, i=None):
"""Return a list of lengths of all files in new/ and cur/
"""
if i is None:
ret = []
for mess in self.list:
if mess:
ret.append(os.stat(mess)[stat.ST_SIZE])
else:
ret.append(0)
return ret
return self.list[i] and os.stat(self.list[i])[stat.ST_SIZE] or 0
def getMessage(self, i):
"""Return an open file-pointer to a message
"""
return open(self.list[i])
def getUidl(self, i):
"""Return a unique identifier for a message
This is done using the basename of the filename.
It is globally unique because this is how Maildirs are designed.
"""
# Returning the actual filename is a mistake. Hash it.
base = os.path.basename(self.list[i])
return md5.md5(base).hexdigest()
def deleteMessage(self, i):
"""Delete a message
This only moves a message to the .Trash/ subfolder,
so it can be undeleted by an administrator.
"""
trashFile = os.path.join(
self.path, '.Trash', 'cur', os.path.basename(self.list[i])
)
os.rename(self.list[i], trashFile)
self.deleted[self.list[i]] = trashFile
self.list[i] = 0
def undeleteMessages(self):
"""Undelete any deleted messages it is possible to undelete
This moves any messages from .Trash/ subfolder back to their
original position, and empties out the deleted dictionary.
"""
for (real, trash) in self.deleted.items():
try:
os.rename(trash, real)
except OSError, (err, estr):
import errno
# If the file has been deleted from disk, oh well!
if err != errno.ENOENT:
raise
# This is a pass
else:
try:
self.list[self.list.index(0)] = real
except ValueError:
self.list.append(real)
self.deleted.clear()
def appendMessage(self, txt):
"""Appends a message into the mailbox."""
task = self.AppendFactory(self, txt)
return task.defer
class StringListMailbox:
implements(pop3.IMailbox)
def __init__(self, msgs):
self.msgs = msgs
def listMessages(self, i=None):
if i is None:
return map(len, self.msgs)
return len(self.msgs[i])
def getMessage(self, i):
return StringIO.StringIO(self.msgs[i])
def getUidl(self, i):
return md5.new(self.msgs[i]).hexdigest()
def deleteMessage(self, i):
pass
def undeleteMessages(self):
pass
def sync(self):
pass
class MaildirDirdbmDomain(AbstractMaildirDomain):
"""A Maildir Domain where membership is checked by a dirdbm file
"""
implements(cred.portal.IRealm, mail.IAliasableDomain)
portal = None
_credcheckers = None
def __init__(self, service, root, postmaster=0):
"""Initialize
The first argument is where the Domain directory is rooted.
The second is whether non-existing addresses are simply
forwarded to postmaster instead of outright bounce
The directory structure of a MailddirDirdbmDomain is:
/passwd <-- a dirdbm file
/USER/{cur,new,del} <-- each user has these three directories
"""
AbstractMaildirDomain.__init__(self, service, root)
dbm = os.path.join(root, 'passwd')
if not os.path.exists(dbm):
os.makedirs(dbm)
self.dbm = dirdbm.open(dbm)
self.postmaster = postmaster
def userDirectory(self, name):
"""Get the directory for a user
If the user exists in the dirdbm file, return the directory
os.path.join(root, name), creating it if necessary.
Otherwise, returns postmaster's mailbox instead if bounces
go to postmaster, otherwise return None
"""
if not self.dbm.has_key(name):
if not self.postmaster:
return None
name = 'postmaster'
dir = os.path.join(self.root, name)
if not os.path.exists(dir):
initializeMaildir(dir)
return dir
##
## IDomain
##
def addUser(self, user, password):
self.dbm[user] = password
# Ensure it is initialized
self.userDirectory(user)
def getCredentialsCheckers(self):
if self._credcheckers is None:
self._credcheckers = [DirdbmDatabase(self.dbm)]
return self._credcheckers
##
## IRealm
##
def requestAvatar(self, avatarId, mind, *interfaces):
if pop3.IMailbox not in interfaces:
raise NotImplementedError("No interface")
if avatarId == cred.checkers.ANONYMOUS:
mbox = StringListMailbox([INTERNAL_ERROR])
else:
mbox = MaildirMailbox(os.path.join(self.root, avatarId))
return (
pop3.IMailbox,
mbox,
lambda: None
)
class DirdbmDatabase:
implements(cred.checkers.ICredentialsChecker)
credentialInterfaces = (
cred.credentials.IUsernamePassword,
cred.credentials.IUsernameHashedPassword
)
def __init__(self, dbm):
self.dirdbm = dbm
def requestAvatarId(self, c):
if c.username in self.dirdbm:
if c.checkPassword(self.dirdbm[c.username]):
return c.username
raise cred.error.UnauthorizedLogin() | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/mail/maildir.py | maildir.py |
#
"""
Implementation module for the `newtexaco` command.
The name is preliminary and subject to change.
"""
import os
import sys
import rfc822
import socket
import getpass
from ConfigParser import ConfigParser
try:
import cStringIO as StringIO
except:
import StringIO
from twisted.internet import reactor
from twisted.mail import bounce, smtp
GLOBAL_CFG = "/etc/mailmail"
LOCAL_CFG = os.path.expanduser("~/.twisted/mailmail")
SMARTHOST = '127.0.0.1'
ERROR_FMT = """\
Subject: Failed Message Delivery
Message delivery failed. The following occurred:
%s
--
The Twisted sendmail application.
"""
def log(message, *args):
sys.stderr.write(str(message) % args + '\n')
class Options:
"""
@type to: C{list} of C{str}
@ivar to: The addresses to which to deliver this message.
@type sender: C{str}
@ivar sender: The address from which this message is being sent.
@type body: C{file}
@ivar body: The object from which the message is to be read.
"""
def getlogin():
try:
return os.getlogin()
except:
return getpass.getuser()
def parseOptions(argv):
o = Options()
o.to = [e for e in argv if not e.startswith('-')]
o.sender = getlogin()
# Just be very stupid
# Skip -bm -- it is the default
# -bp lists queue information. Screw that.
if '-bp' in argv:
raise ValueError, "Unsupported option"
# -bs makes sendmail use stdin/stdout as its transport. Screw that.
if '-bs' in argv:
raise ValueError, "Unsupported option"
# -F sets who the mail is from, but is overridable by the From header
if '-F' in argv:
o.sender = argv[argv.index('-F') + 1]
o.to.remove(o.sender)
# -i and -oi makes us ignore lone "."
if ('-i' in argv) or ('-oi' in argv):
raise ValueError, "Unsupported option"
# -odb is background delivery
if '-odb' in argv:
o.background = True
else:
o.background = False
# -odf is foreground delivery
if '-odf' in argv:
o.background = False
else:
o.background = True
# -oem and -em cause errors to be mailed back to the sender.
# It is also the default.
# -oep and -ep cause errors to be printed to stderr
if ('-oep' in argv) or ('-ep' in argv):
o.printErrors = True
else:
o.printErrors = False
# -om causes a copy of the message to be sent to the sender if the sender
# appears in an alias expansion. We do not support aliases.
if '-om' in argv:
raise ValueError, "Unsupported option"
# -t causes us to pick the recipients of the message from the To, Cc, and Bcc
# headers, and to remove the Bcc header if present.
if '-t' in argv:
o.recipientsFromHeaders = True
o.excludeAddresses = o.to
o.to = []
else:
o.recipientsFromHeaders = False
o.exludeAddresses = []
requiredHeaders = {
'from': [],
'to': [],
'cc': [],
'bcc': [],
'date': [],
}
headers = []
buffer = StringIO.StringIO()
while 1:
write = 1
line = sys.stdin.readline()
if not line.strip():
break
hdrs = line.split(': ', 1)
hdr = hdrs[0].lower()
if o.recipientsFromHeaders and hdr in ('to', 'cc', 'bcc'):
o.to.extend([
a[1] for a in rfc822.AddressList(hdrs[1]).addresslist
])
if hdr == 'bcc':
write = 0
elif hdr == 'from':
o.sender = rfc822.parseaddr(hdrs[1])[1]
if hdr in requiredHeaders:
requiredHeaders[hdr].append(hdrs[1])
if write:
buffer.write(line)
if not requiredHeaders['from']:
buffer.write('From: %s\r\n' % (o.sender,))
if not requiredHeaders['to']:
if not o.to:
raise ValueError, "No recipients specified"
buffer.write('To: %s\r\n' % (', '.join(o.to),))
if not requiredHeaders['date']:
buffer.write('Date: %s\r\n' % (smtp.rfc822date(),))
buffer.write(line)
if o.recipientsFromHeaders:
for a in o.excludeAddresses:
try:
o.to.remove(a)
except:
pass
buffer.seek(0, 0)
o.body = StringIO.StringIO(buffer.getvalue() + sys.stdin.read())
return o
class Configuration:
"""
@ivar allowUIDs: A list of UIDs which are allowed to send mail.
@ivar allowGIDs: A list of GIDs which are allowed to send mail.
@ivar denyUIDs: A list of UIDs which are not allowed to send mail.
@ivar denyGIDs: A list of GIDs which are not allowed to send mail.
@type defaultAccess: C{bool}
@ivar defaultAccess: C{True} if access will be allowed when no other access
control rule matches or C{False} if it will be denied in that case.
@ivar useraccess: Either C{'allow'} to check C{allowUID} first
or C{'deny'} to check C{denyUID} first.
@ivar groupaccess: Either C{'allow'} to check C{allowGID} first or
C{'deny'} to check C{denyGID} first.
@ivar identities: A C{dict} mapping hostnames to credentials to use when
sending mail to that host.
@ivar smarthost: C{None} or a hostname through which all outgoing mail will
be sent.
@ivar domain: C{None} or the hostname with which to identify ourselves when
connecting to an MTA.
"""
def __init__(self):
self.allowUIDs = []
self.denyUIDs = []
self.allowGIDs = []
self.denyGIDs = []
self.useraccess = 'deny'
self.groupaccess= 'deny'
self.identities = {}
self.smarthost = None
self.domain = None
self.defaultAccess = True
def loadConfig(path):
# [useraccess]
# allow=uid1,uid2,...
# deny=uid1,uid2,...
# order=allow,deny
# [groupaccess]
# allow=gid1,gid2,...
# deny=gid1,gid2,...
# order=deny,allow
# [identity]
# host1=username:password
# host2=username:password
# [addresses]
# smarthost=a.b.c.d
# default_domain=x.y.z
c = Configuration()
if not os.access(path, os.R_OK):
return c
p = ConfigParser()
p.read(path)
au = c.allowUIDs
du = c.denyUIDs
ag = c.allowGIDs
dg = c.denyGIDs
for (section, a, d) in (('useraccess', au, du), ('groupaccess', ag, dg)):
if p.has_section(section):
for (mode, L) in (('allow', a), ('deny', d)):
if p.has_option(section, mode) and p.get(section, mode):
for id in p.get(section, mode).split(','):
try:
id = int(id)
except ValueError:
log("Illegal %sID in [%s] section: %s", section[0].upper(), section, id)
else:
L.append(id)
order = p.get(section, 'order')
order = map(str.split, map(str.lower, order.split(',')))
if order[0] == 'allow':
setattr(c, section, 'allow')
else:
setattr(c, section, 'deny')
if p.has_section('identity'):
for (host, up) in p.items('identity'):
parts = up.split(':', 1)
if len(parts) != 2:
log("Illegal entry in [identity] section: %s", up)
continue
p.identities[host] = parts
if p.has_section('addresses'):
if p.has_option('addresses', 'smarthost'):
c.smarthost = p.get('addresses', 'smarthost')
if p.has_option('addresses', 'default_domain'):
c.domain = p.get('addresses', 'default_domain')
return c
def success(result):
reactor.stop()
failed = None
def failure(f):
global failed
reactor.stop()
failed = f
def sendmail(host, options, ident):
d = smtp.sendmail(host, options.sender, options.to, options.body)
d.addCallbacks(success, failure)
reactor.run()
def senderror(failure, options):
recipient = [options.sender]
sender = '"Internally Generated Message (%s)"<postmaster@%s>' % (sys.argv[0], smtp.DNSNAME)
error = StringIO.StringIO()
failure.printTraceback(file=error)
body = StringIO.StringIO(ERROR_FMT % error.getvalue())
d = smtp.sendmail('localhost', sender, recipient, body)
d.addBoth(lambda _: reactor.stop())
def deny(conf):
uid = os.getuid()
gid = os.getgid()
if conf.useraccess == 'deny':
if uid in conf.denyUIDs:
return True
if uid in conf.allowUIDs:
return False
else:
if uid in conf.allowUIDs:
return False
if uid in conf.denyUIDs:
return True
if conf.groupaccess == 'deny':
if gid in conf.denyGIDs:
return True
if gid in conf.allowGIDs:
return False
else:
if gid in conf.allowGIDs:
return False
if gid in conf.denyGIDs:
return True
return not conf.defaultAccess
def run():
o = parseOptions(sys.argv[1:])
gConf = loadConfig(GLOBAL_CFG)
lConf = loadConfig(LOCAL_CFG)
if deny(gConf) or deny(lConf):
log("Permission denied")
return
host = lConf.smarthost or gConf.smarthost or SMARTHOST
ident = gConf.identities.copy()
ident.update(lConf.identities)
if lConf.domain:
smtp.DNSNAME = lConf.domain
elif gConf.domain:
smtp.DNSNAME = gConf.domain
sendmail(host, o, ident)
if failed:
if o.printErrors:
failed.printTraceback(file=sys.stderr)
raise SystemExit(1)
else:
senderror(failed, o) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/mail/scripts/mailmail.py | mailmail.py |
# twisted imports
from twisted import copyright
from twisted.spread import pb
from twisted.python import log, failure
from twisted.cred import portal
from twisted.application import service
from zope.interface import implements, Interface
# sibling imports
import explorer
# system imports
from cStringIO import StringIO
import string
import sys
import traceback
import types
class FakeStdIO:
def __init__(self, type_, list):
self.type = type_
self.list = list
def write(self, text):
log.msg("%s: %s" % (self.type, string.strip(str(text))))
self.list.append((self.type, text))
def flush(self):
pass
def consolidate(self):
"""Concatenate adjacent messages of same type into one.
Greatly cuts down on the number of elements, increasing
network transport friendliness considerably.
"""
if not self.list:
return
inlist = self.list
outlist = []
last_type = inlist[0]
block_begin = 0
for i in xrange(1, len(self.list)):
(mtype, message) = inlist[i]
if mtype == last_type:
continue
else:
if (i - block_begin) == 1:
outlist.append(inlist[block_begin])
else:
messages = map(lambda l: l[1],
inlist[block_begin:i])
message = string.join(messages, '')
outlist.append((last_type, message))
last_type = mtype
block_begin = i
class IManholeClient(Interface):
def console(list_of_messages):
"""Takes a list of (type, message) pairs to display.
Types include:
- \"stdout\" -- string sent to sys.stdout
- \"stderr\" -- string sent to sys.stderr
- \"result\" -- string repr of the resulting value
of the expression
- \"exception\" -- a L{failure.Failure}
"""
def receiveExplorer(xplorer):
"""Receives an explorer.Explorer
"""
def listCapabilities():
"""List what manholey things I am capable of doing.
i.e. C{\"Explorer\"}, C{\"Failure\"}
"""
def runInConsole(command, console, globalNS=None, localNS=None,
filename=None, args=None, kw=None, unsafeTracebacks=False):
"""Run this, directing all output to the specified console.
If command is callable, it will be called with the args and keywords
provided. Otherwise, command will be compiled and eval'd.
(Wouldn't you like a macro?)
Returns the command's return value.
The console is called with a list of (type, message) pairs for
display, see L{IManholeClient.console}.
"""
output = []
fakeout = FakeStdIO("stdout", output)
fakeerr = FakeStdIO("stderr", output)
errfile = FakeStdIO("exception", output)
code = None
val = None
if filename is None:
filename = str(console)
if args is None:
args = ()
if kw is None:
kw = {}
if localNS is None:
localNS = globalNS
if (globalNS is None) and (not callable(command)):
raise ValueError("Need a namespace to evaluate the command in.")
try:
out = sys.stdout
err = sys.stderr
sys.stdout = fakeout
sys.stderr = fakeerr
try:
if callable(command):
val = apply(command, args, kw)
else:
try:
code = compile(command, filename, 'eval')
except:
code = compile(command, filename, 'single')
if code:
val = eval(code, globalNS, localNS)
finally:
sys.stdout = out
sys.stderr = err
except:
(eType, eVal, tb) = sys.exc_info()
fail = failure.Failure(eVal, eType, tb)
del tb
# In CVS reversion 1.35, there was some code here to fill in the
# source lines in the traceback for frames in the local command
# buffer. But I can't figure out when that's triggered, so it's
# going away in the conversion to Failure, until you bring it back.
errfile.write(pb.failure2Copyable(fail, unsafeTracebacks))
if console:
fakeout.consolidate()
console(output)
return val
def _failureOldStyle(fail):
"""Pre-Failure manhole representation of exceptions.
For compatibility with manhole clients without the \"Failure\"
capability.
A dictionary with two members:
- \'traceback\' -- traceback.extract_tb output; a list of tuples
(filename, line number, function name, text) suitable for
feeding to traceback.format_list.
- \'exception\' -- a list of one or more strings, each
ending in a newline. (traceback.format_exception_only output)
"""
import linecache
tb = []
for f in fail.frames:
# (filename, line number, function name, text)
tb.append((f[1], f[2], f[0], linecache.getline(f[1], f[2])))
return {
'traceback': tb,
'exception': traceback.format_exception_only(fail.type, fail.value)
}
# Capabilities clients are likely to have before they knew how to answer a
# "listCapabilities" query.
_defaultCapabilities = {
"Explorer": 'Set'
}
class Perspective(pb.Avatar):
lastDeferred = 0
def __init__(self, service):
self.localNamespace = {
"service": service,
"avatar": self,
"_": None,
}
self.clients = {}
self.service = service
def __getstate__(self):
state = self.__dict__.copy()
state['clients'] = {}
if state['localNamespace'].has_key("__builtins__"):
del state['localNamespace']['__builtins__']
return state
def attached(self, client, identity):
"""A client has attached -- welcome them and add them to the list.
"""
self.clients[client] = identity
host = ':'.join(map(str, client.broker.transport.getHost()[1:]))
msg = self.service.welcomeMessage % {
'you': getattr(identity, 'name', str(identity)),
'host': host,
'longversion': copyright.longversion,
}
client.callRemote('console', [("stdout", msg)])
client.capabilities = _defaultCapabilities
client.callRemote('listCapabilities').addCallbacks(
self._cbClientCapable, self._ebClientCapable,
callbackArgs=(client,),errbackArgs=(client,))
def detached(self, client, identity):
try:
del self.clients[client]
except KeyError:
pass
def runInConsole(self, command, *args, **kw):
"""Convience method to \"runInConsole with my stuff\".
"""
return runInConsole(command,
self.console,
self.service.namespace,
self.localNamespace,
str(self.service),
args=args,
kw=kw,
unsafeTracebacks=self.service.unsafeTracebacks)
### Methods for communicating to my clients.
def console(self, message):
"""Pass a message to my clients' console.
"""
clients = self.clients.keys()
origMessage = message
compatMessage = None
for client in clients:
try:
if not client.capabilities.has_key("Failure"):
if compatMessage is None:
compatMessage = origMessage[:]
for i in xrange(len(message)):
if ((message[i][0] == "exception") and
isinstance(message[i][1], failure.Failure)):
compatMessage[i] = (
message[i][0],
_failureOldStyle(message[i][1]))
client.callRemote('console', compatMessage)
else:
client.callRemote('console', message)
except pb.ProtocolError:
# Stale broker.
self.detached(client, None)
def receiveExplorer(self, objectLink):
"""Pass an Explorer on to my clients.
"""
clients = self.clients.keys()
for client in clients:
try:
client.callRemote('receiveExplorer', objectLink)
except pb.ProtocolError:
# Stale broker.
self.detached(client, None)
def _cbResult(self, val, dnum):
self.console([('result', "Deferred #%s Result: %r\n" %(dnum, val))])
return val
def _cbClientCapable(self, capabilities, client):
log.msg("client %x has %s" % (id(client), capabilities))
client.capabilities = capabilities
def _ebClientCapable(self, reason, client):
reason.trap(AttributeError)
log.msg("Couldn't get capabilities from %s, assuming defaults." %
(client,))
### perspective_ methods, commands used by the client.
def perspective_do(self, expr):
"""Evaluate the given expression, with output to the console.
The result is stored in the local variable '_', and its repr()
string is sent to the console as a \"result\" message.
"""
log.msg(">>> %s" % expr)
val = self.runInConsole(expr)
if val is not None:
self.localNamespace["_"] = val
from twisted.internet.defer import Deferred
# TODO: client support for Deferred.
if isinstance(val, Deferred):
self.lastDeferred += 1
self.console([('result', "Waiting for Deferred #%s...\n" % self.lastDeferred)])
val.addBoth(self._cbResult, self.lastDeferred)
else:
self.console([("result", repr(val) + '\n')])
log.msg("<<<")
def perspective_explore(self, identifier):
"""Browse the object obtained by evaluating the identifier.
The resulting ObjectLink is passed back through the client's
receiveBrowserObject method.
"""
object = self.runInConsole(identifier)
if object:
expl = explorer.explorerPool.getExplorer(object, identifier)
self.receiveExplorer(expl)
def perspective_watch(self, identifier):
"""Watch the object obtained by evaluating the identifier.
Whenever I think this object might have changed, I will pass
an ObjectLink of it back to the client's receiveBrowserObject
method.
"""
raise NotImplementedError
object = self.runInConsole(identifier)
if object:
# Return an ObjectLink of this right away, before the watch.
oLink = self.runInConsole(self.browser.browseObject,
object, identifier)
self.receiveExplorer(oLink)
self.runInConsole(self.browser.watchObject,
object, identifier,
self.receiveExplorer)
class Realm:
implements(portal.IRealm)
def __init__(self, service):
self.service = service
self._cache = {}
def requestAvatar(self, avatarId, mind, *interfaces):
if pb.IPerspective not in interfaces:
raise NotImplementedError("no interface")
if avatarId in self._cache:
p = self._cache[avatarId]
else:
p = Perspective(self.service)
p.attached(mind, avatarId)
def detached():
p.detached(mind, avatarId)
return (pb.IPerspective, p, detached)
class Service(service.Service):
welcomeMessage = (
"\nHello %(you)s, welcome to Manhole "
"on %(host)s.\n"
"%(longversion)s.\n\n")
def __init__(self, unsafeTracebacks=False, namespace=None):
self.unsafeTracebacks = unsafeTracebacks
self.namespace = {
'__name__': '__manhole%x__' % (id(self),),
'sys': sys
}
if namespace:
self.namespace.update(namespace)
def __getstate__(self):
"""This returns the persistent state of this shell factory.
"""
# TODO -- refactor this and twisted.reality.author.Author to
# use common functionality (perhaps the 'code' module?)
dict = self.__dict__.copy()
ns = dict['namespace'].copy()
dict['namespace'] = ns
if ns.has_key('__builtins__'):
del ns['__builtins__']
return dict | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/manhole/service.py | service.py |
# twisted imports
from twisted.protocols import telnet
from twisted.internet import protocol
from twisted.python import log, failure
# system imports
import string, copy, sys
from cStringIO import StringIO
class Shell(telnet.Telnet):
"""A Python command-line shell."""
def connectionMade(self):
telnet.Telnet.connectionMade(self)
self.lineBuffer = []
def loggedIn(self):
self.transport.write(">>> ")
def checkUserAndPass(self, username, password):
return ((self.factory.username == username) and (password == self.factory.password))
def write(self, data):
"""Write some data to the transport.
"""
self.transport.write(data)
def telnet_Command(self, cmd):
if self.lineBuffer:
if not cmd:
cmd = string.join(self.lineBuffer, '\n') + '\n\n\n'
self.doCommand(cmd)
self.lineBuffer = []
return "Command"
else:
self.lineBuffer.append(cmd)
self.transport.write("... ")
return "Command"
else:
self.doCommand(cmd)
return "Command"
def doCommand(self, cmd):
# TODO -- refactor this, Reality.author.Author, and the manhole shell
#to use common functionality (perhaps a twisted.python.code module?)
fn = '$telnet$'
result = None
try:
out = sys.stdout
sys.stdout = self
try:
code = compile(cmd,fn,'eval')
result = eval(code, self.factory.namespace)
except:
try:
code = compile(cmd, fn, 'exec')
exec code in self.factory.namespace
except SyntaxError, e:
if not self.lineBuffer and str(e)[:14] == "unexpected EOF":
self.lineBuffer.append(cmd)
self.transport.write("... ")
return
else:
failure.Failure().printTraceback(file=self)
log.deferr()
self.write('\r\n>>> ')
return
except:
io = StringIO()
failure.Failure().printTraceback(file=self)
log.deferr()
self.write('\r\n>>> ')
return
finally:
sys.stdout = out
self.factory.namespace['_'] = result
if result is not None:
self.transport.write(repr(result))
self.transport.write('\r\n')
self.transport.write(">>> ")
class ShellFactory(protocol.Factory):
username = "admin"
password = "admin"
protocol = Shell
service = None
def __init__(self):
self.namespace = {
'factory': self,
'service': None,
'_': None
}
def setService(self, service):
self.namespace['service'] = self.service = service
def __getstate__(self):
"""This returns the persistent state of this shell factory.
"""
dict = self.__dict__
ns = copy.copy(dict['namespace'])
dict['namespace'] = ns
if ns.has_key('__builtins__'):
del ns['__builtins__']
return dict | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/manhole/telnet.py | telnet.py |
# System Imports
import inspect, new, string, sys, types
import UserDict
# Twisted Imports
from twisted.spread import pb
from twisted.python import reflect
True=(1==1)
False=not True
class Pool(UserDict.UserDict):
def getExplorer(self, object, identifier):
oid = id(object)
if self.data.has_key(oid):
# XXX: This potentially returns something with
# 'identifier' set to a different value.
return self.data[oid]
else:
klass = typeTable.get(type(object), ExplorerGeneric)
e = new.instance(klass, {})
self.data[oid] = e
klass.__init__(e, object, identifier)
return e
explorerPool = Pool()
class Explorer(pb.Cacheable):
properties = ["id", "identifier"]
attributeGroups = []
accessors = ["get_refcount"]
id = None
identifier = None
def __init__(self, object, identifier):
self.object = object
self.identifier = identifier
self.id = id(object)
self.properties = []
reflect.accumulateClassList(self.__class__, 'properties',
self.properties)
self.attributeGroups = []
reflect.accumulateClassList(self.__class__, 'attributeGroups',
self.attributeGroups)
self.accessors = []
reflect.accumulateClassList(self.__class__, 'accessors',
self.accessors)
def getStateToCopyFor(self, perspective):
all = ["properties", "attributeGroups", "accessors"]
all.extend(self.properties)
all.extend(self.attributeGroups)
state = {}
for key in all:
state[key] = getattr(self, key)
state['view'] = pb.ViewPoint(perspective, self)
state['explorerClass'] = self.__class__.__name__
return state
def view_get_refcount(self, perspective):
return sys.getrefcount(self)
class ExplorerGeneric(Explorer):
properties = ["str", "repr", "typename"]
def __init__(self, object, identifier):
Explorer.__init__(self, object, identifier)
self.str = str(object)
self.repr = repr(object)
self.typename = type(object).__name__
class ExplorerImmutable(Explorer):
properties = ["value"]
def __init__(self, object, identifier):
Explorer.__init__(self, object, identifier)
self.value = object
class ExplorerSequence(Explorer):
properties = ["len"]
attributeGroups = ["elements"]
accessors = ["get_elements"]
def __init__(self, seq, identifier):
Explorer.__init__(self, seq, identifier)
self.seq = seq
self.len = len(seq)
# Use accessor method to fill me in.
self.elements = []
def get_elements(self):
self.len = len(self.seq)
l = []
for i in xrange(self.len):
identifier = "%s[%s]" % (self.identifier, i)
# GLOBAL: using global explorerPool
l.append(explorerPool.getExplorer(self.seq[i], identifier))
return l
def view_get_elements(self, perspective):
# XXX: set the .elements member of all my remoteCaches
return self.get_elements()
class ExplorerMapping(Explorer):
properties = ["len"]
attributeGroups = ["keys"]
accessors = ["get_keys", "get_item"]
def __init__(self, dct, identifier):
Explorer.__init__(self, dct, identifier)
self.dct = dct
self.len = len(dct)
# Use accessor method to fill me in.
self.keys = []
def get_keys(self):
keys = self.dct.keys()
self.len = len(keys)
l = []
for i in xrange(self.len):
identifier = "%s.keys()[%s]" % (self.identifier, i)
# GLOBAL: using global explorerPool
l.append(explorerPool.getExplorer(keys[i], identifier))
return l
def view_get_keys(self, perspective):
# XXX: set the .keys member of all my remoteCaches
return self.get_keys()
def view_get_item(self, perspective, key):
if type(key) is types.InstanceType:
key = key.object
item = self.dct[key]
identifier = "%s[%s]" % (self.identifier, repr(key))
# GLOBAL: using global explorerPool
item = explorerPool.getExplorer(item, identifier)
return item
class ExplorerBuiltin(Explorer):
"""
@ivar name: the name the function was defined as
@ivar doc: function's docstring, or C{None} if unavailable
@ivar self: if not C{None}, the function is a method of this object.
"""
properties = ["doc", "name", "self"]
def __init__(self, function, identifier):
Explorer.__init__(self, function, identifier)
self.doc = function.__doc__
self.name = function.__name__
self.self = function.__self__
class ExplorerInstance(Explorer):
"""
Attribute groups:
- B{methods} -- dictionary of methods
- B{data} -- dictionary of data members
Note these are only the *instance* methods and members --
if you want the class methods, you'll have to look up the class.
TODO: Detail levels (me, me & class, me & class ancestory)
@ivar klass: the class this is an instance of.
"""
properties = ["klass"]
attributeGroups = ["methods", "data"]
def __init__(self, instance, identifier):
Explorer.__init__(self, instance, identifier)
members = {}
methods = {}
for i in dir(instance):
# TODO: Make screening of private attributes configurable.
if i[0] == '_':
continue
mIdentifier = string.join([identifier, i], ".")
member = getattr(instance, i)
mType = type(member)
if mType is types.MethodType:
methods[i] = explorerPool.getExplorer(member, mIdentifier)
else:
members[i] = explorerPool.getExplorer(member, mIdentifier)
self.klass = explorerPool.getExplorer(instance.__class__,
self.identifier +
'.__class__')
self.data = members
self.methods = methods
class ExplorerClass(Explorer):
"""
@ivar name: the name the class was defined with
@ivar doc: the class's docstring
@ivar bases: a list of this class's base classes.
@ivar module: the module the class is defined in
Attribute groups:
- B{methods} -- class methods
- B{data} -- other members of the class
"""
properties = ["name", "doc", "bases", "module"]
attributeGroups = ["methods", "data"]
def __init__(self, theClass, identifier):
Explorer.__init__(self, theClass, identifier)
if not identifier:
identifier = theClass.__name__
members = {}
methods = {}
for i in dir(theClass):
if (i[0] == '_') and (i != '__init__'):
continue
mIdentifier = string.join([identifier, i], ".")
member = getattr(theClass, i)
mType = type(member)
if mType is types.MethodType:
methods[i] = explorerPool.getExplorer(member, mIdentifier)
else:
members[i] = explorerPool.getExplorer(member, mIdentifier)
self.name = theClass.__name__
self.doc = inspect.getdoc(theClass)
self.data = members
self.methods = methods
self.bases = explorerPool.getExplorer(theClass.__bases__,
identifier + ".__bases__")
self.module = getattr(theClass, '__module__', None)
class ExplorerFunction(Explorer):
properties = ["name", "doc", "file", "line","signature"]
"""
name -- the name the function was defined as
signature -- the function's calling signature (Signature instance)
doc -- the function's docstring
file -- the file the function is defined in
line -- the line in the file the function begins on
"""
def __init__(self, function, identifier):
Explorer.__init__(self, function, identifier)
code = function.func_code
argcount = code.co_argcount
takesList = (code.co_flags & 0x04) and 1
takesKeywords = (code.co_flags & 0x08) and 1
n = (argcount + takesList + takesKeywords)
signature = Signature(code.co_varnames[:n])
if function.func_defaults:
i_d = 0
for i in xrange(argcount - len(function.func_defaults),
argcount):
default = function.func_defaults[i_d]
default = explorerPool.getExplorer(
default, '%s.func_defaults[%d]' % (identifier, i_d))
signature.set_default(i, default)
i_d = i_d + 1
if takesKeywords:
signature.set_keyword(n - 1)
if takesList:
signature.set_varlist(n - 1 - takesKeywords)
# maybe also: function.func_globals,
# or at least func_globals.__name__?
# maybe the bytecode, for disassembly-view?
self.name = function.__name__
self.signature = signature
self.doc = inspect.getdoc(function)
self.file = code.co_filename
self.line = code.co_firstlineno
class ExplorerMethod(ExplorerFunction):
properties = ["self", "klass"]
"""
In addition to ExplorerFunction properties:
self -- the object I am bound to, or None if unbound
klass -- the class I am a method of
"""
def __init__(self, method, identifier):
function = method.im_func
if type(function) is types.InstanceType:
function = function.__call__.im_func
ExplorerFunction.__init__(self, function, identifier)
self.id = id(method)
self.klass = explorerPool.getExplorer(method.im_class,
identifier + '.im_class')
self.self = explorerPool.getExplorer(method.im_self,
identifier + '.im_self')
if method.im_self:
# I'm a bound method -- eat the 'self' arg.
self.signature.discardSelf()
class ExplorerModule(Explorer):
"""
@ivar name: the name the module was defined as
@ivar doc: documentation string for the module
@ivar file: the file the module is defined in
Attribute groups:
- B{classes} -- the public classes provided by the module
- B{functions} -- the public functions provided by the module
- B{data} -- the public data members provided by the module
(\"Public\" is taken to be \"anything that doesn't start with _\")
"""
properties = ["name","doc","file"]
attributeGroups = ["classes", "functions", "data"]
def __init__(self, module, identifier):
Explorer.__init__(self, module, identifier)
functions = {}
classes = {}
data = {}
for key, value in module.__dict__.items():
if key[0] == '_':
continue
mIdentifier = "%s.%s" % (identifier, key)
if type(value) is types.ClassType:
classes[key] = explorerPool.getExplorer(value,
mIdentifier)
elif type(value) is types.FunctionType:
functions[key] = explorerPool.getExplorer(value,
mIdentifier)
elif type(value) is types.ModuleType:
pass # pass on imported modules
else:
data[key] = explorerPool.getExplorer(value, mIdentifier)
self.name = module.__name__
self.doc = inspect.getdoc(module)
self.file = getattr(module, '__file__', None)
self.classes = classes
self.functions = functions
self.data = data
typeTable = {types.InstanceType: ExplorerInstance,
types.ClassType: ExplorerClass,
types.MethodType: ExplorerMethod,
types.FunctionType: ExplorerFunction,
types.ModuleType: ExplorerModule,
types.BuiltinFunctionType: ExplorerBuiltin,
types.ListType: ExplorerSequence,
types.TupleType: ExplorerSequence,
types.DictType: ExplorerMapping,
types.StringType: ExplorerImmutable,
types.NoneType: ExplorerImmutable,
types.IntType: ExplorerImmutable,
types.FloatType: ExplorerImmutable,
types.LongType: ExplorerImmutable,
types.ComplexType: ExplorerImmutable,
}
class Signature(pb.Copyable):
"""I represent the signature of a callable.
Signatures are immutable, so don't expect my contents to change once
they've been set.
"""
_FLAVOURLESS = None
_HAS_DEFAULT = 2
_VAR_LIST = 4
_KEYWORD_DICT = 8
def __init__(self, argNames):
self.name = argNames
self.default = [None] * len(argNames)
self.flavour = [None] * len(argNames)
def get_name(self, arg):
return self.name[arg]
def get_default(self, arg):
if arg is types.StringType:
arg = self.name.index(arg)
# Wouldn't it be nice if we just returned "None" when there
# wasn't a default? Well, yes, but often times "None" *is*
# the default, so return a tuple instead.
if self.flavour[arg] == self._HAS_DEFAULT:
return (True, self.default[arg])
else:
return (False, None)
def set_default(self, arg, value):
if arg is types.StringType:
arg = self.name.index(arg)
self.flavour[arg] = self._HAS_DEFAULT
self.default[arg] = value
def set_varlist(self, arg):
if arg is types.StringType:
arg = self.name.index(arg)
self.flavour[arg] = self._VAR_LIST
def set_keyword(self, arg):
if arg is types.StringType:
arg = self.name.index(arg)
self.flavour[arg] = self._KEYWORD_DICT
def is_varlist(self, arg):
if arg is types.StringType:
arg = self.name.index(arg)
return (self.flavour[arg] == self._VAR_LIST)
def is_keyword(self, arg):
if arg is types.StringType:
arg = self.name.index(arg)
return (self.flavour[arg] == self._KEYWORD_DICT)
def discardSelf(self):
"""Invoke me to discard the first argument if this is a bound method.
"""
## if self.name[0] != 'self':
## log.msg("Warning: Told to discard self, but name is %s" %
## self.name[0])
self.name = self.name[1:]
self.default.pop(0)
self.flavour.pop(0)
def getStateToCopy(self):
return {'name': tuple(self.name),
'flavour': tuple(self.flavour),
'default': tuple(self.default)}
def __len__(self):
return len(self.name)
def __str__(self):
arglist = []
for arg in xrange(len(self)):
name = self.get_name(arg)
hasDefault, default = self.get_default(arg)
if hasDefault:
a = "%s=%s" % (name, default)
elif self.is_varlist(arg):
a = "*%s" % (name,)
elif self.is_keyword(arg):
a = "**%s" % (name,)
else:
a = name
arglist.append(a)
return string.join(arglist,", ")
class CRUFT_WatchyThingie:
# TODO:
#
# * an exclude mechanism for the watcher's browser, to avoid
# sending back large and uninteresting data structures.
#
# * an exclude mechanism for the watcher's trigger, to avoid
# triggering on some frequently-called-method-that-doesn't-
# actually-change-anything.
#
# * XXX! need removeWatch()
def watchIdentifier(self, identifier, callback):
"""Watch the object returned by evaluating the identifier.
Whenever I think the object might have changed, I'll send an
ObjectLink of it to the callback.
WARNING: This calls eval() on its argument!
"""
object = eval(identifier,
self.globalNamespace,
self.localNamespace)
return self.watchObject(object, identifier, callback)
def watchObject(self, object, identifier, callback):
"""Watch the given object.
Whenever I think the object might have changed, I'll send an
ObjectLink of it to the callback.
The identifier argument is used to generate identifiers for
objects which are members of this one.
"""
if type(object) is not types.InstanceType:
raise TypeError, "Sorry, can only place a watch on Instances."
# uninstallers = []
dct = {}
reflect.addMethodNamesToDict(object.__class__, dct, '')
for k in object.__dict__.keys():
dct[k] = 1
members = dct.keys()
clazzNS = {}
clazz = new.classobj('Watching%s%X' %
(object.__class__.__name__, id(object)),
(_MonkeysSetattrMixin, object.__class__,),
clazzNS)
clazzNS['_watchEmitChanged'] = new.instancemethod(
lambda slf, i=identifier, b=self, cb=callback:
cb(b.browseObject(slf, i)),
None, clazz)
# orig_class = object.__class__
object.__class__ = clazz
for name in members:
m = getattr(object, name)
# Only hook bound methods.
if ((type(m) is types.MethodType)
and (m.im_self is not None)):
# What's the use of putting watch monkeys on methods
# in addition to __setattr__? Well, um, uh, if the
# methods modify their attributes (i.e. add a key to
# a dictionary) instead of [re]setting them, then
# we wouldn't know about it unless we did this.
# (Is that convincing?)
monkey = _WatchMonkey(object)
monkey.install(name)
# uninstallers.append(monkey.uninstall)
# XXX: This probably prevents these objects from ever having a
# zero refcount. Leak, Leak!
## self.watchUninstallers[object] = uninstallers
class _WatchMonkey:
"""I hang on a method and tell you what I see.
TODO: Aya! Now I just do browseObject all the time, but I could
tell you what got called with what when and returning what.
"""
oldMethod = None
def __init__(self, instance):
"""Make a monkey to hang on this instance object.
"""
self.instance = instance
def install(self, methodIdentifier):
"""Install myself on my instance in place of this method.
"""
oldMethod = getattr(self.instance, methodIdentifier, None)
# XXX: this conditional probably isn't effective.
if oldMethod is not self:
# avoid triggering __setattr__
self.instance.__dict__[methodIdentifier] = (
new.instancemethod(self, self.instance,
self.instance.__class__))
self.oldMethod = (methodIdentifier, oldMethod)
def uninstall(self):
"""Remove myself from this instance and restore the original method.
(I hope.)
"""
if self.oldMethod is None:
return
# XXX: This probably doesn't work if multiple monkies are hanging
# on a method and they're not removed in order.
if self.oldMethod[1] is None:
delattr(self.instance, self.oldMethod[0])
else:
setattr(self.instance, self.oldMethod[0], self.oldMethod[1])
def __call__(self, instance, *a, **kw):
"""Pretend to be the method I replaced, and ring the bell.
"""
if self.oldMethod[1]:
rval = apply(self.oldMethod[1], a, kw)
else:
rval = None
instance._watchEmitChanged()
return rval
class _MonkeysSetattrMixin:
"""A mix-in class providing __setattr__ for objects being watched.
"""
def __setattr__(self, k, v):
"""Set the attribute and ring the bell.
"""
if hasattr(self.__class__.__bases__[1], '__setattr__'):
# Hack! Using __bases__[1] is Bad, but since we created
# this class, we can be reasonably sure it'll work.
self.__class__.__bases__[1].__setattr__(self, k, v)
else:
self.__dict__[k] = v
# XXX: Hey, waitasec, did someone just hang a new method on me?
# Do I need to put a monkey on it?
self._watchEmitChanged() | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/manhole/explorer.py | explorer.py |
__all__ = ['install']
# Twisted Imports
from twisted.python import log, threadable, runtime, failure, util, reflect
from twisted.internet.gtk2reactor import Gtk2Reactor as sup
import gtk
import gobject
import gtk.glade
COLUMN_DESCRIPTION = 0
COLUMN_TRANSPORT = 1
COLUMN_READING = 2
COLUMN_WRITING = 3
class GladeReactor(sup):
"""GTK+-2 event loop reactor with GUI.
"""
def listenTCP(self, port, factory, backlog=50, interface=''):
from _inspectro import LoggingFactory
factory = LoggingFactory(factory)
return sup.listenTCP(self, port, factory, backlog, interface)
def connectTCP(self, host, port, factory, timeout=30, bindAddress=None):
from _inspectro import LoggingFactory
factory = LoggingFactory(factory)
return sup.connectTCP(self, host, port, factory, timeout, bindAddress)
def listenSSL(self, port, factory, contextFactory, backlog=50, interface=''):
from _inspectro import LoggingFactory
factory = LoggingFactory(factory)
return sup.listenSSL(self, port, factory, contextFactory, backlog, interface)
def connectSSL(self, host, port, factory, contextFactory, timeout=30, bindAddress=None):
from _inspectro import LoggingFactory
factory = LoggingFactory(factory)
return sup.connectSSL(self, host, port, factory, contextFactory, timeout, bindAddress)
def connectUNIX(self, address, factory, timeout=30):
from _inspectro import LoggingFactory
factory = LoggingFactory(factory)
return sup.connectUNIX(self, address, factory, timeout)
def listenUNIX(self, address, factory, backlog=50, mode=0666):
from _inspectro import LoggingFactory
factory = LoggingFactory(factory)
return sup.listenUNIX(self, address, factory, backlog, mode)
def on_disconnect_clicked(self, w):
store, iter = self.servers.get_selection().get_selected()
store[iter][COLUMN_TRANSPORT].loseConnection()
def on_viewlog_clicked(self, w):
store, iter = self.servers.get_selection().get_selected()
data = store[iter][1]
from _inspectro import LogViewer
if hasattr(data, "protocol") and not data.protocol.logViewer:
LogViewer(data.protocol)
def on_inspect_clicked(self, w):
store, iter = self.servers.get_selection().get_selected()
data = store[iter]
from _inspectro import Inspectro
Inspectro(data[1])
def on_suspend_clicked(self, w):
store, iter = self.servers.get_selection().get_selected()
data = store[iter]
sup.removeReader(self, data[1])
sup.removeWriter(self, data[1])
if data[COLUMN_DESCRIPTION].endswith('(suspended)'):
if data[COLUMN_READING]:
sup.addReader(self, data[COLUMN_TRANSPORT])
if data[COLUMN_WRITING]:
sup.addWriter(self, data[COLUMN_TRANSPORT])
data[COLUMN_DESCRIPTION] = str(data[COLUMN_TRANSPORT])
self.toggle_suspend(1)
else:
data[0] += ' (suspended)'
self.toggle_suspend(0)
def toggle_suspend(self, suspending=0):
stock, nonstock = [('gtk-redo', 'Resume'),
('gtk-undo', 'Suspend')][suspending]
b = self.xml.get_widget("suspend")
b.set_use_stock(1)
b.set_label(stock)
b.get_child().get_child().get_children()[1].set_label(nonstock)
def servers_selection_changed(self, w):
store, iter = w.get_selected()
if iter is None:
self.xml.get_widget("suspend").set_sensitive(0)
self.xml.get_widget('disconnect').set_sensitive(0)
else:
data = store[iter]
self.toggle_suspend(not
data[COLUMN_DESCRIPTION].endswith('(suspended)'))
self.xml.get_widget("suspend").set_sensitive(1)
self.xml.get_widget('disconnect').set_sensitive(1)
def on_quit_clicked(self, w):
self.stop()
def __init__(self):
self.xml = gtk.glade.XML(util.sibpath(__file__,"gladereactor.glade"))
d = {}
for m in reflect.prefixedMethods(self, "on_"):
d[m.im_func.__name__] = m
self.xml.signal_autoconnect(d)
self.xml.get_widget('window1').connect('destroy',
lambda w: self.stop())
self.servers = self.xml.get_widget("servertree")
sel = self.servers.get_selection()
sel.set_mode(gtk.SELECTION_SINGLE)
sel.connect("changed",
self.servers_selection_changed)
## argh coredump: self.servers_selection_changed(sel)
self.xml.get_widget('suspend').set_sensitive(0)
self.xml.get_widget('disconnect').set_sensitive(0)
# setup model, connect it to my treeview
self.model = gtk.ListStore(str, object, gobject.TYPE_BOOLEAN,
gobject.TYPE_BOOLEAN)
self.servers.set_model(self.model)
self.servers.set_reorderable(1)
self.servers.set_headers_clickable(1)
# self.servers.set_headers_draggable(1)
# add a column
for col in [
gtk.TreeViewColumn('Server',
gtk.CellRendererText(),
text=0),
gtk.TreeViewColumn('Reading',
gtk.CellRendererToggle(),
active=2),
gtk.TreeViewColumn('Writing',
gtk.CellRendererToggle(),
active=3)]:
self.servers.append_column(col)
col.set_resizable(1)
sup.__init__(self)
def addReader(self, reader):
sup.addReader(self, reader)
## gtk docs suggest this - but it's stupid
## self.model.set(self.model.append(),
## 0, str(reader),
## 1, reader)
self._maybeAddServer(reader, read=1)
def _goAway(self,reader):
for p in range(len(self.model)):
if self.model[p][1] == reader:
self.model.remove(self.model.get_iter_from_string(str(p)))
return
def _maybeAddServer(self, reader, read=0, write=0):
p = 0
for x in self.model:
if x[1] == reader:
if reader == 0:
reader += 1
x[2] += read
x[3] += write
x[2] = max(x[2],0)
x[3] = max(x[3],0)
if not (x[2] or x[3]):
x[0] = x[0] + '(disconnected)'
self.callLater(5, self._goAway, reader)
return
p += 1
else:
read = max(read,0)
write = max(write, 0)
if read or write:
self.model.append((reader,reader,read,write))
def addWriter(self, writer):
sup.addWriter(self, writer)
self._maybeAddServer(writer, write=1)
def removeReader(self, reader):
sup.removeReader(self, reader)
self._maybeAddServer(reader, read=-1)
def removeWriter(self, writer):
sup.removeWriter(self, writer)
self._maybeAddServer(writer, write=-1)
def crash(self):
gtk.main_quit()
def run(self, installSignalHandlers=1):
self.startRunning(installSignalHandlers=installSignalHandlers)
self.simulate()
gtk.main()
def install():
"""Configure the twisted mainloop to be run inside the gtk mainloop.
"""
reactor = GladeReactor()
from twisted.internet.main import installReactor
installReactor(reactor)
return reactor | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/manhole/gladereactor.py | gladereactor.py |
import time
import gtk
import gobject
import gtk.glade
from twisted.python.util import sibpath
from twisted.python import reflect
from twisted.manhole.ui import gtk2manhole
from twisted.python.components import Adapter, registerAdapter
from twisted.python import log
from twisted.protocols import policies
from zope.interface import implements, Interface
# the glade file uses stock icons, which requires gnome to be installed
import gnome
version = "$Revision: 1.1 $"[11:-2]
gnome.init("gladereactor Inspector", version)
class ConsoleOutput(gtk2manhole.ConsoleOutput):
def _captureLocalLog(self):
self.fobs = log.FileLogObserver(gtk2manhole._Notafile(self, "log"))
self.fobs.start()
def stop(self):
self.fobs.stop()
del self.fobs
class ConsoleInput(gtk2manhole.ConsoleInput):
def sendMessage(self):
buffer = self.textView.get_buffer()
iter1, iter2 = buffer.get_bounds()
text = buffer.get_text(iter1, iter2, False)
self.do(text)
def do(self, text):
self.toplevel.do(text)
class INode(Interface):
"""A node in the inspector tree model.
"""
def __adapt__(adaptable, default):
if hasattr(adaptable, "__dict__"):
return InstanceNode(adaptable)
return AttributesNode(adaptable)
class InspectorNode(Adapter):
implements(INode)
def postInit(self, offset, parent, slot):
self.offset = offset
self.parent = parent
self.slot = slot
def getPath(self):
L = []
x = self
while x.parent is not None:
L.append(x.offset)
x = x.parent
L.reverse()
return L
def __getitem__(self, index):
slot, o = self.get(index)
n = INode(o, persist=False)
n.postInit(index, self, slot)
return n
def origstr(self):
return str(self.original)
def format(self):
return (self.slot, self.origstr())
class ConstantNode(InspectorNode):
def __len__(self):
return 0
class DictionaryNode(InspectorNode):
def get(self, index):
L = self.original.items()
L.sort()
return L[index]
def __len__(self):
return len(self.original)
def origstr(self):
return "Dictionary"
class ListNode(InspectorNode):
def get(self, index):
return index, self.original[index]
def origstr(self):
return "List"
def __len__(self):
return len(self.original)
class AttributesNode(InspectorNode):
def __len__(self):
return len(dir(self.original))
def get(self, index):
L = dir(self.original)
L.sort()
return L[index], getattr(self.original, L[index])
class InstanceNode(InspectorNode):
def __len__(self):
return len(self.original.__dict__) + 1
def get(self, index):
if index == 0:
if hasattr(self.original, "__class__"):
v = self.original.__class__
else:
v = type(self.original)
return "__class__", v
else:
index -= 1
L = self.original.__dict__.items()
L.sort()
return L[index]
import types
for x in dict, types.DictProxyType:
registerAdapter(DictionaryNode, x, INode)
for x in list, tuple:
registerAdapter(ListNode, x, INode)
for x in int, str:
registerAdapter(ConstantNode, x, INode)
class InspectorTreeModel(gtk.GenericTreeModel):
def __init__(self, root):
gtk.GenericTreeModel.__init__(self)
self.root = INode(root, persist=False)
self.root.postInit(0, None, 'root')
def on_get_flags(self):
return 0
def on_get_n_columns(self):
return 1
def on_get_column_type(self, index):
return gobject.TYPE_STRING
def on_get_path(self, node):
return node.getPath()
def on_get_iter(self, path):
x = self.root
for elem in path:
x = x[elem]
return x
def on_get_value(self, node, column):
return node.format()[column]
def on_iter_next(self, node):
try:
return node.parent[node.offset + 1]
except IndexError:
return None
def on_iter_children(self, node):
return node[0]
def on_iter_has_child(self, node):
return len(node)
def on_iter_n_children(self, node):
return len(node)
def on_iter_nth_child(self, node, n):
if node is None:
return None
return node[n]
def on_iter_parent(self, node):
return node.parent
class Inspectro:
selected = None
def __init__(self, o=None):
self.xml = x = gtk.glade.XML(sibpath(__file__, "inspectro.glade"))
self.tree_view = x.get_widget("treeview")
colnames = ["Name", "Value"]
for i in range(len(colnames)):
self.tree_view.append_column(
gtk.TreeViewColumn(
colnames[i], gtk.CellRendererText(), text=i))
d = {}
for m in reflect.prefixedMethods(self, "on_"):
d[m.im_func.__name__] = m
self.xml.signal_autoconnect(d)
if o is not None:
self.inspect(o)
self.ns = {'inspect': self.inspect}
iwidget = x.get_widget('input')
self.input = ConsoleInput(iwidget)
self.input.toplevel = self
iwidget.connect("key_press_event", self.input._on_key_press_event)
self.output = ConsoleOutput(x.get_widget('output'))
def select(self, o):
self.selected = o
self.ns['it'] = o
self.xml.get_widget("itname").set_text(repr(o))
self.xml.get_widget("itpath").set_text("???")
def inspect(self, o):
self.model = InspectorTreeModel(o)
self.tree_view.set_model(self.model)
self.inspected = o
def do(self, command):
filename = '<inspector>'
try:
print repr(command)
try:
code = compile(command, filename, 'eval')
except:
code = compile(command, filename, 'single')
val = eval(code, self.ns, self.ns)
if val is not None:
print repr(val)
self.ns['_'] = val
except:
log.err()
def on_inspect(self, *a):
self.inspect(self.selected)
def on_inspect_new(self, *a):
Inspectro(self.selected)
def on_row_activated(self, tv, path, column):
self.select(self.model.on_get_iter(path).original)
class LoggingProtocol(policies.ProtocolWrapper):
"""Log network traffic."""
logging = True
logViewer = None
def __init__(self, *args):
policies.ProtocolWrapper.__init__(self, *args)
self.inLog = []
self.outLog = []
def write(self, data):
if self.logging:
self.outLog.append((time.time(), data))
if self.logViewer:
self.logViewer.updateOut(self.outLog[-1])
policies.ProtocolWrapper.write(self, data)
def dataReceived(self, data):
if self.logging:
self.inLog.append((time.time(), data))
if self.logViewer:
self.logViewer.updateIn(self.inLog[-1])
policies.ProtocolWrapper.dataReceived(self, data)
def __repr__(self):
r = "wrapped " + repr(self.wrappedProtocol)
if self.logging:
r += " (logging)"
return r
class LoggingFactory(policies.WrappingFactory):
"""Wrap protocols with logging wrappers."""
protocol = LoggingProtocol
logging = True
def buildProtocol(self, addr):
p = self.protocol(self, self.wrappedFactory.buildProtocol(addr))
p.logging = self.logging
return p
def __repr__(self):
r = "wrapped " + repr(self.wrappedFactory)
if self.logging:
r += " (logging)"
return r
class LogViewer:
"""Display log of network traffic."""
def __init__(self, p):
self.p = p
vals = [time.time()]
if p.inLog:
vals.append(p.inLog[0][0])
if p.outLog:
vals.append(p.outLog[0][0])
self.startTime = min(vals)
p.logViewer = self
self.xml = x = gtk.glade.XML(sibpath(__file__, "logview.glade"))
self.xml.signal_autoconnect(self)
self.loglist = self.xml.get_widget("loglist")
# setup model, connect it to my treeview
self.model = gtk.ListStore(str, str, str)
self.loglist.set_model(self.model)
self.loglist.set_reorderable(1)
self.loglist.set_headers_clickable(1)
# self.servers.set_headers_draggable(1)
# add a column
for col in [
gtk.TreeViewColumn('Time',
gtk.CellRendererText(),
text=0),
gtk.TreeViewColumn('D',
gtk.CellRendererText(),
text=1),
gtk.TreeViewColumn('Data',
gtk.CellRendererText(),
text=2)]:
self.loglist.append_column(col)
col.set_resizable(1)
r = []
for t, data in p.inLog:
r.append(((str(t - self.startTime), "R", repr(data)[1:-1])))
for t, data in p.outLog:
r.append(((str(t - self.startTime), "S", repr(data)[1:-1])))
r.sort()
for i in r:
self.model.append(i)
def updateIn(self, (time, data)):
self.model.append((str(time - self.startTime), "R", repr(data)[1:-1]))
def updateOut(self, (time, data)):
self.model.append((str(time - self.startTime), "S", repr(data)[1:-1]))
def on_logview_destroy(self, w):
self.p.logViewer = None
del self.p
def main():
x = Inspectro()
x.inspect(x)
gtk.main()
if __name__ == '__main__':
import sys
log.startLogging(sys.stdout)
main() | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/manhole/_inspectro.py | _inspectro.py |
from twisted.python import log
# TODO:
# gzigzag-style navigation
class SillyModule:
def __init__(self, module, prefix):
self.__module = module
self.__prefix = prefix
def __getattr__(self, attr):
try:
return getattr(self.__module, self.__prefix + attr)
except AttributeError:
return getattr(self.__module, attr)
# We use gnome.ui because that's what happens to have Python bindings
# for the Canvas. I think this canvas widget is available seperately
# in "libart", but nobody's given me Python bindings for just that.
# The Gnome canvas is said to be modeled after the Tk canvas, so we
# could probably write this in Tk too. But my experience is with GTK,
# not with Tk, so this is what I use.
import gnome.ui
gnome = SillyModule(gnome.ui, 'Gnome')
import gtk
(True, False) = (gtk.TRUE, gtk.FALSE)
gtk = SillyModule(gtk, 'Gtk')
import GDK
from twisted.python import reflect, text
from twisted.spread import pb
from twisted.manhole import explorer
import string, sys, types
import UserList
_PIXELS_PER_UNIT=10
#### Support class.
class PairList(UserList.UserList):
"""An ordered list of key, value pairs.
Kinda like an ordered dictionary. Made with small data sets
in mind, as get() does a linear search, not hashing.
"""
def get(self, key):
i = 0
for k, v in self.data:
if key == k:
return (i, v)
i = i + 1
else:
return (None, None)
def keys(self):
return map(lambda x: x[0], self.data)
#### Public
class SpelunkDisplay(gnome.Canvas):
"""Spelunk widget.
The top-level widget for this module. This gtk.Widget is where the
explorer display will be, and this object is also your interface to
creating new visages.
"""
def __init__(self, aa=False):
gnome.Canvas.__init__(self, aa)
self.set_pixels_per_unit(_PIXELS_PER_UNIT)
self.visages = {}
def makeDefaultCanvas(self):
"""Make myself the default canvas which new visages are created on.
"""
# XXX: For some reason, the 'canvas' and 'parent' properties
# of CanvasItems aren't accessible thorugh pygnome.
Explorer.canvas = self
def receiveExplorer(self, xplorer):
if self.visages.has_key(xplorer.id):
log.msg("Using cached visage for %d" % (xplorer.id, ))
# Ikk. Just because we just received this explorer, that
# doesn't necessarily mean its attributes are fresh. Fix
# that, either by having this side pull or the server
# side push.
visage = self.visages[xplorer.id]
#xplorer.give_properties(visage)
#xplorer.give_attributes(visage)
else:
log.msg("Making new visage for %d" % (xplorer.id, ))
self.visages[xplorer.id] = xplorer.newVisage(self.root(),
self)
#### Base classes
class Explorer(pb.RemoteCache):
"""Base class for all RemoteCaches of explorer.Explorer cachables.
Meaning that when an Explorer comes back over the wire, one of
these is created. From this, you can make a Visage for the
SpelunkDisplay, or a widget to display as an Attribute.
"""
canvas = None
# From our cache:
id = None
identifier = None
explorerClass = None
attributeGroups = None
def newVisage(self, group, canvas=None):
"""Make a new visage for the object I explore.
Returns a Visage.
"""
canvas = canvas or self.canvas
klass = spelunkerClassTable.get(self.explorerClass, None)
if (not klass) or (klass[0] is None):
log.msg("%s not in table, using generic" % self.explorerClass)
klass = GenericVisage
else:
klass = klass[0]
spelunker = klass(self, group, canvas)
if hasattr(canvas, "visages") \
and not canvas.visages.has_key(self.id):
canvas.visages[self.id] = spelunker
self.give_properties(spelunker)
self.give_attributes(spelunker)
return spelunker
def newAttributeWidget(self, group):
"""Make a new attribute item for my object.
Returns a gtk.Widget.
"""
klass = spelunkerClassTable.get(self.explorerClass, None)
if (not klass) or (klass[1] is None):
log.msg("%s not in table, using generic" % self.explorerClass)
klass = GenericAttributeWidget
else:
klass = klass[1]
return klass(self, group)
def give_properties(self, spelunker):
"""Give a spelunker my properties in an ordered list.
"""
valuelist = PairList()
for p in spelunker.propertyLabels.keys():
value = getattr(self, p, None)
valuelist.append((p,value))
spelunker.fill_properties(valuelist)
def give_attributes(self, spelunker):
for a in spelunker.groupLabels.keys():
things = getattr(self, a)
spelunker.fill_attributeGroup(a, things)
class _LooseBoxBorder:
box = None
color = 'black'
width = 1
def __init__(self, box):
self.box = box
class LooseBox(gnome.CanvasGroup):
def __init__(self):
self.border = _LooseBoxBorder(self)
class Visage(gnome.CanvasGroup):
"""A \"face\" of an object under exploration.
A Visage is a representation of an object presented to the user.
The \"face\" in \"interface\".
'propertyLabels' and 'groupLabels' are lists of (key, name)
2-ples, with 'key' being the string the property or group is
denoted by in the code, and 'name' being the pretty human-readable
string you want me to show on the Visage. These attributes are
accumulated from base classes as well.
I am a gnome.CanvasItem (more specifically, CanvasGroup).
"""
color = {'border': '#006644'}
border_width = 8
detail_level = 0
# These are mappings from the strings the code calls these by
# and the pretty names you want to see on the screen.
# (e.g. Capitalized or localized)
propertyLabels = []
groupLabels = []
drag_x0 = 0
drag_y0 = 0
def __init__(self, explorer, rootGroup, canvas):
"""Place a new Visage of an explorer in a canvas group.
I also need a 'canvas' reference is for certain coordinate
conversions, and pygnome doesn't give access to my GtkObject's
.canvas attribute. :(
"""
# Ugh. PyGtk/GtkObject/GnomeCanvas interfacing grits.
gnome.CanvasGroup.__init__(self,
_obj = rootGroup.add('group')._o)
self.propertyLabels = PairList()
reflect.accumulateClassList(self.__class__, 'propertyLabels',
self.propertyLabels)
self.groupLabels = PairList()
reflect.accumulateClassList(self.__class__, 'groupLabels',
self.groupLabels)
self.explorer = explorer
self.identifier = explorer.identifier
self.objectId = explorer.id
self.canvas = canvas
self.rootGroup = rootGroup
self.ebox = gtk.EventBox()
self.ebox.set_name("Visage")
self.frame = gtk.Frame(self.identifier)
self.container = gtk.VBox()
self.ebox.add(self.frame)
self.frame.add(self.container)
self.canvasWidget = self.add('widget', widget=self.ebox,
x=0, y=0, anchor=gtk.ANCHOR_NW,
size_pixels=0)
self.border = self.add('rect', x1=0, y1=0,
x2=1, y2=1,
fill_color=None,
outline_color=self.color['border'],
width_pixels=self.border_width)
self.subtable = {}
self._setup_table()
# TODO:
# Collapse me
# Movable/resizeable me
# Destroy me
# Set my detail level
self.frame.connect("size_allocate", self.signal_size_allocate,
None)
self.connect("destroy", self.signal_destroy, None)
self.connect("event", self.signal_event)
self.ebox.show_all()
# Our creator will call our fill_ methods when she has the goods.
def _setup_table(self):
"""Called by __init__ to set up my main table.
You can easily override me instead of clobbering __init__.
"""
table = gtk.Table(len(self.propertyLabels), 2)
self.container.add(table)
table.set_name("PropertyTable")
self.subtable['properties'] = table
row = 0
for p, name in self.propertyLabels:
label = gtk.Label(name)
label.set_name("PropertyName")
label.set_data("property", p)
table.attach(label, 0, 1, row, row + 1)
label.set_alignment(0, 0)
row = row + 1
# XXX: make these guys collapsable
for g, name in self.groupLabels:
table = gtk.Table(1, 2)
self.container.add(table)
table.set_name("AttributeGroupTable")
self.subtable[g] = table
label = gtk.Label(name)
label.set_name("AttributeGroupTitle")
table.attach(label, 0, 2, 0, 1)
def fill_properties(self, propValues):
"""Fill in values for my properites.
Takes a list of (name, value) pairs. 'name' should be one of
the keys in my propertyLabels, and 'value' either an Explorer
or a string.
"""
table = self.subtable['properties']
table.resize(len(propValues), 2)
# XXX: Do I need to destroy previously attached children?
for name, value in propValues:
self.fill_property(name, value)
table.show_all()
def fill_property(self, property, value):
"""Set a value for a particular property.
'property' should be one of the keys in my propertyLabels.
"""
row, name = self.propertyLabels.get(property)
if type(value) is not types.InstanceType:
widget = gtk.Label(str(value))
widget.set_alignment(0, 0)
else:
widget = value.newAttributeWidget(self)
widget.set_name("PropertyValue")
self.subtable['properties'].attach(widget, 1, 2, row, row+1)
def fill_attributeGroup(self, group, attributes):
"""Provide members of an attribute group.
'group' should be one of the keys in my groupLabels, and
'attributes' a list of (name, value) pairs, with each value as
either an Explorer or string.
"""
# XXX: How to indicate detail level of members?
table = self.subtable[group]
if not attributes:
table.hide()
return
table.resize(len(attributes)+1, 2)
# XXX: Do I need to destroy previously attached children?
row = 1 # 0 is title
for name, value in attributes.items():
label = gtk.Label(name)
label.set_name("AttributeName")
label.set_alignment(0, 0)
if type(value) is types.StringType:
widget = gtk.Label(value)
widget.set_alignment(0, 0)
else:
widget = value.newAttributeWidget(self)
table.attach(label, 0, 1, row, row + 1)
table.attach(widget, 1, 2, row, row + 1)
row = row + 1
table.show_all()
def signal_event(self, widget, event=None):
if not event:
log.msg("Huh? got event signal with no event.")
return
if event.type == GDK.BUTTON_PRESS:
if event.button == 1:
self.drag_x0, self.drag_y0 = event.x, event.y
return True
elif event.type == GDK.MOTION_NOTIFY:
if event.state & GDK.BUTTON1_MASK:
self.move(event.x - self.drag_x0, event.y - self.drag_y0)
self.drag_x0, self.drag_y0 = event.x, event.y
return True
return False
def signal_size_allocate(self, frame_widget,
unusable_allocation, unused_data):
(x, y, w, h) = frame_widget.get_allocation()
# XXX: allocation PyCObject is apparently unusable!
# (w, h) = allocation.width, allocation.height
w, h = (float(w)/_PIXELS_PER_UNIT, float(h)/_PIXELS_PER_UNIT)
x1, y1 = (self.canvasWidget['x'], self.canvasWidget['y'])
b = self.border
(b['x1'], b['y1'], b['x2'], b['y2']) = (x1, y1, x1+w, y1+h)
def signal_destroy(self, unused_object, unused_data):
del self.explorer
del self.canvasWidget
del self.border
del self.ebox
del self.frame
del self.container
self.subtable.clear()
class AttributeWidget(gtk.Widget):
"""A widget briefly describing an object.
This is similar to a Visage, but has far less detail. This should
display only essential identifiying information, a gtk.Widget
suitable for including in a single table cell.
(gtk.Widgets are used here instead of the more graphically
pleasing gnome.CanvasItems because I was too lazy to re-write
gtk.table for the canvas. A new table widget/item would be great
though, not only for canvas prettiness, but also because we could
use one with a mone pythonic API.)
"""
def __init__(self, explorer, parent):
"""A new AttributeWidget describing an explorer.
"""
self.parent = parent
self.explorer = explorer
self.identifier = explorer.identifier
self.id = explorer.id
widgetObj = self._makeWidgetObject()
gtk.Widget.__init__(self, _obj=widgetObj)
self.set_name("AttributeValue")
self.connect("destroy", self.signal_destroy, None)
self.connect("button-press-event", self.signal_buttonPressEvent,
None)
def getTextForLabel(self):
"""Returns text for my label.
The default implementation of AttributeWidget is a gtk.Label
widget. You may override this method to change the text which
appears in the label. However, if you don't want to be a
label, override _makeWidgetObject instead.
"""
return self.identifier
def _makeWidgetObject(self):
"""Make the GTK widget object that is me.
Called by __init__ to construct the GtkObject I wrap-- the ._o
member of a pygtk GtkObject. Isn't subclassing GtkObjects in
Python fun?
"""
ebox = gtk.EventBox()
label = gtk.Label(self.getTextForLabel())
label.set_alignment(0,0)
ebox.add(label)
return ebox._o
def signal_destroy(self, unused_object, unused_data):
del self.explorer
def signal_buttonPressEvent(self, widget, eventButton, unused_data):
if eventButton.type == GDK._2BUTTON_PRESS:
if self.parent.canvas.visages.has_key(self.explorer.id):
visage = self.parent.canvas.visages[self.explorer.id]
else:
visage = self.explorer.newVisage(self.parent.rootGroup,
self.parent.canvas)
(x, y, w, h) = self.get_allocation()
wx, wy = self.parent.canvas.c2w(x, y)
x1, y1, x2, y2 = self.parent.get_bounds()
v_x1, v_y1, v_x2, v_y2 = visage.get_bounds()
visage.move(x2 - v_x1, wy + y1 - v_y1)
#### Widget-specific subclasses of Explorer, Visage, and Attribute
# Instance
class ExplorerInstance(Explorer):
pass
class InstanceVisage(Visage):
# Detail levels:
# Just me
# me and my class
# me and my whole class heirarchy
propertyLabels = [('klass', "Class")]
groupLabels = [('data', "Data"),
('methods', "Methods")]
detail = 0
def __init__(self, explorer, group, canvas):
Visage.__init__(self, explorer, group, canvas)
class_identifier = self.explorer.klass.name
# XXX: include partial module name in class?
self.frame.set_label("%s (%s)" % (self.identifier,
class_identifier))
class InstanceAttributeWidget(AttributeWidget):
def getTextForLabel(self):
return "%s instance" % (self.explorer.klass.name,)
# Class
class ExplorerClass(Explorer):
pass
class ClassVisage(Visage):
propertyLabels = [("name", "Name"),
("module", "Module"),
("bases", "Bases")]
groupLabels = [('data', "Data"),
('methods', "Methods")]
def fill_properties(self, propValues):
Visage.fill_properties(self, propValues)
basesExplorer = propValues.get('bases')[1]
basesExplorer.view.callRemote("get_elements").addCallback(self.fill_bases)
def fill_bases(self, baseExplorers):
box = gtk.HBox()
for b in baseExplorers:
box.add(b.newAttributeWidget(self))
row = self.propertyLabels.get('bases')[0]
self.subtable["properties"].attach(box, 1, 2, row, row+1)
box.show_all()
class ClassAttributeWidget(AttributeWidget):
def getTextForLabel(self):
return self.explorer.name
# Function
class ExplorerFunction(Explorer):
pass
class FunctionAttributeWidget(AttributeWidget):
def getTextForLabel(self):
signature = self.explorer.signature
arglist = []
for arg in xrange(len(signature)):
name = signature.name[arg]
hasDefault, default = signature.get_default(arg)
if hasDefault:
if default.explorerClass == "ExplorerImmutable":
default = default.value
else:
# XXX
pass
a = "%s=%s" % (name, default)
elif signature.is_varlist(arg):
a = "*%s" % (name,)
elif signature.is_keyword(arg):
a = "**%s" % (name,)
else:
a = name
arglist.append(a)
return string.join(arglist, ", ")
# Method
class ExplorerMethod(ExplorerFunction):
pass
class MethodAttributeWidget(FunctionAttributeWidget):
pass
class ExplorerBulitin(Explorer):
pass
class ExplorerModule(Explorer):
pass
class ExplorerSequence(Explorer):
pass
# Sequence
class SequenceVisage(Visage):
propertyLabels = [('len', 'length')]
# XXX: add elements group
class SequenceAttributeWidget(AttributeWidget):
def getTextForLabel(self):
# XXX: Differentiate between lists and tuples.
if self.explorer.len:
txt = "list of length %d" % (self.explorer.len,)
else:
txt = "[]"
return txt
# Mapping
class ExplorerMapping(Explorer):
pass
class MappingVisage(Visage):
propertyLabels = [('len', 'length')]
# XXX: add items group
class MappingAttributeWidget(AttributeWidget):
def getTextForLabel(self):
if self.explorer.len:
txt = "dict with %d elements" % (self.explorer.len,)
else:
txt = "{}"
return txt
class ExplorerImmutable(Explorer):
pass
# Immutable
class ImmutableVisage(Visage):
def __init__(self, explorer, rootGroup, canvas):
Visage.__init__(self, explorer, rootGroup, canvas)
widget = explorer.newAttributeWidget(self)
self.container.add(widget)
self.container.show_all()
class ImmutableAttributeWidget(AttributeWidget):
def getTextForLabel(self):
return repr(self.explorer.value)
#### misc. module definitions
spelunkerClassTable = {
"ExplorerInstance": (InstanceVisage, InstanceAttributeWidget),
"ExplorerFunction": (None, FunctionAttributeWidget),
"ExplorerMethod": (None, MethodAttributeWidget),
"ExplorerImmutable": (ImmutableVisage, ImmutableAttributeWidget),
"ExplorerClass": (ClassVisage, ClassAttributeWidget),
"ExplorerSequence": (SequenceVisage, SequenceAttributeWidget),
"ExplorerMapping": (MappingVisage, MappingAttributeWidget),
}
GenericVisage = Visage
GenericAttributeWidget = AttributeWidget
pb.setCopierForClassTree(sys.modules[__name__],
Explorer, 'twisted.manhole.explorer') | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/manhole/ui/spelunk_gnome.py | spelunk_gnome.py |
# TODO:
# * send script
# * replace method
# * save readline history
# * save-history-as-python
# * save transcript
# * identifier completion
import code, string, sys, traceback, types
import gtk
from twisted.python import rebuild, util
from twisted.spread.ui import gtkutil
from twisted.spread import pb
from twisted.manhole import explorer
True = gtk.TRUE
False = gtk.FALSE
try:
import spelunk_gnome
except ImportError:
_GNOME_POWER = False
else:
_GNOME_POWER = True
## def findBeginningOfLineWithPoint(entry):
## pos = entry.get_point()
## while pos:
## pos = pos - 1
## c = entry.get_chars(pos, pos+1)
## if c == '\n':
## return pos+1
## return 0
import pywidgets
class Interaction(pywidgets.Interaction, pb.Referenceable):
loginWindow = None
capabilities = {
"Explorer": 'Set',
}
def __init__(self):
pywidgets.Interaction.__init__(self)
self.signal_connect('destroy', gtk.mainquit, None)
if _GNOME_POWER:
self.display = BrowserDisplay()
dWindow = gtk.GtkWindow(title="Spelunking")
dWindow.add(self.display)
dWindow.show_all()
self.display.makeDefaultCanvas()
else:
self.display = BrowserDisplay(self)
# The referencable attached to the Perspective
self.client = self
def remote_console(self, message):
self.output.console(message)
def remote_receiveExplorer(self, xplorer):
if _GNOME_POWER:
self.display.receiveExplorer(xplorer)
else:
XXX # text display?
def remote_listCapabilities(self):
return self.capabilities
def connected(self, perspective):
self.loginWindow.hide()
self.name = self.loginWindow.username.get_text()
self.hostname = self.loginWindow.hostname.get_text()
perspective.broker.notifyOnDisconnect(self.connectionLost)
self.perspective = perspective
self.show_all()
self.set_title("Manhole: %s@%s" % (self.name, self.hostname))
def connectionLost(self, reason=None):
if not reason:
reason = "Connection Lost"
self.loginWindow.loginReport(reason)
self.hide()
self.loginWindow.show()
def codeInput(self, text):
methodName = 'do'
if text[0] == '/':
split = string.split(text[1:],' ',1)
statement = split[0]
if len(split) == 2:
remainder = split[1]
if statement in ('browse', 'explore'):
methodName = 'explore'
text = remainder
elif statement == 'watch':
methodName = 'watch'
text = remainder
elif statement == 'self_rebuild':
rebuild.rebuild(explorer)
if _GNOME_POWER:
rebuild.rebuild(spelunk_gnome)
rebuild.rebuild(sys.modules[__name__])
return
try:
self.perspective.callRemote(methodName, text)
except pb.ProtocolError:
# ASSUMPTION: pb.ProtocolError means we lost our connection.
(eType, eVal, tb) = sys.exc_info()
del tb
s = string.join(traceback.format_exception_only(eType, eVal),
'')
self.connectionLost(s)
except:
traceback.print_exc()
gtk.mainquit()
class LineOrientedBrowserDisplay:
def __init__(self, toplevel=None):
if toplevel:
self.toplevel = toplevel
def receiveBrowserObject(self, obj):
"""Display a browser ObjectLink.
"""
# This is a stop-gap implementation. Ideally, everything
# would be nicely formatted with pretty colours and you could
# select referenced objects to browse them with
# browse(selectedLink.identifier)
if obj.type in map(explorer.typeString, [types.FunctionType,
types.MethodType]):
arglist = []
for arg in obj.value['signature']:
if arg.has_key('default'):
a = "%s=%s" % (arg['name'], arg['default'])
elif arg.has_key('list'):
a = "*%s" % (arg['name'],)
elif arg.has_key('keywords'):
a = "**%s" % (arg['name'],)
else:
a = arg['name']
arglist.append(a)
things = ''
if obj.value.has_key('class'):
things = "Class: %s\n" % (obj.value['class'],)
if obj.value.has_key('self'):
things = things + "Self: %s\n" % (obj.value['self'],)
s = "%(name)s(%(arglist)s)\n%(things)s\n%(doc)s\n" % {
'name': obj.value['name'],
'doc': obj.value['doc'],
'things': things,
'arglist': string.join(arglist,", "),
}
else:
s = str(obj) + '\n'
self.toplevel.output.console([('stdout',s)])
if _GNOME_POWER:
BrowserDisplay = spelunk_gnome.SpelunkDisplay
else:
BrowserDisplay = LineOrientedBrowserDisplay
class Signature(pb.RemoteCopy, explorer.Signature):
def __init__(self):
pass
__str__ = explorer.Signature.__str__
pb.setCopierForClass('twisted.manhole.explorer.Signature', Signature) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/manhole/ui/gtkmanhole.py | gtkmanhole.py |
__version__ = '$Revision: 1.9 $'[11:-2]
from twisted import copyright
from twisted.internet import reactor
from twisted.python import components, failure, log, util
from twisted.spread import pb
from twisted.spread.ui import gtk2util
from twisted.manhole.service import IManholeClient
from zope.interface import implements
# The pygtk.require for version 2.0 has already been done by the reactor.
import gtk
import code, types, inspect
# TODO:
# Make wrap-mode a run-time option.
# Explorer.
# Code doesn't cleanly handle opening a second connection. Fix that.
# Make some acknowledgement of when a command has completed, even if
# it has no return value so it doesn't print anything to the console.
class OfflineError(Exception):
pass
class ManholeWindow(components.Componentized, gtk2util.GladeKeeper):
gladefile = util.sibpath(__file__, "gtk2manhole.glade")
_widgets = ('input','output','manholeWindow')
def __init__(self):
self.defaults = {}
gtk2util.GladeKeeper.__init__(self)
components.Componentized.__init__(self)
self.input = ConsoleInput(self._input)
self.input.toplevel = self
self.output = ConsoleOutput(self._output)
# Ugh. GladeKeeper actually isn't so good for composite objects.
# I want this connected to the ConsoleInput's handler, not something
# on this class.
self._input.connect("key_press_event", self.input._on_key_press_event)
def setDefaults(self, defaults):
self.defaults = defaults
def login(self):
client = self.getComponent(IManholeClient)
d = gtk2util.login(client, **self.defaults)
d.addCallback(self._cbLogin)
d.addCallback(client._cbLogin)
d.addErrback(self._ebLogin)
def _cbDisconnected(self, perspective):
self.output.append("%s went away. :(\n" % (perspective,), "local")
self._manholeWindow.set_title("Manhole")
def _cbLogin(self, perspective):
peer = perspective.broker.transport.getPeer()
self.output.append("Connected to %s\n" % (peer,), "local")
perspective.notifyOnDisconnect(self._cbDisconnected)
self._manholeWindow.set_title("Manhole - %s" % (peer))
return perspective
def _ebLogin(self, reason):
self.output.append("Login FAILED %s\n" % (reason.value,), "exception")
def _on_aboutMenuItem_activate(self, widget, *unused):
import sys
from os import path
self.output.append("""\
a Twisted Manhole client
Versions:
%(twistedVer)s
Python %(pythonVer)s on %(platform)s
GTK %(gtkVer)s / PyGTK %(pygtkVer)s
%(module)s %(modVer)s
http://twistedmatrix.com/
""" % {'twistedVer': copyright.longversion,
'pythonVer': sys.version.replace('\n', '\n '),
'platform': sys.platform,
'gtkVer': ".".join(map(str, gtk.gtk_version)),
'pygtkVer': ".".join(map(str, gtk.pygtk_version)),
'module': path.basename(__file__),
'modVer': __version__,
}, "local")
def _on_openMenuItem_activate(self, widget, userdata=None):
self.login()
def _on_manholeWindow_delete_event(self, widget, *unused):
reactor.stop()
def _on_quitMenuItem_activate(self, widget, *unused):
reactor.stop()
def on_reload_self_activate(self, *unused):
from twisted.python import rebuild
rebuild.rebuild(inspect.getmodule(self.__class__))
tagdefs = {
'default': {"family": "monospace"},
# These are message types we get from the server.
'stdout': {"foreground": "black"},
'stderr': {"foreground": "#AA8000"},
'result': {"foreground": "blue"},
'exception': {"foreground": "red"},
# Messages generate locally.
'local': {"foreground": "#008000"},
'log': {"foreground": "#000080"},
'command': {"foreground": "#666666"},
}
# TODO: Factor Python console stuff back out to pywidgets.
class ConsoleOutput:
_willScroll = None
def __init__(self, textView):
self.textView = textView
self.buffer = textView.get_buffer()
# TODO: Make this a singleton tag table.
for name, props in tagdefs.iteritems():
tag = self.buffer.create_tag(name)
# This can be done in the constructor in newer pygtk (post 1.99.14)
for k, v in props.iteritems():
tag.set_property(k, v)
self.buffer.tag_table.lookup("default").set_priority(0)
self._captureLocalLog()
def _captureLocalLog(self):
return log.startLogging(_Notafile(self, "log"), setStdout=False)
def append(self, text, kind=None):
# XXX: It seems weird to have to do this thing with always applying
# a 'default' tag. Can't we change the fundamental look instead?
tags = ["default"]
if kind is not None:
tags.append(kind)
self.buffer.insert_with_tags_by_name(self.buffer.get_end_iter(),
text, *tags)
# Silly things, the TextView needs to update itself before it knows
# where the bottom is.
if self._willScroll is None:
self._willScroll = gtk.idle_add(self._scrollDown)
def _scrollDown(self, *unused):
self.textView.scroll_to_iter(self.buffer.get_end_iter(), 0,
True, 1.0, 1.0)
self._willScroll = None
return False
class History:
def __init__(self, maxhist=10000):
self.ringbuffer = ['']
self.maxhist = maxhist
self.histCursor = 0
def append(self, htext):
self.ringbuffer.insert(-1, htext)
if len(self.ringbuffer) > self.maxhist:
self.ringbuffer.pop(0)
self.histCursor = len(self.ringbuffer) - 1
self.ringbuffer[-1] = ''
def move(self, prevnext=1):
'''
Return next/previous item in the history, stopping at top/bottom.
'''
hcpn = self.histCursor + prevnext
if hcpn >= 0 and hcpn < len(self.ringbuffer):
self.histCursor = hcpn
return self.ringbuffer[hcpn]
else:
return None
def histup(self, textbuffer):
if self.histCursor == len(self.ringbuffer) - 1:
si, ei = textbuffer.get_start_iter(), textbuffer.get_end_iter()
self.ringbuffer[-1] = textbuffer.get_text(si,ei)
newtext = self.move(-1)
if newtext is None:
return
textbuffer.set_text(newtext)
def histdown(self, textbuffer):
newtext = self.move(1)
if newtext is None:
return
textbuffer.set_text(newtext)
class ConsoleInput:
toplevel, rkeymap = None, None
__debug = False
def __init__(self, textView):
self.textView=textView
self.rkeymap = {}
self.history = History()
for name in dir(gtk.keysyms):
try:
self.rkeymap[getattr(gtk.keysyms, name)] = name
except TypeError:
pass
def _on_key_press_event(self, entry, event):
stopSignal = False
ksym = self.rkeymap.get(event.keyval, None)
mods = []
for prefix, mask in [('ctrl', gtk.gdk.CONTROL_MASK), ('shift', gtk.gdk.SHIFT_MASK)]:
if event.state & mask:
mods.append(prefix)
if mods:
ksym = '_'.join(mods + [ksym])
if ksym:
rvalue = getattr(
self, 'key_%s' % ksym, lambda *a, **kw: None)(entry, event)
if self.__debug:
print ksym
return rvalue
def getText(self):
buffer = self.textView.get_buffer()
iter1, iter2 = buffer.get_bounds()
text = buffer.get_text(iter1, iter2, False)
return text
def setText(self, text):
self.textView.get_buffer().set_text(text)
def key_Return(self, entry, event):
text = self.getText()
# Figure out if that Return meant "next line" or "execute."
try:
c = code.compile_command(text)
except SyntaxError, e:
# This could conceivably piss you off if the client's python
# doesn't accept keywords that are known to the manhole's
# python.
point = buffer.get_iter_at_line_offset(e.lineno, e.offset)
buffer.place(point)
# TODO: Componentize!
self.toplevel.output.append(str(e), "exception")
except (OverflowError, ValueError), e:
self.toplevel.output.append(str(e), "exception")
else:
if c is not None:
self.sendMessage()
# Don't insert Return as a newline in the buffer.
self.history.append(text)
self.clear()
# entry.emit_stop_by_name("key_press_event")
return True
else:
# not a complete code block
return False
return False
def key_Up(self, entry, event):
# if I'm at the top, previous history item.
textbuffer = self.textView.get_buffer()
if textbuffer.get_iter_at_mark(textbuffer.get_insert()).get_line() == 0:
self.history.histup(textbuffer)
return True
return False
def key_Down(self, entry, event):
textbuffer = self.textView.get_buffer()
if textbuffer.get_iter_at_mark(textbuffer.get_insert()).get_line() == (
textbuffer.get_line_count() - 1):
self.history.histdown(textbuffer)
return True
return False
key_ctrl_p = key_Up
key_ctrl_n = key_Down
def key_ctrl_shift_F9(self, entry, event):
if self.__debug:
import pdb; pdb.set_trace()
def clear(self):
buffer = self.textView.get_buffer()
buffer.delete(*buffer.get_bounds())
def sendMessage(self):
buffer = self.textView.get_buffer()
iter1, iter2 = buffer.get_bounds()
text = buffer.get_text(iter1, iter2, False)
self.toplevel.output.append(pythonify(text), 'command')
# TODO: Componentize better!
try:
return self.toplevel.getComponent(IManholeClient).do(text)
except OfflineError:
self.toplevel.output.append("Not connected, command not sent.\n",
"exception")
def pythonify(text):
'''
Make some text appear as though it was typed in at a Python prompt.
'''
lines = text.split('\n')
lines[0] = '>>> ' + lines[0]
return '\n... '.join(lines) + '\n'
class _Notafile:
"""Curry to make failure.printTraceback work with the output widget."""
def __init__(self, output, kind):
self.output = output
self.kind = kind
def write(self, txt):
self.output.append(txt, self.kind)
def flush(self):
pass
class ManholeClient(components.Adapter, pb.Referenceable):
implements(IManholeClient)
capabilities = {
# "Explorer": 'Set',
"Failure": 'Set'
}
def _cbLogin(self, perspective):
self.perspective = perspective
perspective.notifyOnDisconnect(self._cbDisconnected)
return perspective
def remote_console(self, messages):
for kind, content in messages:
if isinstance(content, types.StringTypes):
self.original.output.append(content, kind)
elif (kind == "exception") and isinstance(content, failure.Failure):
content.printTraceback(_Notafile(self.original.output,
"exception"))
else:
self.original.output.append(str(content), kind)
def remote_receiveExplorer(self, xplorer):
pass
def remote_listCapabilities(self):
return self.capabilities
def _cbDisconnected(self, perspective):
self.perspective = None
def do(self, text):
if self.perspective is None:
raise OfflineError
return self.perspective.callRemote("do", text)
components.registerAdapter(ManholeClient, ManholeWindow, IManholeClient) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/manhole/ui/gtk2manhole.py | gtk2manhole.py |
import code, string, sys, traceback
import gtk
True = 1
False = 0
# Twisted Imports
from twisted.spread.ui import gtkutil
from twisted.python import util
rcfile = util.sibpath(__file__, 'gtkrc')
gtk.rc_parse(rcfile)
def isCursorOnFirstLine(entry):
firstnewline = string.find(entry.get_chars(0,-1), '\n')
if entry.get_point() <= firstnewline or firstnewline == -1:
return 1
def isCursorOnLastLine(entry):
if entry.get_point() >= string.rfind(string.rstrip(entry.get_chars(0,-1)), '\n'):
return 1
class InputText(gtk.GtkText):
linemode = 0
blockcount = 0
def __init__(self, toplevel=None):
gtk.GtkText.__init__(self)
self['name'] = 'Input'
self.set_editable(gtk.TRUE)
self.connect("key_press_event", self.processKey)
#self.set_word_wrap(gtk.TRUE)
self.history = []
self.histpos = 0
if toplevel:
self.toplevel = toplevel
def historyUp(self):
if self.histpos > 0:
self.histpos = self.histpos - 1
self.delete_text(0, -1)
self.insert_defaults(self.history[self.histpos])
self.set_position(0)
def historyDown(self):
if self.histpos < len(self.history) - 1:
self.histpos = self.histpos + 1
self.delete_text(0, -1)
self.insert_defaults(self.history[self.histpos])
elif self.histpos == len(self.history) - 1:
self.histpos = self.histpos + 1
self.delete_text(0, -1)
def processKey(self, entry, event):
# TODO: make key bindings easier to customize.
stopSignal = False
# ASSUMPTION: Assume Meta == mod4
isMeta = event.state & gtk.GDK.MOD4_MASK
if event.keyval == gtk.GDK.Return:
isShift = event.state & gtk.GDK.SHIFT_MASK
if isShift:
self.linemode = True
self.insert_defaults('\n')
else:
stopSignal = True
text = self.get_chars(0,-1)
if not text: return
try:
if text[0] == '/':
# It's a local-command, don't evaluate it as
# Python.
c = True
else:
# This will tell us it's a complete expression.
c = code.compile_command(text)
except SyntaxError, e:
# Ding!
self.set_positionLineOffset(e.lineno, e.offset)
print "offset", e.offset
errmsg = {'traceback': [],
'exception': [str(e) + '\n']}
self.toplevel.output.console([('exception', errmsg)])
except OverflowError, e:
e = traceback.format_exception_only(OverflowError, e)
errmsg = {'traceback': [],
'exception': e}
self.toplevel.output.console([('exception', errmsg)])
else:
if c is None:
self.linemode = True
stopSignal = False
else:
self.sendMessage(entry)
self.clear()
elif ((event.keyval == gtk.GDK.Up and isCursorOnFirstLine(self))
or (isMeta and event.string == 'p')):
self.historyUp()
stopSignal = True
elif ((event.keyval == gtk.GDK.Down and isCursorOnLastLine(self))
or (isMeta and event.string == 'n')):
self.historyDown()
stopSignal = True
if stopSignal:
self.emit_stop_by_name("key_press_event")
return True
def clear(self):
self.delete_text(0, -1)
self.linemode = False
def set_positionLineOffset(self, line, offset):
text = self.get_chars(0, -1)
pos = 0
for l in xrange(line - 1):
pos = string.index(text, '\n', pos) + 1
pos = pos + offset - 1
self.set_position(pos)
def sendMessage(self, unused_data=None):
text = self.get_chars(0,-1)
if self.linemode:
self.blockcount = self.blockcount + 1
fmt = ">>> # begin %s\n%%s\n#end %s\n" % (
self.blockcount, self.blockcount)
else:
fmt = ">>> %s\n"
self.history.append(text)
self.histpos = len(self.history)
self.toplevel.output.console([['command',fmt % text]])
self.toplevel.codeInput(text)
def readHistoryFile(self, filename=None):
if filename is None:
filename = self.historyfile
f = open(filename, 'r', 1)
self.history.extend(f.readlines())
f.close()
self.histpos = len(self.history)
def writeHistoryFile(self, filename=None):
if filename is None:
filename = self.historyfile
f = open(filename, 'a', 1)
f.writelines(self.history)
f.close()
class Interaction(gtk.GtkWindow):
titleText = "Abstract Python Console"
def __init__(self):
gtk.GtkWindow.__init__(self, gtk.WINDOW_TOPLEVEL)
self.set_title(self.titleText)
self.set_default_size(300, 300)
self.set_name("Manhole")
vbox = gtk.GtkVBox()
pane = gtk.GtkVPaned()
self.output = OutputConsole(toplevel=self)
pane.pack1(gtkutil.scrollify(self.output), gtk.TRUE, gtk.FALSE)
self.input = InputText(toplevel=self)
pane.pack2(gtkutil.scrollify(self.input), gtk.FALSE, gtk.TRUE)
vbox.pack_start(pane, 1,1,0)
self.add(vbox)
self.input.grab_focus()
def codeInput(self, text):
raise NotImplementedError("Bleh.")
class LocalInteraction(Interaction):
titleText = "Local Python Console"
def __init__(self):
Interaction.__init__(self)
self.globalNS = {}
self.localNS = {}
self.filename = "<gtk console>"
def codeInput(self, text):
from twisted.manhole.service import runInConsole
val = runInConsole(text, self.output.console,
self.globalNS, self.localNS, self.filename)
if val is not None:
self.localNS["_"] = val
self.output.console([("result", repr(val) + "\n")])
class OutputConsole(gtk.GtkText):
maxBufSz = 10000
def __init__(self, toplevel=None):
gtk.GtkText.__init__(self)
self['name'] = "Console"
gtkutil.defocusify(self)
#self.set_word_wrap(gtk.TRUE)
if toplevel:
self.toplevel = toplevel
def console(self, message):
self.set_point(self.get_length())
self.freeze()
previous_kind = None
style = self.get_style()
style_cache = {}
try:
for element in message:
if element[0] == 'exception':
s = traceback.format_list(element[1]['traceback'])
s.extend(element[1]['exception'])
s = string.join(s, '')
else:
s = element[1]
if element[0] != previous_kind:
style = style_cache.get(element[0], None)
if style is None:
gtk.rc_parse_string(
'widget \"Manhole.*.Console\" '
'style \"Console_%s\"\n'
% (element[0]))
self.set_rc_style()
style_cache[element[0]] = style = self.get_style()
# XXX: You'd think we'd use style.bg instead of 'None'
# here, but that doesn't seem to match the color of
# the backdrop.
self.insert(style.font, style.fg[gtk.STATE_NORMAL],
None, s)
previous_kind = element[0]
l = self.get_length()
diff = self.maxBufSz - l
if diff < 0:
diff = - diff
self.delete_text(0,diff)
finally:
self.thaw()
a = self.get_vadjustment()
a.set_value(a.upper - a.page_size) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/manhole/ui/pywidgets.py | pywidgets.py |
import time
import types
try:
import cStringIO as StringIO
except:
import StringIO
from twisted.protocols import basic
from twisted.python import log
def parseRange(text):
articles = text.split('-')
if len(articles) == 1:
try:
a = int(articles[0])
return a, a
except ValueError, e:
return None, None
elif len(articles) == 2:
try:
if len(articles[0]):
l = int(articles[0])
else:
l = None
if len(articles[1]):
h = int(articles[1])
else:
h = None
except ValueError, e:
return None, None
return l, h
def extractCode(line):
line = line.split(' ', 1)
if len(line) != 2:
return None
try:
return int(line[0]), line[1]
except ValueError:
return None
class NNTPError(Exception):
def __init__(self, string):
self.string = string
def __str__(self):
return 'NNTPError: %s' % self.string
class NNTPClient(basic.LineReceiver):
MAX_COMMAND_LENGTH = 510
def __init__(self):
self.currentGroup = None
self._state = []
self._error = []
self._inputBuffers = []
self._responseCodes = []
self._responseHandlers = []
self._postText = []
self._newState(self._statePassive, None, self._headerInitial)
def gotAllGroups(self, groups):
"Override for notification when fetchGroups() action is completed"
def getAllGroupsFailed(self, error):
"Override for notification when fetchGroups() action fails"
def gotOverview(self, overview):
"Override for notification when fetchOverview() action is completed"
def getOverviewFailed(self, error):
"Override for notification when fetchOverview() action fails"
def gotSubscriptions(self, subscriptions):
"Override for notification when fetchSubscriptions() action is completed"
def getSubscriptionsFailed(self, error):
"Override for notification when fetchSubscriptions() action fails"
def gotGroup(self, group):
"Override for notification when fetchGroup() action is completed"
def getGroupFailed(self, error):
"Override for notification when fetchGroup() action fails"
def gotArticle(self, article):
"Override for notification when fetchArticle() action is completed"
def getArticleFailed(self, error):
"Override for notification when fetchArticle() action fails"
def gotHead(self, head):
"Override for notification when fetchHead() action is completed"
def getHeadFailed(self, error):
"Override for notification when fetchHead() action fails"
def gotBody(self, info):
"Override for notification when fetchBody() action is completed"
def getBodyFailed(self, body):
"Override for notification when fetchBody() action fails"
def postedOk(self):
"Override for notification when postArticle() action is successful"
def postFailed(self, error):
"Override for notification when postArticle() action fails"
def gotXHeader(self, headers):
"Override for notification when getXHeader() action is successful"
def getXHeaderFailed(self, error):
"Override for notification when getXHeader() action fails"
def gotNewNews(self, news):
"Override for notification when getNewNews() action is successful"
def getNewNewsFailed(self, error):
"Override for notification when getNewNews() action fails"
def gotNewGroups(self, groups):
"Override for notification when getNewGroups() action is successful"
def getNewGroupsFailed(self, error):
"Override for notification when getNewGroups() action fails"
def setStreamSuccess(self):
"Override for notification when setStream() action is successful"
def setStreamFailed(self, error):
"Override for notification when setStream() action fails"
def fetchGroups(self):
"""
Request a list of all news groups from the server. gotAllGroups()
is called on success, getGroupsFailed() on failure
"""
self.sendLine('LIST')
self._newState(self._stateList, self.getAllGroupsFailed)
def fetchOverview(self):
"""
Request the overview format from the server. gotOverview() is called
on success, getOverviewFailed() on failure
"""
self.sendLine('LIST OVERVIEW.FMT')
self._newState(self._stateOverview, self.getOverviewFailed)
def fetchSubscriptions(self):
"""
Request a list of the groups it is recommended a new user subscribe to.
gotSubscriptions() is called on success, getSubscriptionsFailed() on
failure
"""
self.sendLine('LIST SUBSCRIPTIONS')
self._newState(self._stateSubscriptions, self.getSubscriptionsFailed)
def fetchGroup(self, group):
"""
Get group information for the specified group from the server. gotGroup()
is called on success, getGroupFailed() on failure.
"""
self.sendLine('GROUP %s' % (group,))
self._newState(None, self.getGroupFailed, self._headerGroup)
def fetchHead(self, index = ''):
"""
Get the header for the specified article (or the currently selected
article if index is '') from the server. gotHead() is called on
success, getHeadFailed() on failure
"""
self.sendLine('HEAD %s' % (index,))
self._newState(self._stateHead, self.getHeadFailed)
def fetchBody(self, index = ''):
"""
Get the body for the specified article (or the currently selected
article if index is '') from the server. gotBody() is called on
success, getBodyFailed() on failure
"""
self.sendLine('BODY %s' % (index,))
self._newState(self._stateBody, self.getBodyFailed)
def fetchArticle(self, index = ''):
"""
Get the complete article with the specified index (or the currently
selected article if index is '') or Message-ID from the server.
gotArticle() is called on success, getArticleFailed() on failure.
"""
self.sendLine('ARTICLE %s' % (index,))
self._newState(self._stateArticle, self.getArticleFailed)
def postArticle(self, text):
"""
Attempt to post an article with the specified text to the server. 'text'
must consist of both head and body data, as specified by RFC 850. If the
article is posted successfully, postedOk() is called, otherwise postFailed()
is called.
"""
self.sendLine('POST')
self._newState(None, self.postFailed, self._headerPost)
self._postText.append(text)
def fetchNewNews(self, groups, date, distributions = ''):
"""
Get the Message-IDs for all new news posted to any of the given
groups since the specified date - in seconds since the epoch, GMT -
optionally restricted to the given distributions. gotNewNews() is
called on success, getNewNewsFailed() on failure.
One invocation of this function may result in multiple invocations
of gotNewNews()/getNewNewsFailed().
"""
date, timeStr = time.strftime('%y%m%d %H%M%S', time.gmtime(date)).split()
line = 'NEWNEWS %%s %s %s %s' % (date, timeStr, distributions)
groupPart = ''
while len(groups) and len(line) + len(groupPart) + len(groups[-1]) + 1 < NNTPClient.MAX_COMMAND_LENGTH:
group = groups.pop()
groupPart = groupPart + ',' + group
self.sendLine(line % (groupPart,))
self._newState(self._stateNewNews, self.getNewNewsFailed)
if len(groups):
self.fetchNewNews(groups, date, distributions)
def fetchNewGroups(self, date, distributions):
"""
Get the names of all new groups created/added to the server since
the specified date - in seconds since the ecpoh, GMT - optionally
restricted to the given distributions. gotNewGroups() is called
on success, getNewGroupsFailed() on failure.
"""
date, timeStr = time.strftime('%y%m%d %H%M%S', time.gmtime(date)).split()
self.sendLine('NEWGROUPS %s %s %s' % (date, timeStr, distributions))
self._newState(self._stateNewGroups, self.getNewGroupsFailed)
def fetchXHeader(self, header, low = None, high = None, id = None):
"""
Request a specific header from the server for an article or range
of articles. If 'id' is not None, a header for only the article
with that Message-ID will be requested. If both low and high are
None, a header for the currently selected article will be selected;
If both low and high are zero-length strings, headers for all articles
in the currently selected group will be requested; Otherwise, high
and low will be used as bounds - if one is None the first or last
article index will be substituted, as appropriate.
"""
if id is not None:
r = header + ' <%s>' % (id,)
elif low is high is None:
r = header
elif high is None:
r = header + ' %d-' % (low,)
elif low is None:
r = header + ' -%d' % (high,)
else:
r = header + ' %d-%d' % (low, high)
self.sendLine('XHDR ' + r)
self._newState(self._stateXHDR, self.getXHeaderFailed)
def setStream(self):
"""
Set the mode to STREAM, suspending the normal "lock-step" mode of
communications. setStreamSuccess() is called on success,
setStreamFailed() on failure.
"""
self.sendLine('MODE STREAM')
self._newState(None, self.setStreamFailed, self._headerMode)
def quit(self):
self.sendLine('QUIT')
self.transport.loseConnection()
def _newState(self, method, error, responseHandler = None):
self._inputBuffers.append([])
self._responseCodes.append(None)
self._state.append(method)
self._error.append(error)
self._responseHandlers.append(responseHandler)
def _endState(self):
buf = self._inputBuffers[0]
del self._responseCodes[0]
del self._inputBuffers[0]
del self._state[0]
del self._error[0]
del self._responseHandlers[0]
return buf
def _newLine(self, line, check = 1):
if check and line and line[0] == '.':
line = line[1:]
self._inputBuffers[0].append(line)
def _setResponseCode(self, code):
self._responseCodes[0] = code
def _getResponseCode(self):
return self._responseCodes[0]
def lineReceived(self, line):
if not len(self._state):
self._statePassive(line)
elif self._getResponseCode() is None:
code = extractCode(line)
if code is None or not (200 <= code[0] < 400): # An error!
self._error[0](line)
self._endState()
else:
self._setResponseCode(code)
if self._responseHandlers[0]:
self._responseHandlers[0](code)
else:
self._state[0](line)
def _statePassive(self, line):
log.msg('Server said: %s' % line)
def _passiveError(self, error):
log.err('Passive Error: %s' % (error,))
def _headerInitial(self, (code, message)):
if code == 200:
self.canPost = 1
else:
self.canPost = 0
self._endState()
def _stateList(self, line):
if line != '.':
data = filter(None, line.strip().split())
self._newLine((data[0], int(data[1]), int(data[2]), data[3]), 0)
else:
self.gotAllGroups(self._endState())
def _stateOverview(self, line):
if line != '.':
self._newLine(filter(None, line.strip().split()), 0)
else:
self.gotOverview(self._endState())
def _stateSubscriptions(self, line):
if line != '.':
self._newLine(line.strip(), 0)
else:
self.gotSubscriptions(self._endState())
def _headerGroup(self, (code, line)):
self.gotGroup(tuple(line.split()))
self._endState()
def _stateArticle(self, line):
if line != '.':
if line.startswith('.'):
line = line[1:]
self._newLine(line, 0)
else:
self.gotArticle('\n'.join(self._endState())+'\n')
def _stateHead(self, line):
if line != '.':
self._newLine(line, 0)
else:
self.gotHead('\n'.join(self._endState()))
def _stateBody(self, line):
if line != '.':
if line.startswith('.'):
line = line[1:]
self._newLine(line, 0)
else:
self.gotBody('\n'.join(self._endState())+'\n')
def _headerPost(self, (code, message)):
if code == 340:
self.transport.write(self._postText[0].replace('\n', '\r\n').replace('\r\n.', '\r\n..'))
if self._postText[0][-1:] != '\n':
self.sendLine('')
self.sendLine('.')
del self._postText[0]
self._newState(None, self.postFailed, self._headerPosted)
else:
self.postFailed('%d %s' % (code, message))
self._endState()
def _headerPosted(self, (code, message)):
if code == 240:
self.postedOk()
else:
self.postFailed('%d %s' % (code, message))
self._endState()
def _stateXHDR(self, line):
if line != '.':
self._newLine(line.split(), 0)
else:
self._gotXHeader(self._endState())
def _stateNewNews(self, line):
if line != '.':
self._newLine(line, 0)
else:
self.gotNewNews(self._endState())
def _stateNewGroups(self, line):
if line != '.':
self._newLine(line, 0)
else:
self.gotNewGroups(self._endState())
def _headerMode(self, (code, message)):
if code == 203:
self.setStreamSuccess()
else:
self.setStreamFailed((code, message))
self._endState()
class NNTPServer(basic.LineReceiver):
COMMANDS = [
'LIST', 'GROUP', 'ARTICLE', 'STAT', 'MODE', 'LISTGROUP', 'XOVER',
'XHDR', 'HEAD', 'BODY', 'NEXT', 'LAST', 'POST', 'QUIT', 'IHAVE',
'HELP', 'SLAVE', 'XPATH', 'XINDEX', 'XROVER', 'TAKETHIS', 'CHECK'
]
def __init__(self):
self.servingSlave = 0
def connectionMade(self):
self.inputHandler = None
self.currentGroup = None
self.currentIndex = None
self.sendLine('200 server ready - posting allowed')
def lineReceived(self, line):
if self.inputHandler is not None:
self.inputHandler(line)
else:
parts = line.strip().split()
if len(parts):
cmd, parts = parts[0].upper(), parts[1:]
if cmd in NNTPServer.COMMANDS:
func = getattr(self, 'do_%s' % cmd)
try:
func(*parts)
except TypeError:
self.sendLine('501 command syntax error')
log.msg("501 command syntax error")
log.msg("command was", line)
log.deferr()
except:
self.sendLine('503 program fault - command not performed')
log.msg("503 program fault")
log.msg("command was", line)
log.deferr()
else:
self.sendLine('500 command not recognized')
def do_LIST(self, subcmd = '', *dummy):
subcmd = subcmd.strip().lower()
if subcmd == 'newsgroups':
# XXX - this could use a real implementation, eh?
self.sendLine('215 Descriptions in form "group description"')
self.sendLine('.')
elif subcmd == 'overview.fmt':
defer = self.factory.backend.overviewRequest()
defer.addCallbacks(self._gotOverview, self._errOverview)
log.msg('overview')
elif subcmd == 'subscriptions':
defer = self.factory.backend.subscriptionRequest()
defer.addCallbacks(self._gotSubscription, self._errSubscription)
log.msg('subscriptions')
elif subcmd == '':
defer = self.factory.backend.listRequest()
defer.addCallbacks(self._gotList, self._errList)
else:
self.sendLine('500 command not recognized')
def _gotList(self, list):
self.sendLine('215 newsgroups in form "group high low flags"')
for i in list:
self.sendLine('%s %d %d %s' % tuple(i))
self.sendLine('.')
def _errList(self, failure):
print 'LIST failed: ', failure
self.sendLine('503 program fault - command not performed')
def _gotSubscription(self, parts):
self.sendLine('215 information follows')
for i in parts:
self.sendLine(i)
self.sendLine('.')
def _errSubscription(self, failure):
print 'SUBSCRIPTIONS failed: ', failure
self.sendLine('503 program fault - comand not performed')
def _gotOverview(self, parts):
self.sendLine('215 Order of fields in overview database.')
for i in parts:
self.sendLine(i + ':')
self.sendLine('.')
def _errOverview(self, failure):
print 'LIST OVERVIEW.FMT failed: ', failure
self.sendLine('503 program fault - command not performed')
def do_LISTGROUP(self, group = None):
group = group or self.currentGroup
if group is None:
self.sendLine('412 Not currently in newsgroup')
else:
defer = self.factory.backend.listGroupRequest(group)
defer.addCallbacks(self._gotListGroup, self._errListGroup)
def _gotListGroup(self, (group, articles)):
self.currentGroup = group
if len(articles):
self.currentIndex = int(articles[0])
else:
self.currentIndex = None
self.sendLine('211 list of article numbers follow')
for i in articles:
self.sendLine(str(i))
self.sendLine('.')
def _errListGroup(self, failure):
print 'LISTGROUP failed: ', failure
self.sendLine('502 no permission')
def do_XOVER(self, range):
if self.currentGroup is None:
self.sendLine('412 No news group currently selected')
else:
l, h = parseRange(range)
defer = self.factory.backend.xoverRequest(self.currentGroup, l, h)
defer.addCallbacks(self._gotXOver, self._errXOver)
def _gotXOver(self, parts):
self.sendLine('224 Overview information follows')
for i in parts:
self.sendLine('\t'.join(map(str, i)))
self.sendLine('.')
def _errXOver(self, failure):
print 'XOVER failed: ', failure
self.sendLine('420 No article(s) selected')
def xhdrWork(self, header, range):
if self.currentGroup is None:
self.sendLine('412 No news group currently selected')
else:
if range is None:
if self.currentIndex is None:
self.sendLine('420 No current article selected')
return
else:
l = h = self.currentIndex
else:
# FIXME: articles may be a message-id
l, h = parseRange(range)
if l is h is None:
self.sendLine('430 no such article')
else:
return self.factory.backend.xhdrRequest(self.currentGroup, l, h, header)
def do_XHDR(self, header, range = None):
d = self.xhdrWork(header, range)
if d:
d.addCallbacks(self._gotXHDR, self._errXHDR)
def _gotXHDR(self, parts):
self.sendLine('221 Header follows')
for i in parts:
self.sendLine('%d %s' % i)
self.sendLine('.')
def _errXHDR(self, failure):
print 'XHDR failed: ', failure
self.sendLine('502 no permission')
def do_XROVER(self, header, range = None):
d = self.xhdrWork(header, range)
if d:
d.addCallbacks(self._gotXROVER, self._errXROVER)
def _gotXROVER(self, parts):
self.sendLine('224 Overview information follows')
for i in parts:
self.sendLine('%d %s' % i)
self.sendLine('.')
def _errXROVER(self, failure):
print 'XROVER failed: ',
self._errXHDR(failure)
def do_POST(self):
self.inputHandler = self._doingPost
self.message = ''
self.sendLine('340 send article to be posted. End with <CR-LF>.<CR-LF>')
def _doingPost(self, line):
if line == '.':
self.inputHandler = None
group, article = self.currentGroup, self.message
self.message = ''
defer = self.factory.backend.postRequest(article)
defer.addCallbacks(self._gotPost, self._errPost)
else:
self.message = self.message + line + '\r\n'
def _gotPost(self, parts):
self.sendLine('240 article posted ok')
def _errPost(self, failure):
print 'POST failed: ', failure
self.sendLine('441 posting failed')
def do_CHECK(self, id):
d = self.factory.backend.articleExistsRequest(id)
d.addCallbacks(self._gotCheck, self._errCheck)
def _gotCheck(self, result):
if result:
self.sendLine("438 already have it, please don't send it to me")
else:
self.sendLine('238 no such article found, please send it to me')
def _errCheck(self, failure):
print 'CHECK failed: ', failure
self.sendLine('431 try sending it again later')
def do_TAKETHIS(self, id):
self.inputHandler = self._doingTakeThis
self.message = ''
def _doingTakeThis(self, line):
if line == '.':
self.inputHandler = None
article = self.message
self.message = ''
d = self.factory.backend.postRequest(article)
d.addCallbacks(self._didTakeThis, self._errTakeThis)
else:
self.message = self.message + line + '\r\n'
def _didTakeThis(self, result):
self.sendLine('239 article transferred ok')
def _errTakeThis(self, failure):
print 'TAKETHIS failed: ', failure
self.sendLine('439 article transfer failed')
def do_GROUP(self, group):
defer = self.factory.backend.groupRequest(group)
defer.addCallbacks(self._gotGroup, self._errGroup)
def _gotGroup(self, (name, num, high, low, flags)):
self.currentGroup = name
self.currentIndex = low
self.sendLine('211 %d %d %d %s group selected' % (num, low, high, name))
def _errGroup(self, failure):
print 'GROUP failed: ', failure
self.sendLine('411 no such group')
def articleWork(self, article, cmd, func):
if self.currentGroup is None:
self.sendLine('412 no newsgroup has been selected')
else:
if not article:
if self.currentIndex is None:
self.sendLine('420 no current article has been selected')
else:
article = self.currentIndex
else:
if article[0] == '<':
return func(self.currentGroup, index = None, id = article)
else:
try:
article = int(article)
return func(self.currentGroup, article)
except ValueError, e:
self.sendLine('501 command syntax error')
def do_ARTICLE(self, article = None):
defer = self.articleWork(article, 'ARTICLE', self.factory.backend.articleRequest)
if defer:
defer.addCallbacks(self._gotArticle, self._errArticle)
def _gotArticle(self, (index, id, article)):
if isinstance(article, types.StringType):
import warnings
warnings.warn(
"Returning the article as a string from `articleRequest' "
"is deprecated. Return a file-like object instead."
)
article = StringIO.StringIO(article)
self.currentIndex = index
self.sendLine('220 %d %s article' % (index, id))
s = basic.FileSender()
d = s.beginFileTransfer(article, self.transport)
d.addCallback(self.finishedFileTransfer)
##
## Helper for FileSender
##
def finishedFileTransfer(self, lastsent):
if lastsent != '\n':
line = '\r\n.'
else:
line = '.'
self.sendLine(line)
##
def _errArticle(self, failure):
print 'ARTICLE failed: ', failure
self.sendLine('423 bad article number')
def do_STAT(self, article = None):
defer = self.articleWork(article, 'STAT', self.factory.backend.articleRequest)
if defer:
defer.addCallbacks(self._gotStat, self._errStat)
def _gotStat(self, (index, id, article)):
self.currentIndex = index
self.sendLine('223 %d %s article retreived - request text separately' % (index, id))
def _errStat(self, failure):
print 'STAT failed: ', failure
self.sendLine('423 bad article number')
def do_HEAD(self, article = None):
defer = self.articleWork(article, 'HEAD', self.factory.backend.headRequest)
if defer:
defer.addCallbacks(self._gotHead, self._errHead)
def _gotHead(self, (index, id, head)):
self.currentIndex = index
self.sendLine('221 %d %s article retrieved' % (index, id))
self.transport.write(head + '\r\n')
self.sendLine('.')
def _errHead(self, failure):
print 'HEAD failed: ', failure
self.sendLine('423 no such article number in this group')
def do_BODY(self, article):
defer = self.articleWork(article, 'BODY', self.factory.backend.bodyRequest)
if defer:
defer.addCallbacks(self._gotBody, self._errBody)
def _gotBody(self, (index, id, body)):
if isinstance(body, types.StringType):
import warnings
warnings.warn(
"Returning the article as a string from `articleRequest' "
"is deprecated. Return a file-like object instead."
)
body = StringIO.StringIO(body)
self.currentIndex = index
self.sendLine('221 %d %s article retrieved' % (index, id))
self.lastsent = ''
s = basic.FileSender()
d = s.beginFileTransfer(body, self.transport)
d.addCallback(self.finishedFileTransfer)
def _errBody(self, failure):
print 'BODY failed: ', failure
self.sendLine('423 no such article number in this group')
# NEXT and LAST are just STATs that increment currentIndex first.
# Accordingly, use the STAT callbacks.
def do_NEXT(self):
i = self.currentIndex + 1
defer = self.factory.backend.articleRequest(self.currentGroup, i)
defer.addCallbacks(self._gotStat, self._errStat)
def do_LAST(self):
i = self.currentIndex - 1
defer = self.factory.backend.articleRequest(self.currentGroup, i)
defer.addCallbacks(self._gotStat, self._errStat)
def do_MODE(self, cmd):
cmd = cmd.strip().upper()
if cmd == 'READER':
self.servingSlave = 0
self.sendLine('200 Hello, you can post')
elif cmd == 'STREAM':
self.sendLine('500 Command not understood')
else:
# This is not a mistake
self.sendLine('500 Command not understood')
def do_QUIT(self):
self.sendLine('205 goodbye')
self.transport.loseConnection()
def do_HELP(self):
self.sendLine('100 help text follows')
self.sendLine('Read the RFC.')
self.sendLine('.')
def do_SLAVE(self):
self.sendLine('202 slave status noted')
self.servingeSlave = 1
def do_XPATH(self, article):
# XPATH is a silly thing to have. No client has the right to ask
# for this piece of information from me, and so that is what I'll
# tell them.
self.sendLine('502 access restriction or permission denied')
def do_XINDEX(self, article):
# XINDEX is another silly command. The RFC suggests it be relegated
# to the history books, and who am I to disagree?
self.sendLine('502 access restriction or permission denied')
def do_XROVER(self, range = None):
self.do_XHDR(self, 'References', range)
def do_IHAVE(self, id):
self.factory.backend.articleExistsRequest(id).addCallback(self._foundArticle)
def _foundArticle(self, result):
if result:
self.sendLine('437 article rejected - do not try again')
else:
self.sendLine('335 send article to be transferred. End with <CR-LF>.<CR-LF>')
self.inputHandler = self._handleIHAVE
self.message = ''
def _handleIHAVE(self, line):
if line == '.':
self.inputHandler = None
self.factory.backend.postRequest(
self.message
).addCallbacks(self._gotIHAVE, self._errIHAVE)
self.message = ''
else:
self.message = self.message + line + '\r\n'
def _gotIHAVE(self, result):
self.sendLine('235 article transferred ok')
def _errIHAVE(self, failure):
print 'IHAVE failed: ', failure
self.sendLine('436 transfer failed - try again later')
class UsenetClientProtocol(NNTPClient):
"""
A client that connects to an NNTP server and asks for articles new
since a certain time.
"""
def __init__(self, groups, date, storage):
"""
Fetch all new articles from the given groups since the
given date and dump them into the given storage. groups
is a list of group names. date is an integer or floating
point representing seconds since the epoch (GMT). storage is
any object that implements the NewsStorage interface.
"""
NNTPClient.__init__(self)
self.groups, self.date, self.storage = groups, date, storage
def connectionMade(self):
NNTPClient.connectionMade(self)
log.msg("Initiating update with remote host: " + str(self.transport.getPeer()))
self.setStream()
self.fetchNewNews(self.groups, self.date, '')
def articleExists(self, exists, article):
if exists:
self.fetchArticle(article)
else:
self.count = self.count - 1
self.disregard = self.disregard + 1
def gotNewNews(self, news):
self.disregard = 0
self.count = len(news)
log.msg("Transfering " + str(self.count) + " articles from remote host: " + str(self.transport.getPeer()))
for i in news:
self.storage.articleExistsRequest(i).addCallback(self.articleExists, i)
def getNewNewsFailed(self, reason):
log.msg("Updated failed (" + reason + ") with remote host: " + str(self.transport.getPeer()))
self.quit()
def gotArticle(self, article):
self.storage.postRequest(article)
self.count = self.count - 1
if not self.count:
log.msg("Completed update with remote host: " + str(self.transport.getPeer()))
if self.disregard:
log.msg("Disregarded %d articles." % (self.disregard,))
self.factory.updateChecks(self.transport.getPeer())
self.quit() | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/news/nntp.py | nntp.py |
from twisted.news import nntp
from twisted.internet import protocol, reactor
import time
class NNTPFactory(protocol.ServerFactory):
"""A factory for NNTP server protocols."""
protocol = nntp.NNTPServer
def __init__(self, backend):
self.backend = backend
def buildProtocol(self, connection):
p = self.protocol()
p.factory = self
return p
class UsenetClientFactory(protocol.ClientFactory):
def __init__(self, groups, storage):
self.lastChecks = {}
self.groups = groups
self.storage = storage
def clientConnectionLost(self, connector, reason):
pass
def clientConnectionFailed(self, connector, reason):
print 'Connection failed: ', reason
def updateChecks(self, addr):
self.lastChecks[addr] = time.mktime(time.gmtime())
def buildProtocol(self, addr):
last = self.lastChecks.setdefault(addr, time.mktime(time.gmtime()) - (60 * 60 * 24 * 7))
p = nntp.UsenetClientProtocol(self.groups, last, self.storage)
p.factory = self
return p
# XXX - Maybe this inheritence doesn't make so much sense?
class UsenetServerFactory(NNTPFactory):
"""A factory for NNTP Usenet server protocols."""
protocol = nntp.NNTPServer
def __init__(self, backend, remoteHosts = None, updatePeriod = 60):
NNTPFactory.__init__(self, backend)
self.updatePeriod = updatePeriod
self.remoteHosts = remoteHosts or []
self.clientFactory = UsenetClientFactory(self.remoteHosts, self.backend)
def startFactory(self):
self._updateCall = reactor.callLater(0, self.syncWithRemotes)
def stopFactory(self):
if self._updateCall:
self._updateCall.cancel()
self._updateCall = None
def buildProtocol(self, connection):
p = self.protocol()
p.factory = self
return p
def syncWithRemotes(self):
for remote in self.remoteHosts:
reactor.connectTCP(remote, 119, self.clientFactory)
self._updateCall = reactor.callLater(self.updatePeriod, self.syncWithRemotes)
# backwards compatability
Factory = UsenetServerFactory | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/news/news.py | news.py |
from __future__ import nested_scopes
from twisted.news.nntp import NNTPError
from twisted.mail import smtp
from twisted.internet import defer
from twisted.enterprise import adbapi
from twisted.persisted import dirdbm
import getpass, pickle, time, socket, md5
import os
import StringIO
from zope.interface import implements, Interface
ERR_NOGROUP, ERR_NOARTICLE = range(2, 4) # XXX - put NNTP values here (I guess?)
OVERVIEW_FMT = [
'Subject', 'From', 'Date', 'Message-ID', 'References',
'Bytes', 'Lines', 'Xref'
]
def hexdigest(md5): #XXX: argh. 1.5.2 doesn't have this.
return ''.join(map(lambda x: hex(ord(x))[2:], md5.digest()))
class Article:
def __init__(self, head, body):
self.body = body
self.headers = {}
header = None
for line in head.split('\r\n'):
if line[0] in ' \t':
i = list(self.headers[header])
i[1] += '\r\n' + line
else:
i = line.split(': ', 1)
header = i[0].lower()
self.headers[header] = tuple(i)
if not self.getHeader('Message-ID'):
s = str(time.time()) + self.body
id = hexdigest(md5.md5(s)) + '@' + socket.gethostname()
self.putHeader('Message-ID', '<%s>' % id)
if not self.getHeader('Bytes'):
self.putHeader('Bytes', str(len(self.body)))
if not self.getHeader('Lines'):
self.putHeader('Lines', str(self.body.count('\n')))
if not self.getHeader('Date'):
self.putHeader('Date', time.ctime(time.time()))
def getHeader(self, header):
h = header.lower()
if self.headers.has_key(h):
return self.headers[h][1]
else:
return ''
def putHeader(self, header, value):
self.headers[header.lower()] = (header, value)
def textHeaders(self):
headers = []
for i in self.headers.values():
headers.append('%s: %s' % i)
return '\r\n'.join(headers) + '\r\n'
def overview(self):
xover = []
for i in OVERVIEW_FMT:
xover.append(self.getHeader(i))
return xover
class NewsServerError(Exception):
pass
class INewsStorage(Interface):
"""
An interface for storing and requesting news articles
"""
def listRequest():
"""
Returns a deferred whose callback will be passed a list of 4-tuples
containing (name, max index, min index, flags) for each news group
"""
def subscriptionRequest():
"""
Returns a deferred whose callback will be passed the list of
recommended subscription groups for new server users
"""
def postRequest(message):
"""
Returns a deferred whose callback will be invoked if 'message'
is successfully posted to one or more specified groups and
whose errback will be invoked otherwise.
"""
def overviewRequest():
"""
Returns a deferred whose callback will be passed the a list of
headers describing this server's overview format.
"""
def xoverRequest(group, low, high):
"""
Returns a deferred whose callback will be passed a list of xover
headers for the given group over the given range. If low is None,
the range starts at the first article. If high is None, the range
ends at the last article.
"""
def xhdrRequest(group, low, high, header):
"""
Returns a deferred whose callback will be passed a list of XHDR data
for the given group over the given range. If low is None,
the range starts at the first article. If high is None, the range
ends at the last article.
"""
def listGroupRequest(group):
"""
Returns a deferred whose callback will be passed a two-tuple of
(group name, [article indices])
"""
def groupRequest(group):
"""
Returns a deferred whose callback will be passed a five-tuple of
(group name, article count, highest index, lowest index, group flags)
"""
def articleExistsRequest(id):
"""
Returns a deferred whose callback will be passed with a true value
if a message with the specified Message-ID exists in the database
and with a false value otherwise.
"""
def articleRequest(group, index, id = None):
"""
Returns a deferred whose callback will be passed a file-like object
containing the full article text (headers and body) for the article
of the specified index in the specified group, and whose errback
will be invoked if the article or group does not exist. If id is
not None, index is ignored and the article with the given Message-ID
will be returned instead, along with its index in the specified
group.
"""
def headRequest(group, index):
"""
Returns a deferred whose callback will be passed the header for
the article of the specified index in the specified group, and
whose errback will be invoked if the article or group does not
exist.
"""
def bodyRequest(group, index):
"""
Returns a deferred whose callback will be passed the body for
the article of the specified index in the specified group, and
whose errback will be invoked if the article or group does not
exist.
"""
class NewsStorage:
"""
Backwards compatibility class -- There is no reason to inherit from this,
just implement INewsStorage instead.
"""
def listRequest(self):
raise NotImplementedError()
def subscriptionRequest(self):
raise NotImplementedError()
def postRequest(self, message):
raise NotImplementedError()
def overviewRequest(self):
return defer.succeed(OVERVIEW_FMT)
def xoverRequest(self, group, low, high):
raise NotImplementedError()
def xhdrRequest(self, group, low, high, header):
raise NotImplementedError()
def listGroupRequest(self, group):
raise NotImplementedError()
def groupRequest(self, group):
raise NotImplementedError()
def articleExistsRequest(self, id):
raise NotImplementedError()
def articleRequest(self, group, index, id = None):
raise NotImplementedError()
def headRequest(self, group, index):
raise NotImplementedError()
def bodyRequest(self, group, index):
raise NotImplementedError()
class PickleStorage:
"""A trivial NewsStorage implementation using pickles
Contains numerous flaws and is generally unsuitable for any
real applications. Consider yourself warned!
"""
implements(INewsStorage)
sharedDBs = {}
def __init__(self, filename, groups = None, moderators = ()):
self.datafile = filename
self.load(filename, groups, moderators)
def getModerators(self, groups):
# first see if any groups are moderated. if so, nothing gets posted,
# but the whole messages gets forwarded to the moderator address
moderators = []
for group in groups:
moderators.append(self.db['moderators'].get(group, None))
return filter(None, moderators)
def notifyModerators(self, moderators, article):
# Moderated postings go through as long as they have an Approved
# header, regardless of what the value is
article.putHeader('To', ', '.join(moderators))
return smtp.sendEmail(
'twisted@' + socket.gethostname(),
moderators,
article.body,
dict(article.headers.values())
)
def listRequest(self):
"Returns a list of 4-tuples: (name, max index, min index, flags)"
l = self.db['groups']
r = []
for i in l:
if len(self.db[i].keys()):
low = min(self.db[i].keys())
high = max(self.db[i].keys()) + 1
else:
low = high = 0
if self.db['moderators'].has_key(i):
flags = 'm'
else:
flags = 'y'
r.append((i, high, low, flags))
return defer.succeed(r)
def subscriptionRequest(self):
return defer.succeed(['alt.test'])
def postRequest(self, message):
cleave = message.find('\r\n\r\n')
headers, article = message[:cleave], message[cleave + 4:]
a = Article(headers, article)
groups = a.getHeader('Newsgroups').split()
xref = []
# Check moderated status
moderators = self.getModerators(groups)
if moderators and not a.getHeader('Approved'):
return self.notifyModerators(moderators, a)
for group in groups:
if self.db.has_key(group):
if len(self.db[group].keys()):
index = max(self.db[group].keys()) + 1
else:
index = 1
xref.append((group, str(index)))
self.db[group][index] = a
if len(xref) == 0:
return defer.fail(None)
a.putHeader('Xref', '%s %s' % (
socket.gethostname().split()[0],
''.join(map(lambda x: ':'.join(x), xref))
))
self.flush()
return defer.succeed(None)
def overviewRequest(self):
return defer.succeed(OVERVIEW_FMT)
def xoverRequest(self, group, low, high):
if not self.db.has_key(group):
return defer.succeed([])
r = []
for i in self.db[group].keys():
if (low is None or i >= low) and (high is None or i <= high):
r.append([str(i)] + self.db[group][i].overview())
return defer.succeed(r)
def xhdrRequest(self, group, low, high, header):
if not self.db.has_key(group):
return defer.succeed([])
r = []
for i in self.db[group].keys():
if low is None or i >= low and high is None or i <= high:
r.append((i, self.db[group][i].getHeader(header)))
return defer.succeed(r)
def listGroupRequest(self, group):
if self.db.has_key(group):
return defer.succeed((group, self.db[group].keys()))
else:
return defer.fail(None)
def groupRequest(self, group):
if self.db.has_key(group):
if len(self.db[group].keys()):
num = len(self.db[group].keys())
low = min(self.db[group].keys())
high = max(self.db[group].keys())
else:
num = low = high = 0
flags = 'y'
return defer.succeed((group, num, high, low, flags))
else:
return defer.fail(ERR_NOGROUP)
def articleExistsRequest(self, id):
for g in self.db.values():
for a in g.values():
if a.getHeader('Message-ID') == id:
return defer.succeed(1)
return defer.succeed(0)
def articleRequest(self, group, index, id = None):
if id is not None:
raise NotImplementedError
if self.db.has_key(group):
if self.db[group].has_key(index):
a = self.db[group][index]
return defer.succeed((
index,
a.getHeader('Message-ID'),
StringIO.StringIO(a.textHeaders() + '\r\n' + a.body)
))
else:
return defer.fail(ERR_NOARTICLE)
else:
return defer.fail(ERR_NOGROUP)
def headRequest(self, group, index):
if self.db.has_key(group):
if self.db[group].has_key(index):
a = self.db[group][index]
return defer.succeed((index, a.getHeader('Message-ID'), a.textHeaders()))
else:
return defer.fail(ERR_NOARTICLE)
else:
return defer.fail(ERR_NOGROUP)
def bodyRequest(self, group, index):
if self.db.has_key(group):
if self.db[group].has_key(index):
a = self.db[group][index]
return defer.succeed((index, a.getHeader('Message-ID'), StringIO.StringIO(a.body)))
else:
return defer.fail(ERR_NOARTICLE)
else:
return defer.fail(ERR_NOGROUP)
def flush(self):
pickle.dump(self.db, open(self.datafile, 'w'))
def load(self, filename, groups = None, moderators = ()):
if PickleStorage.sharedDBs.has_key(filename):
self.db = PickleStorage.sharedDBs[filename]
else:
try:
self.db = pickle.load(open(filename))
PickleStorage.sharedDBs[filename] = self.db
except IOError, e:
self.db = PickleStorage.sharedDBs[filename] = {}
self.db['groups'] = groups
if groups is not None:
for i in groups:
self.db[i] = {}
self.db['moderators'] = dict(moderators)
self.flush()
class Group:
name = None
flags = ''
minArticle = 1
maxArticle = 0
articles = None
def __init__(self, name, flags = 'y'):
self.name = name
self.flags = flags
self.articles = {}
class NewsShelf:
"""
A NewStorage implementation using Twisted's dirdbm persistence module.
"""
implements(INewsStorage)
def __init__(self, mailhost, path):
self.path = path
self.mailhost = mailhost
if not os.path.exists(path):
os.mkdir(path)
self.dbm = dirdbm.Shelf(os.path.join(path, "newsshelf"))
if not len(self.dbm.keys()):
self.initialize()
def initialize(self):
# A dictionary of group name/Group instance items
self.dbm['groups'] = dirdbm.Shelf(os.path.join(self.path, 'groups'))
# A dictionary of group name/email address
self.dbm['moderators'] = dirdbm.Shelf(os.path.join(self.path, 'moderators'))
# A list of group names
self.dbm['subscriptions'] = []
# A dictionary of MessageID strings/xref lists
self.dbm['Message-IDs'] = dirdbm.Shelf(os.path.join(self.path, 'Message-IDs'))
def addGroup(self, name, flags):
self.dbm['groups'][name] = Group(name, flags)
def addSubscription(self, name):
self.dbm['subscriptions'] = self.dbm['subscriptions'] + [name]
def addModerator(self, group, email):
self.dbm['moderators'][group] = email
def listRequest(self):
result = []
for g in self.dbm['groups'].values():
result.append((g.name, g.maxArticle, g.minArticle, g.flags))
return defer.succeed(result)
def subscriptionRequest(self):
return defer.succeed(self.dbm['subscriptions'])
def getModerator(self, groups):
# first see if any groups are moderated. if so, nothing gets posted,
# but the whole messages gets forwarded to the moderator address
for group in groups:
try:
return self.dbm['moderators'][group]
except KeyError:
pass
return None
def notifyModerator(self, moderator, article):
# Moderated postings go through as long as they have an Approved
# header, regardless of what the value is
print 'To is ', moderator
article.putHeader('To', moderator)
return smtp.sendEmail(
self.mailhost,
'twisted-news@' + socket.gethostname(),
moderator,
article.body,
dict(article.headers.values())
)
def postRequest(self, message):
cleave = message.find('\r\n\r\n')
headers, article = message[:cleave], message[cleave + 4:]
article = Article(headers, article)
groups = article.getHeader('Newsgroups').split()
xref = []
# Check for moderated status
moderator = self.getModerator(groups)
if moderator and not article.getHeader('Approved'):
return self.notifyModerator(moderator, article)
for group in groups:
try:
g = self.dbm['groups'][group]
except KeyError:
pass
else:
index = g.maxArticle + 1
g.maxArticle += 1
g.articles[index] = article
xref.append((group, str(index)))
self.dbm['groups'][group] = g
if not xref:
return defer.fail(NewsServerError("No groups carried: " + ' '.join(groups)))
article.putHeader('Xref', '%s %s' % (socket.gethostname().split()[0], ' '.join(map(lambda x: ':'.join(x), xref))))
self.dbm['Message-IDs'][article.getHeader('Message-ID')] = xref
return defer.succeed(None)
def overviewRequest(self):
return defer.succeed(OVERVIEW_FMT)
def xoverRequest(self, group, low, high):
if not self.dbm['groups'].has_key(group):
return defer.succeed([])
if low is None:
low = 0
if high is None:
high = self.dbm['groups'][group].maxArticle
r = []
for i in range(low, high + 1):
if self.dbm['groups'][group].articles.has_key(i):
r.append([str(i)] + self.dbm['groups'][group].articles[i].overview())
return defer.succeed(r)
def xhdrRequest(self, group, low, high, header):
if group not in self.dbm['groups']:
return defer.succeed([])
if low is None:
low = 0
if high is None:
high = self.dbm['groups'][group].maxArticle
r = []
for i in range(low, high + 1):
if self.dbm['groups'][group].articles.has_key(i):
r.append((i, self.dbm['groups'][group].articles[i].getHeader(header)))
return defer.succeed(r)
def listGroupRequest(self, group):
if self.dbm['groups'].has_key(group):
return defer.succeed((group, self.dbm['groups'][group].articles.keys()))
return defer.fail(NewsServerError("No such group: " + group))
def groupRequest(self, group):
try:
g = self.dbm['groups'][group]
except KeyError:
return defer.fail(NewsServerError("No such group: " + group))
else:
flags = g.flags
low = g.minArticle
high = g.maxArticle
num = high - low + 1
return defer.succeed((group, num, high, low, flags))
def articleExistsRequest(self, id):
return defer.succeed(id in self.dbm['Message-IDs'])
def articleRequest(self, group, index, id = None):
if id is not None:
try:
xref = self.dbm['Message-IDs'][id]
except KeyError:
return defer.fail(NewsServerError("No such article: " + id))
else:
group, index = xref[0]
index = int(index)
try:
a = self.dbm['groups'][group].articles[index]
except KeyError:
return defer.fail(NewsServerError("No such group: " + group))
else:
return defer.succeed((
index,
a.getHeader('Message-ID'),
StringIO.StringIO(a.textHeaders() + '\r\n' + a.body)
))
def headRequest(self, group, index, id = None):
if id is not None:
try:
xref = self.dbm['Message-IDs'][id]
except KeyError:
return defer.fail(NewsServerError("No such article: " + id))
else:
group, index = xref[0]
index = int(index)
try:
a = self.dbm['groups'][group].articles[index]
except KeyError:
return defer.fail(NewsServerError("No such group: " + group))
else:
return defer.succeed((index, a.getHeader('Message-ID'), a.textHeaders()))
def bodyRequest(self, group, index, id = None):
if id is not None:
try:
xref = self.dbm['Message-IDs'][id]
except KeyError:
return defer.fail(NewsServerError("No such article: " + id))
else:
group, index = xref[0]
index = int(index)
try:
a = self.dbm['groups'][group].articles[index]
except KeyError:
return defer.fail(NewsServerError("No such group: " + group))
else:
return defer.succeed((index, a.getHeader('Message-ID'), StringIO.StringIO(a.body)))
class NewsStorageAugmentation:
"""
A NewsStorage implementation using Twisted's asynchronous DB-API
"""
implements(INewsStorage)
schema = """
CREATE TABLE groups (
group_id SERIAL,
name VARCHAR(80) NOT NULL,
flags INTEGER DEFAULT 0 NOT NULL
);
CREATE UNIQUE INDEX group_id_index ON groups (group_id);
CREATE UNIQUE INDEX name_id_index ON groups (name);
CREATE TABLE articles (
article_id SERIAL,
message_id TEXT,
header TEXT,
body TEXT
);
CREATE UNIQUE INDEX article_id_index ON articles (article_id);
CREATE UNIQUE INDEX article_message_index ON articles (message_id);
CREATE TABLE postings (
group_id INTEGER,
article_id INTEGER,
article_index INTEGER NOT NULL
);
CREATE UNIQUE INDEX posting_article_index ON postings (article_id);
CREATE TABLE subscriptions (
group_id INTEGER
);
CREATE TABLE overview (
header TEXT
);
"""
def __init__(self, info):
self.info = info
self.dbpool = adbapi.ConnectionPool(**self.info)
def __setstate__(self, state):
self.__dict__ = state
self.info['password'] = getpass.getpass('Database password for %s: ' % (self.info['user'],))
self.dbpool = adbapi.ConnectionPool(**self.info)
del self.info['password']
def listRequest(self):
# COALESCE may not be totally portable
# it is shorthand for
# CASE WHEN (first parameter) IS NOT NULL then (first parameter) ELSE (second parameter) END
sql = """
SELECT groups.name,
COALESCE(MAX(postings.article_index), 0),
COALESCE(MIN(postings.article_index), 0),
groups.flags
FROM groups LEFT OUTER JOIN postings
ON postings.group_id = groups.group_id
GROUP BY groups.name, groups.flags
ORDER BY groups.name
"""
return self.dbpool.runQuery(sql)
def subscriptionRequest(self):
sql = """
SELECT groups.name FROM groups,subscriptions WHERE groups.group_id = subscriptions.group_id
"""
return self.dbpool.runQuery(sql)
def postRequest(self, message):
cleave = message.find('\r\n\r\n')
headers, article = message[:cleave], message[cleave + 4:]
article = Article(headers, article)
return self.dbpool.runInteraction(self._doPost, article)
def _doPost(self, transaction, article):
# Get the group ids
groups = article.getHeader('Newsgroups').split()
if not len(groups):
raise NNTPError('Missing Newsgroups header')
sql = """
SELECT name, group_id FROM groups
WHERE name IN (%s)
""" % (', '.join([("'%s'" % (adbapi.safe(group),)) for group in groups]),)
transaction.execute(sql)
result = transaction.fetchall()
# No relevant groups, bye bye!
if not len(result):
raise NNTPError('None of groups in Newsgroup header carried')
# Got some groups, now find the indices this article will have in each
sql = """
SELECT groups.group_id, COALESCE(MAX(postings.article_index), 0) + 1
FROM groups LEFT OUTER JOIN postings
ON postings.group_id = groups.group_id
WHERE groups.group_id IN (%s)
GROUP BY groups.group_id
""" % (', '.join([("%d" % (id,)) for (group, id) in result]),)
transaction.execute(sql)
indices = transaction.fetchall()
if not len(indices):
raise NNTPError('Internal server error - no indices found')
# Associate indices with group names
gidToName = dict([(b, a) for (a, b) in result])
gidToIndex = dict(indices)
nameIndex = []
for i in gidToName:
nameIndex.append((gidToName[i], gidToIndex[i]))
# Build xrefs
xrefs = socket.gethostname().split()[0]
xrefs = xrefs + ' ' + ' '.join([('%s:%d' % (group, id)) for (group, id) in nameIndex])
article.putHeader('Xref', xrefs)
# Hey! The article is ready to be posted! God damn f'in finally.
sql = """
INSERT INTO articles (message_id, header, body)
VALUES ('%s', '%s', '%s')
""" % (
adbapi.safe(article.getHeader('Message-ID')),
adbapi.safe(article.textHeaders()),
adbapi.safe(article.body)
)
transaction.execute(sql)
# Now update the posting to reflect the groups to which this belongs
for gid in gidToName:
sql = """
INSERT INTO postings (group_id, article_id, article_index)
VALUES (%d, (SELECT last_value FROM articles_article_id_seq), %d)
""" % (gid, gidToIndex[gid])
transaction.execute(sql)
return len(nameIndex)
def overviewRequest(self):
sql = """
SELECT header FROM overview
"""
return self.dbpool.runQuery(sql).addCallback(lambda result: [header[0] for header in result])
def xoverRequest(self, group, low, high):
sql = """
SELECT postings.article_index, articles.header
FROM articles,postings,groups
WHERE postings.group_id = groups.group_id
AND groups.name = '%s'
AND postings.article_id = articles.article_id
%s
%s
""" % (
adbapi.safe(group),
low is not None and "AND postings.article_index >= %d" % (low,) or "",
high is not None and "AND postings.article_index <= %d" % (high,) or ""
)
return self.dbpool.runQuery(sql).addCallback(
lambda results: [
[id] + Article(header, None).overview() for (id, header) in results
]
)
def xhdrRequest(self, group, low, high, header):
sql = """
SELECT articles.header
FROM groups,postings,articles
WHERE groups.name = '%s' AND postings.group_id = groups.group_id
AND postings.article_index >= %d
AND postings.article_index <= %d
""" % (adbapi.safe(group), low, high)
return self.dbpool.runQuery(sql).addCallback(
lambda results: [
(i, Article(h, None).getHeader(h)) for (i, h) in results
]
)
def listGroupRequest(self, group):
sql = """
SELECT postings.article_index FROM postings,groups
WHERE postings.group_id = groups.group_id
AND groups.name = '%s'
""" % (adbapi.safe(group),)
return self.dbpool.runQuery(sql).addCallback(
lambda results, group = group: (group, [res[0] for res in results])
)
def groupRequest(self, group):
sql = """
SELECT groups.name,
COUNT(postings.article_index),
COALESCE(MAX(postings.article_index), 0),
COALESCE(MIN(postings.article_index), 0),
groups.flags
FROM groups LEFT OUTER JOIN postings
ON postings.group_id = groups.group_id
WHERE groups.name = '%s'
GROUP BY groups.name, groups.flags
""" % (adbapi.safe(group),)
return self.dbpool.runQuery(sql).addCallback(
lambda results: tuple(results[0])
)
def articleExistsRequest(self, id):
sql = """
SELECT COUNT(message_id) FROM articles
WHERE message_id = '%s'
""" % (adbapi.safe(id),)
return self.dbpool.runQuery(sql).addCallback(
lambda result: bool(result[0][0])
)
def articleRequest(self, group, index, id = None):
if id is not None:
sql = """
SELECT postings.article_index, articles.message_id, articles.header, articles.body
FROM groups,postings LEFT OUTER JOIN articles
ON articles.message_id = '%s'
WHERE groups.name = '%s'
AND groups.group_id = postings.group_id
""" % (adbapi.safe(id), adbapi.safe(group))
else:
sql = """
SELECT postings.article_index, articles.message_id, articles.header, articles.body
FROM groups,articles LEFT OUTER JOIN postings
ON postings.article_id = articles.article_id
WHERE postings.article_index = %d
AND postings.group_id = groups.group_id
AND groups.name = '%s'
""" % (index, adbapi.safe(group))
return self.dbpool.runQuery(sql).addCallback(
lambda result: (
result[0][0],
result[0][1],
StringIO.StringIO(result[0][2] + '\r\n' + result[0][3])
)
)
def headRequest(self, group, index):
sql = """
SELECT postings.article_index, articles.message_id, articles.header
FROM groups,articles LEFT OUTER JOIN postings
ON postings.article_id = articles.article_id
WHERE postings.article_index = %d
AND postings.group_id = groups.group_id
AND groups.name = '%s'
""" % (index, adbapi.safe(group))
return self.dbpool.runQuery(sql).addCallback(lambda result: result[0])
def bodyRequest(self, group, index):
sql = """
SELECT postings.article_index, articles.message_id, articles.body
FROM groups,articles LEFT OUTER JOIN postings
ON postings.article_id = articles.article_id
WHERE postings.article_index = %d
AND postings.group_id = groups.group_id
AND groups.name = '%s'
""" % (index, adbapi.safe(group))
return self.dbpool.runQuery(sql).addCallback(
lambda result: result[0]
).addCallback(
lambda (index, id, body): (index, id, StringIO.StringIO(body))
)
####
#### XXX - make these static methods some day
####
def makeGroupSQL(groups):
res = ''
for g in groups:
res = res + """\n INSERT INTO groups (name) VALUES ('%s');\n""" % (adbapi.safe(g),)
return res
def makeOverviewSQL():
res = ''
for o in OVERVIEW_FMT:
res = res + """\n INSERT INTO overview (header) VALUES ('%s');\n""" % (adbapi.safe(o),)
return res | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/news/database.py | database.py |
from twisted.news import news, database
from twisted.application import strports
from twisted.python import usage, log
class DBOptions(usage.Options):
optParameters = [
['module', None, 'pyPgSQL.PgSQL', "DB-API 2.0 module to use"],
['dbhost', None, 'localhost', "Host where database manager is listening"],
['dbuser', None, 'news', "Username with which to connect to database"],
['database', None, 'news', "Database name to use"],
['schema', None, 'schema.sql', "File to which to write SQL schema initialisation"],
# XXX - Hrm.
["groups", "g", "groups.list", "File containing group list"],
["servers", "s", "servers.list", "File containing server list"]
]
def postOptions(self):
# XXX - Hmmm.
self['groups'] = [g.strip() for g in open(self['groups']).readlines() if not g.startswith('#')]
self['servers'] = [s.strip() for s in open(self['servers']).readlines() if not s.startswith('#')]
try:
__import__(self['module'])
except ImportError:
log.msg("Warning: Cannot import %s" % (self['module'],))
open(self['schema'], 'w').write(
database.NewsStorageAugmentation.schema + '\n' +
database.makeGroupSQL(self['groups']) + '\n' +
database.makeOverviewSQL()
)
info = {
'host': self['dbhost'], 'user': self['dbuser'],
'database': self['database'], 'dbapiName': self['module']
}
self.db = database.NewsStorageAugmentation(info)
class PickleOptions(usage.Options):
optParameters = [
['file', None, 'news.pickle', "File to which to save pickle"],
# XXX - Hrm.
["groups", "g", "groups.list", "File containing group list"],
["servers", "s", "servers.list", "File containing server list"],
["moderators", "m", "moderators.list",
"File containing moderators list"],
]
subCommands = None
def postOptions(self):
# XXX - Hmmm.
filename = self['file']
self['groups'] = [g.strip() for g in open(self['groups']).readlines()
if not g.startswith('#')]
self['servers'] = [s.strip() for s in open(self['servers']).readlines()
if not s.startswith('#')]
self['moderators'] = [s.split()
for s in open(self['moderators']).readlines()
if not s.startswith('#')]
self.db = database.PickleStorage(filename, self['groups'],
self['moderators'])
class Options(usage.Options):
synopsis = "Usage: mktap news [options]"
groups = None
servers = None
subscriptions = None
optParameters = [
["port", "p", "119", "Listen port"],
["interface", "i", "", "Interface to which to bind"],
["datadir", "d", "news.db", "Root data storage path"],
["mailhost", "m", "localhost", "Host of SMTP server to use"]
]
zsh_actions = {"datadir" : "_dirs", "mailhost" : "_hosts"}
def __init__(self):
usage.Options.__init__(self)
self.groups = []
self.servers = []
self.subscriptions = []
def opt_group(self, group):
"""The name of a newsgroup to carry."""
self.groups.append([group, None])
def opt_moderator(self, moderator):
"""The email of the moderator for the most recently passed group."""
self.groups[-1][1] = moderator
def opt_subscription(self, group):
"""A newsgroup to list as a recommended subscription."""
self.subscriptions.append(group)
def opt_server(self, server):
"""The address of a Usenet server to pass messages to and receive messages from."""
self.servers.append(server)
def makeService(config):
if not len(config.groups):
raise usage.UsageError("No newsgroups specified")
db = database.NewsShelf(config['mailhost'], config['datadir'])
for (g, m) in config.groups:
if m:
db.addGroup(g, 'm')
db.addModerator(g, m)
else:
db.addGroup(g, 'y')
for s in config.subscriptions:
print s
db.addSubscription(s)
s = config['port']
if config['interface']:
# Add a warning here
s += ':interface='+config['interface']
return strports.service(s, news.UsenetServerFactory(db, config.servers)) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/news/tap.py | tap.py |
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
from cStringIO import StringIO
from twisted.python import failure
import html
import resource
import linecache
import string, re
import types
def redirectTo(URL, request):
request.redirect(URL)
return """
<html>
<head>
<meta http-equiv=\"refresh\" content=\"0;URL=%(url)s\">
</head>
<body bgcolor=\"#FFFFFF\" text=\"#000000\">
<a href=\"%(url)s\">click here</a>
</body>
</html>
""" % {'url': URL}
class Redirect(resource.Resource):
isLeaf = 1
def __init__(self, url):
resource.Resource.__init__(self)
self.url = url
def render(self, request):
return redirectTo(self.url, request)
def getChild(self, name, request):
return self
class ChildRedirector(Redirect):
isLeaf = 0
def __init__(self, url):
# XXX is this enough?
if ((url.find('://') == -1)
and (not url.startswith('..'))
and (not url.startswith('/'))):
raise ValueError("It seems you've given me a redirect (%s) that is a child of myself! That's not good, it'll cause an infinite redirect." % url)
Redirect.__init__(self, url)
def getChild(self, name, request):
newUrl = self.url
if not newUrl.endswith('/'):
newUrl += '/'
newUrl += name
return ChildRedirector(newUrl)
from twisted.python import urlpath
class ParentRedirect(resource.Resource):
"""
I redirect to URLPath.here().
"""
isLeaf = 1
def render(self, request):
return redirectTo(urlpath.URLPath.fromRequest(request).here(), request)
def getChild(self, request):
return self
class DeferredResource(resource.Resource):
"""
I wrap up a Deferred that will eventually result in a Resource
object.
"""
isLeaf = 1
def __init__(self, d):
resource.Resource.__init__(self)
self.d = d
def getChild(self, name, request):
return self
def render(self, request):
self.d.addCallback(self._cbChild, request).addErrback(
self._ebChild,request)
from twisted.web.server import NOT_DONE_YET
return NOT_DONE_YET
def _cbChild(self, child, request):
result = resource.getChildForRequest(child, request).render(request)
from twisted.web.server import NOT_DONE_YET
if result == NOT_DONE_YET:
return
else:
request.write(result)
request.finish()
def _ebChild(self, reason, request):
request.processingFailed(reason)
return reason
stylesheet = """
<style type="text/css">
p.error {
color: red;
font-family: Verdana, Arial, helvetica, sans-serif;
font-weight: bold;
}
div {
font-family: Verdana, Arial, helvetica, sans-serif;
}
div.stackTrace {
}
div.frame {
padding: 1em;
background: white;
border-bottom: thin black dashed;
}
div.firstFrame {
padding: 1em;
background: white;
border-top: thin black dashed;
border-bottom: thin black dashed;
}
div.location {
}
div.snippet {
margin-bottom: 0.5em;
margin-left: 1em;
background: #FFFFDD;
}
div.snippetHighlightLine {
color: red;
}
span.code {
font-family: "Courier New", courier, monotype;
}
span.function {
font-weight: bold;
font-family: "Courier New", courier, monotype;
}
table.variables {
border-collapse: collapse;
margin-left: 1em;
}
td.varName {
vertical-align: top;
font-weight: bold;
padding-left: 0.5em;
padding-right: 0.5em;
}
td.varValue {
padding-left: 0.5em;
padding-right: 0.5em;
}
div.variables {
margin-bottom: 0.5em;
}
span.heading {
font-weight: bold;
}
div.dict {
background: #cccc99;
padding: 2px;
float: left;
}
td.dictKey {
background: #ffff99;
font-weight: bold;
}
td.dictValue {
background: #ffff99;
}
div.list {
background: #7777cc;
padding: 2px;
float: left;
}
div.listItem {
background: #9999ff;
}
div.instance {
background: #cc7777;
padding: 2px;
float: left;
}
span.instanceName {
font-weight: bold;
display: block;
}
span.instanceRepr {
background: #ff9999;
font-family: "Courier New", courier, monotype;
}
div.function {
background: orange;
font-weight: bold;
float: left;
}
</style>
"""
def htmlrepr(x):
return htmlReprTypes.get(type(x), htmlUnknown)(x)
def saferepr(x):
try:
rx = repr(x)
except:
rx = "<repr failed! %s instance at %s>" % (x.__class__, id(x))
return rx
def htmlUnknown(x):
return '<code>'+html.escape(saferepr(x))+'</code>'
def htmlDict(d):
io = StringIO()
w = io.write
w('<div class="dict"><span class="heading">Dictionary instance @ %s</span>' % hex(id(d)))
w('<table class="dict">')
for k, v in d.items():
if k == '__builtins__':
v = 'builtin dictionary'
w('<tr><td class="dictKey">%s</td><td class="dictValue">%s</td></tr>' % (htmlrepr(k), htmlrepr(v)))
w('</table></div>')
return io.getvalue()
def htmlList(l):
io = StringIO()
w = io.write
w('<div class="list"><span class="heading">List instance @ %s</span>' % hex(id(l)))
for i in l:
w('<div class="listItem">%s</div>' % htmlrepr(i))
w('</div>')
return io.getvalue()
def htmlInst(i):
if hasattr(i, "__html__"):
s = i.__html__()
else:
s = html.escape(saferepr(i))
return '''<div class="instance"><span class="instanceName">%s instance @ %s</span>
<span class="instanceRepr">%s</span></div>
''' % (i.__class__, hex(id(i)), s)
def htmlString(s):
return html.escape(saferepr(s))
def htmlFunc(f):
return ('<div class="function">' +
html.escape("function %s in file %s at line %s" %
(f.__name__, f.func_code.co_filename,
f.func_code.co_firstlineno))+
'</div>')
htmlReprTypes = {types.DictType: htmlDict,
types.ListType: htmlList,
types.InstanceType: htmlInst,
types.StringType: htmlString,
types.FunctionType: htmlFunc}
def htmlIndent(snippetLine):
ret = string.replace(string.replace(html.escape(string.rstrip(snippetLine)),
' ', ' '),
'\t', ' ')
return ret
def formatFailure(myFailure):
exceptionHTML = """
<p class="error">%s: %s</p>
"""
frameHTML = """
<div class="location">%s, line %s in <span class="function">%s</span></div>
"""
snippetLineHTML = """
<div class="snippetLine"><span class="lineno">%s</span><span class="code">%s</span></div>
"""
snippetHighlightLineHTML = """
<div class="snippetHighlightLine"><span class="lineno">%s</span><span class="code">%s</span></div>
"""
variableHTML = """
<tr class="varRow"><td class="varName">%s</td><td class="varValue">%s</td></tr>
"""
if not isinstance(myFailure, failure.Failure):
return html.PRE(str(myFailure))
io = StringIO()
w = io.write
w(stylesheet)
w('<a href="#tbend">')
w(exceptionHTML % (html.escape(str(myFailure.type)),
html.escape(str(myFailure.value))))
w('</a>')
w('<div class="stackTrace">')
first = 1
for method, filename, lineno, localVars, globalVars in myFailure.frames:
if filename == '<string>':
continue
if first:
w('<div class="firstFrame">')
first = 0
else:
w('<div class="frame">')
w(frameHTML % (filename, lineno, method))
w('<div class="snippet">')
textSnippet = ''
for snipLineNo in range(lineno-2, lineno+2):
snipLine = linecache.getline(filename, snipLineNo)
textSnippet += snipLine
snipLine = htmlIndent(snipLine)
if snipLineNo == lineno:
w(snippetHighlightLineHTML % (snipLineNo, snipLine))
else:
w(snippetLineHTML % (snipLineNo, snipLine))
w('</div>')
# Instance variables
for name, var in localVars:
if name == 'self' and hasattr(var, '__dict__'):
usedVars = [ (key, value) for (key, value) in var.__dict__.items()
if re.search(r'\W'+'self.'+key+r'\W', textSnippet) ]
if usedVars:
w('<div class="variables"><b>Self</b>')
w('<table class="variables">')
for key, value in usedVars:
w(variableHTML % (key, htmlrepr(value)))
w('</table></div>')
break
# Local and global vars
for nm, varList in ('Locals', localVars), ('Globals', globalVars):
usedVars = [ (name, var) for (name, var) in varList
if re.search(r'\W'+name+r'\W', textSnippet) ]
if usedVars:
w('<div class="variables"><b>%s</b><table class="variables">' % nm)
for name, var in usedVars:
w(variableHTML % (name, htmlrepr(var)))
w('</table></div>')
w('</div>') # frame
w('</div>') # stacktrace
w('<a name="tbend"> </a>')
w(exceptionHTML % (html.escape(str(myFailure.type)),
html.escape(str(myFailure.value))))
return io.getvalue() | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/util.py | util.py |
# System Imports
import string
# Twisted Imports
from twisted.python import roots
# Sibling Imports
import resource
import error
class VirtualHostCollection(roots.Homogenous):
"""Wrapper for virtual hosts collection.
This exists for configuration purposes.
"""
entityType = resource.Resource
def __init__(self, nvh):
self.nvh = nvh
def listStaticEntities(self):
return self.nvh.hosts.items()
def getStaticEntity(self, name):
return self.nvh.hosts.get(self)
def reallyPutEntity(self, name, entity):
self.nvh.addHost(name, entity)
def delEntity(self, name):
self.nvh.removeHost(name)
class NameVirtualHost(resource.Resource):
"""I am a resource which represents named virtual hosts.
"""
default = None
def __init__(self):
"""Initialize.
"""
resource.Resource.__init__(self)
self.hosts = {}
def listStaticEntities(self):
return resource.Resource.listStaticEntities(self) + [("Virtual Hosts", VirtualHostCollection(self))]
def getStaticEntity(self, name):
if name == "Virtual Hosts":
return VirtualHostCollection(self)
else:
return resource.Resource.getStaticEntity(self, name)
def addHost(self, name, resrc):
"""Add a host to this virtual host.
This will take a host named `name', and map it to a resource
`resrc'. For example, a setup for our virtual hosts would be::
nvh.addHost('divunal.com', divunalDirectory)
nvh.addHost('www.divunal.com', divunalDirectory)
nvh.addHost('twistedmatrix.com', twistedMatrixDirectory)
nvh.addHost('www.twistedmatrix.com', twistedMatrixDirectory)
"""
self.hosts[name] = resrc
def removeHost(self, name):
"""Remove a host."""
del self.hosts[name]
def _getResourceForRequest(self, request):
"""(Internal) Get the appropriate resource for the given host.
"""
hostHeader = request.getHeader('host')
if hostHeader == None:
return self.default or error.NoResource()
else:
host = string.split(string.lower(hostHeader),':')[0]
return (self.hosts.get(host, self.default)
or error.NoResource("host %s not in vhost map" % repr(host)))
def render(self, request):
"""Implementation of resource.Resource's render method.
"""
resrc = self._getResourceForRequest(request)
return resrc.render(request)
def getChild(self, path, request):
"""Implementation of resource.Resource's getChild method.
"""
resrc = self._getResourceForRequest(request)
if resrc.isLeaf:
request.postpath.insert(0,request.prepath.pop(-1))
return resrc
else:
return resrc.getChildWithDefault(path, request)
class _HostResource(resource.Resource):
def getChild(self, path, request):
if ':' in path:
host, port = path.split(':', 1)
port = int(port)
else:
host, port = path, 80
request.setHost(host, port)
prefixLen = 3+request.isSecure()+4+len(path)+len(request.prepath[-3])
request.path = '/'+'/'.join(request.postpath)
request.uri = request.uri[prefixLen:]
del request.prepath[:3]
return request.site.getResourceFor(request)
class VHostMonsterResource(resource.Resource):
"""
Use this to be able to record the hostname and method (http vs. https)
in the URL without disturbing your web site. If you put this resource
in a URL http://foo.com/bar then requests to
http://foo.com/bar/http/baz.com/something will be equivalent to
http://foo.com/something, except that the hostname the request will
appear to be accessing will be "baz.com". So if "baz.com" is redirecting
all requests for to foo.com, while foo.com is inaccessible from the outside,
then redirect and url generation will work correctly
"""
def getChild(self, path, request):
if path == 'http':
request.isSecure = lambda: 0
elif path == 'https':
request.isSecure = lambda: 1
return _HostResource() | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/vhost.py | vhost.py |
from __future__ import nested_scopes
__version__ = "$Revision: 1.32 $"[11:-2]
# System Imports
import xmlrpclib
import urlparse
# Sibling Imports
from twisted.web import resource, server
from twisted.internet import defer, protocol, reactor
from twisted.python import log, reflect, failure
from twisted.web import http
# These are deprecated, use the class level definitions
NOT_FOUND = 8001
FAILURE = 8002
# Useful so people don't need to import xmlrpclib directly
Fault = xmlrpclib.Fault
Binary = xmlrpclib.Binary
Boolean = xmlrpclib.Boolean
DateTime = xmlrpclib.DateTime
class NoSuchFunction(Fault):
"""There is no function by the given name."""
pass
class Handler:
"""Handle a XML-RPC request and store the state for a request in progress.
Override the run() method and return result using self.result,
a Deferred.
We require this class since we're not using threads, so we can't
encapsulate state in a running function if we're going to have
to wait for results.
For example, lets say we want to authenticate against twisted.cred,
run a LDAP query and then pass its result to a database query, all
as a result of a single XML-RPC command. We'd use a Handler instance
to store the state of the running command.
"""
def __init__(self, resource, *args):
self.resource = resource # the XML-RPC resource we are connected to
self.result = defer.Deferred()
self.run(*args)
def run(self, *args):
# event driven equivalent of 'raise UnimplementedError'
self.result.errback(NotImplementedError("Implement run() in subclasses"))
class XMLRPC(resource.Resource):
"""A resource that implements XML-RPC.
You probably want to connect this to '/RPC2'.
Methods published can return XML-RPC serializable results, Faults,
Binary, Boolean, DateTime, Deferreds, or Handler instances.
By default methods beginning with 'xmlrpc_' are published.
Sub-handlers for prefixed methods (e.g., system.listMethods)
can be added with putSubHandler. By default, prefixes are
separated with a '.'. Override self.separator to change this.
"""
# Error codes for Twisted, if they conflict with yours then
# modify them at runtime.
NOT_FOUND = 8001
FAILURE = 8002
isLeaf = 1
separator = '.'
def __init__(self, allowNone=False):
resource.Resource.__init__(self)
self.subHandlers = {}
self.allowNone = allowNone
def putSubHandler(self, prefix, handler):
self.subHandlers[prefix] = handler
def getSubHandler(self, prefix):
return self.subHandlers.get(prefix, None)
def getSubHandlerPrefixes(self):
return self.subHandlers.keys()
def render(self, request):
request.content.seek(0, 0)
args, functionPath = xmlrpclib.loads(request.content.read())
try:
function = self._getFunction(functionPath)
except Fault, f:
self._cbRender(f, request)
else:
request.setHeader("content-type", "text/xml")
defer.maybeDeferred(function, *args).addErrback(
self._ebRender
).addCallback(
self._cbRender, request
)
return server.NOT_DONE_YET
def _cbRender(self, result, request):
if isinstance(result, Handler):
result = result.result
if not isinstance(result, Fault):
result = (result,)
try:
s = xmlrpclib.dumps(result, methodresponse=True, allow_none=self.allowNone)
except:
f = Fault(self.FAILURE, "can't serialize output")
s = xmlrpclib.dumps(f, methodresponse=True, allow_none=self.allowNone)
request.setHeader("content-length", str(len(s)))
request.write(s)
request.finish()
def _ebRender(self, failure):
if isinstance(failure.value, Fault):
return failure.value
log.err(failure)
return Fault(self.FAILURE, "error")
def _getFunction(self, functionPath):
"""Given a string, return a function, or raise NoSuchFunction.
This returned function will be called, and should return the result
of the call, a Deferred, or a Fault instance.
Override in subclasses if you want your own policy. The default
policy is that given functionPath 'foo', return the method at
self.xmlrpc_foo, i.e. getattr(self, "xmlrpc_" + functionPath).
If functionPath contains self.separator, the sub-handler for
the initial prefix is used to search for the remaining path.
"""
if functionPath.find(self.separator) != -1:
prefix, functionPath = functionPath.split(self.separator, 1)
handler = self.getSubHandler(prefix)
if handler is None: raise NoSuchFunction(self.NOT_FOUND, "no such subHandler %s" % prefix)
return handler._getFunction(functionPath)
f = getattr(self, "xmlrpc_%s" % functionPath, None)
if not f:
raise NoSuchFunction(self.NOT_FOUND, "function %s not found" % functionPath)
elif not callable(f):
raise NoSuchFunction(self.NOT_FOUND, "function %s not callable" % functionPath)
else:
return f
def _listFunctions(self):
"""Return a list of the names of all xmlrpc methods."""
return reflect.prefixedMethodNames(self.__class__, 'xmlrpc_')
class XMLRPCIntrospection(XMLRPC):
"""Implement the XML-RPC Introspection API.
By default, the methodHelp method returns the 'help' method attribute,
if it exists, otherwise the __doc__ method attribute, if it exists,
otherwise the empty string.
To enable the methodSignature method, add a 'signature' method attribute
containing a list of lists. See methodSignature's documentation for the
format. Note the type strings should be XML-RPC types, not Python types.
"""
def __init__(self, parent):
"""Implement Introspection support for an XMLRPC server.
@param parent: the XMLRPC server to add Introspection support to.
"""
XMLRPC.__init__(self)
self._xmlrpc_parent = parent
def xmlrpc_listMethods(self):
"""Return a list of the method names implemented by this server."""
functions = []
todo = [(self._xmlrpc_parent, '')]
while todo:
obj, prefix = todo.pop(0)
functions.extend([ prefix + name for name in obj._listFunctions() ])
todo.extend([ (obj.getSubHandler(name),
prefix + name + obj.separator)
for name in obj.getSubHandlerPrefixes() ])
return functions
xmlrpc_listMethods.signature = [['array']]
def xmlrpc_methodHelp(self, method):
"""Return a documentation string describing the use of the given method.
"""
method = self._xmlrpc_parent._getFunction(method)
return (getattr(method, 'help', None)
or getattr(method, '__doc__', None) or '')
xmlrpc_methodHelp.signature = [['string', 'string']]
def xmlrpc_methodSignature(self, method):
"""Return a list of type signatures.
Each type signature is a list of the form [rtype, type1, type2, ...]
where rtype is the return type and typeN is the type of the Nth
argument. If no signature information is available, the empty
string is returned.
"""
method = self._xmlrpc_parent._getFunction(method)
return getattr(method, 'signature', None) or ''
xmlrpc_methodSignature.signature = [['array', 'string'],
['string', 'string']]
def addIntrospection(xmlrpc):
"""Add Introspection support to an XMLRPC server.
@param xmlrpc: The xmlrpc server to add Introspection support to.
"""
xmlrpc.putSubHandler('system', XMLRPCIntrospection(xmlrpc))
class QueryProtocol(http.HTTPClient):
def connectionMade(self):
self.sendCommand('POST', self.factory.path)
self.sendHeader('User-Agent', 'Twisted/XMLRPClib')
self.sendHeader('Host', self.factory.host)
self.sendHeader('Content-type', 'text/xml')
self.sendHeader('Content-length', str(len(self.factory.payload)))
if self.factory.user:
auth = '%s:%s' % (self.factory.user, self.factory.password)
auth = auth.encode('base64').strip()
self.sendHeader('Authorization', 'Basic %s' % (auth,))
self.endHeaders()
self.transport.write(self.factory.payload)
def handleStatus(self, version, status, message):
if status != '200':
self.factory.badStatus(status, message)
def handleResponse(self, contents):
self.factory.parseResponse(contents)
payloadTemplate = """<?xml version="1.0"?>
<methodCall>
<methodName>%s</methodName>
%s
</methodCall>
"""
class _QueryFactory(protocol.ClientFactory):
deferred = None
protocol = QueryProtocol
def __init__(self, path, host, method, user=None, password=None, allowNone=False, args=()):
self.path, self.host = path, host
self.user, self.password = user, password
self.payload = payloadTemplate % (method, xmlrpclib.dumps(args, allow_none=allowNone))
self.deferred = defer.Deferred()
def parseResponse(self, contents):
if not self.deferred:
return
try:
response = xmlrpclib.loads(contents)
except:
self.deferred.errback(failure.Failure())
self.deferred = None
else:
self.deferred.callback(response[0][0])
self.deferred = None
def clientConnectionLost(self, _, reason):
if self.deferred is not None:
self.deferred.errback(reason)
self.deferred = None
clientConnectionFailed = clientConnectionLost
def badStatus(self, status, message):
self.deferred.errback(ValueError(status, message))
self.deferred = None
class Proxy:
"""A Proxy for making remote XML-RPC calls.
Pass the URL of the remote XML-RPC server to the constructor.
Use proxy.callRemote('foobar', *args) to call remote method
'foobar' with *args.
"""
def __init__(self, url, user=None, password=None, allowNone=False):
"""
@type url: C{str}
@param url: The URL to which to post method calls. Calls will be made
over SSL if the scheme is HTTPS. If netloc contains username or
password information, these will be used to authenticate, as long as
the C{user} and C{password} arguments are not specified.
@type user: C{str} or None
@param user: The username with which to authenticate with the server
when making calls. If specified, overrides any username information
embedded in C{url}. If not specified, a value may be taken from C{url}
if present.
@type password: C{str} or None
@param password: The password with which to authenticate with the
server when making calls. If specified, overrides any password
information embedded in C{url}. If not specified, a value may be taken
from C{url} if present.
@type allowNone: C{bool} or None
@param allowNone: allow the use of None values in parameters. It's
passed to the underlying xmlrpclib implementation. Default to False.
"""
scheme, netloc, path, params, query, fragment = urlparse.urlparse(url)
netlocParts = netloc.split('@')
if len(netlocParts) == 2:
userpass = netlocParts.pop(0).split(':')
self.user = userpass.pop(0)
try:
self.password = userpass.pop(0)
except:
self.password = None
else:
self.user = self.password = None
hostport = netlocParts[0].split(':')
self.host = hostport.pop(0)
try:
self.port = int(hostport.pop(0))
except:
self.port = None
self.path = path
if self.path in ['', None]:
self.path = '/'
self.secure = (scheme == 'https')
if user is not None:
self.user = user
if password is not None:
self.password = password
self.allowNone = allowNone
def callRemote(self, method, *args):
factory = _QueryFactory(
self.path, self.host, method, self.user,
self.password, self.allowNone, args)
if self.secure:
from twisted.internet import ssl
reactor.connectSSL(self.host, self.port or 443,
factory, ssl.ClientContextFactory())
else:
reactor.connectTCP(self.host, self.port or 80, factory)
return factory.deferred
__all__ = ["XMLRPC", "Handler", "NoSuchFunction", "Fault", "Proxy"] | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/xmlrpc.py | xmlrpc.py |
from twisted.internet.protocol import Protocol, FileWrapper
from twisted.python.reflect import prefixedMethodNames
# Elements of the three-tuples in the state table.
BEGIN_HANDLER = 0
DO_HANDLER = 1
END_HANDLER = 2
identChars = '.-_:'
lenientIdentChars = identChars + ';+#/%~'
def nop(*args, **kw):
"Do nothing."
def unionlist(*args):
l = []
for x in args:
l.extend(x)
d = dict([(x, 1) for x in l])
return d.keys()
def zipfndict(*args, **kw):
default = kw.get('default', nop)
d = {}
for key in unionlist(*[fndict.keys() for fndict in args]):
d[key] = tuple([x.get(key, default) for x in args])
return d
def prefixedMethodClassDict(clazz, prefix):
return dict([(name, getattr(clazz, prefix + name)) for name in prefixedMethodNames(clazz, prefix)])
def prefixedMethodObjDict(obj, prefix):
return dict([(name, getattr(obj, prefix + name)) for name in prefixedMethodNames(obj.__class__, prefix)])
class ParseError(Exception):
def __init__(self, filename, line, col, message):
self.filename = filename
self.line = line
self.col = col
self.message = message
def __str__(self):
return "%s:%s:%s: %s" % (self.filename, self.line, self.col,
self.message)
class XMLParser(Protocol):
state = None
encodings = None
filename = "<xml />"
beExtremelyLenient = 0
_prepend = None
# _leadingBodyData will sometimes be set before switching to the
# 'bodydata' state, when we "accidentally" read a byte of bodydata
# in a different state.
_leadingBodyData = None
def connectionMade(self):
self.lineno = 1
self.colno = 0
self.encodings = []
def saveMark(self):
'''Get the line number and column of the last character parsed'''
# This gets replaced during dataReceived, restored afterwards
return (self.lineno, self.colno)
def _parseError(self, message):
raise ParseError(*((self.filename,)+self.saveMark()+(message,)))
def _buildStateTable(self):
'''Return a dictionary of begin, do, end state function tuples'''
# _buildStateTable leaves something to be desired but it does what it
# does.. probably slowly, so I'm doing some evil caching so it doesn't
# get called more than once per class.
stateTable = getattr(self.__class__, '__stateTable', None)
if stateTable is None:
stateTable = self.__class__.__stateTable = zipfndict(
*[prefixedMethodObjDict(self, prefix)
for prefix in ('begin_', 'do_', 'end_')])
return stateTable
def _decode(self, data):
if 'UTF-16' in self.encodings or 'UCS-2' in self.encodings:
assert not len(data) & 1, 'UTF-16 must come in pairs for now'
if self._prepend:
data = self._prepend + data
for encoding in self.encodings:
data = unicode(data, encoding)
return data
def maybeBodyData(self):
if self.endtag:
return 'bodydata'
# Get ready for fun! We're going to allow
# <script>if (foo < bar)</script> to work!
# We do this by making everything between <script> and
# </script> a Text
# BUT <script src="foo"> will be special-cased to do regular,
# lenient behavior, because those may not have </script>
# -radix
if (self.tagName == 'script'
and not self.tagAttributes.has_key('src')):
# we do this ourselves rather than having begin_waitforendscript
# becuase that can get called multiple times and we don't want
# bodydata to get reset other than the first time.
self.begin_bodydata(None)
return 'waitforendscript'
return 'bodydata'
def dataReceived(self, data):
stateTable = self._buildStateTable()
if not self.state:
# all UTF-16 starts with this string
if data.startswith('\xff\xfe'):
self._prepend = '\xff\xfe'
self.encodings.append('UTF-16')
data = data[2:]
elif data.startswith('\xfe\xff'):
self._prepend = '\xfe\xff'
self.encodings.append('UTF-16')
data = data[2:]
self.state = 'begin'
if self.encodings:
data = self._decode(data)
# bring state, lineno, colno into local scope
lineno, colno = self.lineno, self.colno
curState = self.state
# replace saveMark with a nested scope function
_saveMark = self.saveMark
def saveMark():
return (lineno, colno)
self.saveMark = saveMark
# fetch functions from the stateTable
beginFn, doFn, endFn = stateTable[curState]
try:
for byte in data:
# do newline stuff
if byte == '\n':
lineno += 1
colno = 0
else:
colno += 1
newState = doFn(byte)
if newState is not None and newState != curState:
# this is the endFn from the previous state
endFn()
curState = newState
beginFn, doFn, endFn = stateTable[curState]
beginFn(byte)
finally:
self.saveMark = _saveMark
self.lineno, self.colno = lineno, colno
# state doesn't make sense if there's an exception..
self.state = curState
def connectionLost(self, reason):
"""
End the last state we were in.
"""
stateTable = self._buildStateTable()
stateTable[self.state][END_HANDLER]()
# state methods
def do_begin(self, byte):
if byte.isspace():
return
if byte != '<':
if self.beExtremelyLenient:
self._leadingBodyData = byte
return 'bodydata'
self._parseError("First char of document [%r] wasn't <" % (byte,))
return 'tagstart'
def begin_comment(self, byte):
self.commentbuf = ''
def do_comment(self, byte):
self.commentbuf += byte
if self.commentbuf.endswith('-->'):
self.gotComment(self.commentbuf[:-3])
return 'bodydata'
def begin_tagstart(self, byte):
self.tagName = '' # name of the tag
self.tagAttributes = {} # attributes of the tag
self.termtag = 0 # is the tag self-terminating
self.endtag = 0
def do_tagstart(self, byte):
if byte.isalnum() or byte in identChars:
self.tagName += byte
if self.tagName == '!--':
return 'comment'
elif byte.isspace():
if self.tagName:
if self.endtag:
# properly strict thing to do here is probably to only
# accept whitespace
return 'waitforgt'
return 'attrs'
else:
self._parseError("Whitespace before tag-name")
elif byte == '>':
if self.endtag:
self.gotTagEnd(self.tagName)
return 'bodydata'
else:
self.gotTagStart(self.tagName, {})
return (not self.beExtremelyLenient) and 'bodydata' or self.maybeBodyData()
elif byte == '/':
if self.tagName:
return 'afterslash'
else:
self.endtag = 1
elif byte in '!?':
if self.tagName:
if not self.beExtremelyLenient:
self._parseError("Invalid character in tag-name")
else:
self.tagName += byte
self.termtag = 1
elif byte == '[':
if self.tagName == '!':
return 'expectcdata'
else:
self._parseError("Invalid '[' in tag-name")
else:
if self.beExtremelyLenient:
self.bodydata = '<'
return 'unentity'
self._parseError('Invalid tag character: %r'% byte)
def begin_unentity(self, byte):
self.bodydata += byte
def do_unentity(self, byte):
self.bodydata += byte
return 'bodydata'
def end_unentity(self):
self.gotText(self.bodydata)
def begin_expectcdata(self, byte):
self.cdatabuf = byte
def do_expectcdata(self, byte):
self.cdatabuf += byte
cdb = self.cdatabuf
cd = '[CDATA['
if len(cd) > len(cdb):
if cd.startswith(cdb):
return
elif self.beExtremelyLenient:
## WHAT THE CRAP!? MSWord9 generates HTML that includes these
## bizarre <![if !foo]> <![endif]> chunks, so I've gotta ignore
## 'em as best I can. this should really be a separate parse
## state but I don't even have any idea what these _are_.
return 'waitforgt'
else:
self._parseError("Mal-formed CDATA header")
if cd == cdb:
self.cdatabuf = ''
return 'cdata'
self._parseError("Mal-formed CDATA header")
def do_cdata(self, byte):
self.cdatabuf += byte
if self.cdatabuf.endswith("]]>"):
self.cdatabuf = self.cdatabuf[:-3]
return 'bodydata'
def end_cdata(self):
self.gotCData(self.cdatabuf)
self.cdatabuf = ''
def do_attrs(self, byte):
if byte.isalnum() or byte in identChars:
# XXX FIXME really handle !DOCTYPE at some point
if self.tagName == '!DOCTYPE':
return 'doctype'
if self.tagName[0] in '!?':
return 'waitforgt'
return 'attrname'
elif byte.isspace():
return
elif byte == '>':
self.gotTagStart(self.tagName, self.tagAttributes)
return (not self.beExtremelyLenient) and 'bodydata' or self.maybeBodyData()
elif byte == '/':
return 'afterslash'
elif self.beExtremelyLenient:
# discard and move on? Only case I've seen of this so far was:
# <foo bar="baz"">
return
self._parseError("Unexpected character: %r" % byte)
def begin_doctype(self, byte):
self.doctype = byte
def do_doctype(self, byte):
if byte == '>':
return 'bodydata'
self.doctype += byte
def end_doctype(self):
self.gotDoctype(self.doctype)
self.doctype = None
def do_waitforgt(self, byte):
if byte == '>':
if self.endtag or not self.beExtremelyLenient:
return 'bodydata'
return self.maybeBodyData()
def begin_attrname(self, byte):
self.attrname = byte
self._attrname_termtag = 0
def do_attrname(self, byte):
if byte.isalnum() or byte in identChars:
self.attrname += byte
return
elif byte == '=':
return 'beforeattrval'
elif byte.isspace():
return 'beforeeq'
elif self.beExtremelyLenient:
if byte in '"\'':
return 'attrval'
if byte in lenientIdentChars or byte.isalnum():
self.attrname += byte
return
if byte == '/':
self._attrname_termtag = 1
return
if byte == '>':
self.attrval = 'True'
self.tagAttributes[self.attrname] = self.attrval
self.gotTagStart(self.tagName, self.tagAttributes)
if self._attrname_termtag:
self.gotTagEnd(self.tagName)
return 'bodydata'
return self.maybeBodyData()
# something is really broken. let's leave this attribute where it
# is and move on to the next thing
return
self._parseError("Invalid attribute name: %r %r" % (self.attrname, byte))
def do_beforeattrval(self, byte):
if byte in '"\'':
return 'attrval'
elif byte.isspace():
return
elif self.beExtremelyLenient:
if byte in lenientIdentChars or byte.isalnum():
return 'messyattr'
if byte == '>':
self.attrval = 'True'
self.tagAttributes[self.attrname] = self.attrval
self.gotTagStart(self.tagName, self.tagAttributes)
return self.maybeBodyData()
if byte == '\\':
# I saw this in actual HTML once:
# <font size=\"3\"><sup>SM</sup></font>
return
self._parseError("Invalid initial attribute value: %r; Attribute values must be quoted." % byte)
attrname = ''
attrval = ''
def begin_beforeeq(self,byte):
self._beforeeq_termtag = 0
def do_beforeeq(self, byte):
if byte == '=':
return 'beforeattrval'
elif byte.isspace():
return
elif self.beExtremelyLenient:
if byte.isalnum() or byte in identChars:
self.attrval = 'True'
self.tagAttributes[self.attrname] = self.attrval
return 'attrname'
elif byte == '>':
self.attrval = 'True'
self.tagAttributes[self.attrname] = self.attrval
self.gotTagStart(self.tagName, self.tagAttributes)
if self._beforeeq_termtag:
self.gotTagEnd(self.tagName)
return 'bodydata'
return self.maybeBodyData()
elif byte == '/':
self._beforeeq_termtag = 1
return
self._parseError("Invalid attribute")
def begin_attrval(self, byte):
self.quotetype = byte
self.attrval = ''
def do_attrval(self, byte):
if byte == self.quotetype:
return 'attrs'
self.attrval += byte
def end_attrval(self):
self.tagAttributes[self.attrname] = self.attrval
self.attrname = self.attrval = ''
def begin_messyattr(self, byte):
self.attrval = byte
def do_messyattr(self, byte):
if byte.isspace():
return 'attrs'
elif byte == '>':
endTag = 0
if self.attrval.endswith('/'):
endTag = 1
self.attrval = self.attrval[:-1]
self.tagAttributes[self.attrname] = self.attrval
self.gotTagStart(self.tagName, self.tagAttributes)
if endTag:
self.gotTagEnd(self.tagName)
return 'bodydata'
return self.maybeBodyData()
else:
self.attrval += byte
def end_messyattr(self):
if self.attrval:
self.tagAttributes[self.attrname] = self.attrval
def begin_afterslash(self, byte):
self._after_slash_closed = 0
def do_afterslash(self, byte):
# this state is only after a self-terminating slash, e.g. <foo/>
if self._after_slash_closed:
self._parseError("Mal-formed")#XXX When does this happen??
if byte != '>':
if self.beExtremelyLenient:
return
else:
self._parseError("No data allowed after '/'")
self._after_slash_closed = 1
self.gotTagStart(self.tagName, self.tagAttributes)
self.gotTagEnd(self.tagName)
# don't need maybeBodyData here because there better not be
# any javascript code after a <script/>... we'll see :(
return 'bodydata'
def begin_bodydata(self, byte):
if self._leadingBodyData:
self.bodydata = self._leadingBodyData
del self._leadingBodyData
else:
self.bodydata = ''
def do_bodydata(self, byte):
if byte == '<':
return 'tagstart'
if byte == '&':
return 'entityref'
self.bodydata += byte
def end_bodydata(self):
self.gotText(self.bodydata)
self.bodydata = ''
def do_waitforendscript(self, byte):
if byte == '<':
return 'waitscriptendtag'
self.bodydata += byte
def begin_waitscriptendtag(self, byte):
self.temptagdata = ''
self.tagName = ''
self.endtag = 0
def do_waitscriptendtag(self, byte):
# 1 enforce / as first byte read
# 2 enforce following bytes to be subset of "script" until
# tagName == "script"
# 2a when that happens, gotText(self.bodydata) and gotTagEnd(self.tagName)
# 3 spaces can happen anywhere, they're ignored
# e.g. < / script >
# 4 anything else causes all data I've read to be moved to the
# bodydata, and switch back to waitforendscript state
# If it turns out this _isn't_ a </script>, we need to
# remember all the data we've been through so we can append it
# to bodydata
self.temptagdata += byte
# 1
if byte == '/':
self.endtag = True
elif not self.endtag:
self.bodydata += "<" + self.temptagdata
return 'waitforendscript'
# 2
elif byte.isalnum() or byte in identChars:
self.tagName += byte
if not 'script'.startswith(self.tagName):
self.bodydata += "<" + self.temptagdata
return 'waitforendscript'
elif self.tagName == 'script':
self.gotText(self.bodydata)
self.gotTagEnd(self.tagName)
return 'waitforgt'
# 3
elif byte.isspace():
return 'waitscriptendtag'
# 4
else:
self.bodydata += "<" + self.temptagdata
return 'waitforendscript'
def begin_entityref(self, byte):
self.erefbuf = ''
self.erefextra = '' # extra bit for lenient mode
def do_entityref(self, byte):
if byte.isspace() or byte == "<":
if self.beExtremelyLenient:
# '&foo' probably was '&foo'
if self.erefbuf and self.erefbuf != "amp":
self.erefextra = self.erefbuf
self.erefbuf = "amp"
if byte == "<":
return "tagstart"
else:
self.erefextra += byte
return 'spacebodydata'
self._parseError("Bad entity reference")
elif byte != ';':
self.erefbuf += byte
else:
return 'bodydata'
def end_entityref(self):
self.gotEntityReference(self.erefbuf)
# hacky support for space after & in entityref in beExtremelyLenient
# state should only happen in that case
def begin_spacebodydata(self, byte):
self.bodydata = self.erefextra
self.erefextra = None
do_spacebodydata = do_bodydata
end_spacebodydata = end_bodydata
# Sorta SAX-ish API
def gotTagStart(self, name, attributes):
'''Encountered an opening tag.
Default behaviour is to print.'''
print 'begin', name, attributes
def gotText(self, data):
'''Encountered text
Default behaviour is to print.'''
print 'text:', repr(data)
def gotEntityReference(self, entityRef):
'''Encountered mnemonic entity reference
Default behaviour is to print.'''
print 'entityRef: &%s;' % entityRef
def gotComment(self, comment):
'''Encountered comment.
Default behaviour is to ignore.'''
pass
def gotCData(self, cdata):
'''Encountered CDATA
Default behaviour is to call the gotText method'''
self.gotText(cdata)
def gotDoctype(self, doctype):
"""Encountered DOCTYPE
This is really grotty: it basically just gives you everything between
'<!DOCTYPE' and '>' as an argument.
"""
print '!DOCTYPE', repr(doctype)
def gotTagEnd(self, name):
'''Encountered closing tag
Default behaviour is to print.'''
print 'end', name
if __name__ == '__main__':
from cStringIO import StringIO
testDocument = '''
<!DOCTYPE ignore all this shit, hah its malformed!!!!@$>
<?xml version="suck it"?>
<foo>
A
<bar />
<baz boz="buz">boz &zop;</baz>
<![CDATA[ foo bar baz ]]>
</foo>
'''
x = XMLParser()
x.makeConnection(FileWrapper(StringIO()))
# fn = "/home/glyph/Projects/Twisted/doc/howto/ipc10paper.html"
fn = "/home/glyph/gruesome.xml"
# testDocument = open(fn).read()
x.dataReceived(testDocument) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/sux.py | sux.py |
#
"""\"I'm Feeling Lucky\" with U{Google<http://google.com>}.
"""
import urllib
from twisted.internet import protocol, reactor, defer
from twisted.web import http
class GoogleChecker(http.HTTPClient):
def connectionMade(self):
self.sendCommand('GET', self.factory.url)
self.sendHeader('Host', self.factory.host)
self.sendHeader('User-Agent', self.factory.agent)
self.endHeaders()
def handleHeader(self, key, value):
key = key.lower()
if key == 'location':
self.factory.gotLocation(value)
def handleStatus(self, version, status, message):
if status != '302':
self.factory.noLocation(ValueError("bad status"))
def handleEndHeaders(self):
self.factory.noLocation(ValueError("no location"))
def handleResponsePart(self, part):
pass
def handleResponseEnd(self):
pass
def connectionLost(self, reason):
self.factory.noLocation(reason)
class GoogleCheckerFactory(protocol.ClientFactory):
protocol = GoogleChecker
def __init__(self, words):
self.url = ('/search?q=%s&btnI=%s' %
(urllib.quote_plus(' '.join(words)),
urllib.quote_plus("I'm Feeling Lucky")))
self.agent="Twisted/GoogleChecker"
self.host = "www.google.com"
self.deferred = defer.Deferred()
def clientConnectionFailed(self, _, reason):
self.noLocation(reason)
def gotLocation(self, location):
if self.deferred:
self.deferred.callback(location)
self.deferred = None
def noLocation(self, error):
if self.deferred:
self.deferred.errback(error)
self.deferred = None
def checkGoogle(words):
"""Check google for a match.
@returns: a Deferred which will callback with a URL or errback with a
Failure.
"""
factory = GoogleCheckerFactory(words)
reactor.connectTCP('www.google.com', 80, factory)
return factory.deferred | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/google.py | google.py |
# System Imports
from twisted.internet import defer
from twisted.python import roots, reflect
from zope.interface import Attribute, implements, Interface
class IResource(Interface):
"""A web resource."""
isLeaf = Attribute(\
"""Signal if this IResource implementor is a "leaf node" or not. If True,
getChildWithDefault will not be called on this Resource.""")
def getChildWithDefault(name, request):
"""Return a child with the given name for the given request.
This is the external interface used by the Resource publishing
machinery. If implementing IResource without subclassing
Resource, it must be provided. However, if subclassing Resource,
getChild overridden instead.
"""
def putChild(path, child):
"""Put a child IResource implementor at the given path.
"""
def render(request):
"""Render a request. This is called on the leaf resource for
a request. Render must return either a string, which will
be sent to the browser as the HTML for the request, or
server.NOT_DONE_YET. If NOT_DONE_YET is returned,
at some point later (in a Deferred callback, usually)
call request.write("<html>") to write data to the request,
and request.finish() to send the data to the browser.
"""
def getChildForRequest(resource, request):
"""Traverse resource tree to find who will handle the request."""
while request.postpath and not resource.isLeaf:
pathElement = request.postpath.pop(0)
request.prepath.append(pathElement)
resource = resource.getChildWithDefault(pathElement, request)
return resource
class Resource:
"""I define a web-accessible resource.
I serve 2 main purposes; one is to provide a standard representation for
what HTTP specification calls an 'entity', and the other is to provide an
abstract directory structure for URL retrieval.
"""
implements(IResource)
entityType = IResource
server = None
def __init__(self):
"""Initialize.
"""
self.children = {}
isLeaf = 0
### Abstract Collection Interface
def listStaticNames(self):
return self.children.keys()
def listStaticEntities(self):
return self.children.items()
def listNames(self):
return self.listStaticNames() + self.listDynamicNames()
def listEntities(self):
return self.listStaticEntities() + self.listDynamicEntities()
def listDynamicNames(self):
return []
def listDynamicEntities(self, request=None):
return []
def getStaticEntity(self, name):
return self.children.get(name)
def getDynamicEntity(self, name, request):
if not self.children.has_key(name):
return self.getChild(name, request)
else:
return None
def delEntity(self, name):
del self.children[name]
def reallyPutEntity(self, name, entity):
self.children[name] = entity
# Concrete HTTP interface
def getChild(self, path, request):
"""Retrieve a 'child' resource from me.
Implement this to create dynamic resource generation -- resources which
are always available may be registered with self.putChild().
This will not be called if the class-level variable 'isLeaf' is set in
your subclass; instead, the 'postpath' attribute of the request will be
left as a list of the remaining path elements.
For example, the URL /foo/bar/baz will normally be::
| site.resource.getChild('foo').getChild('bar').getChild('baz').
However, if the resource returned by 'bar' has isLeaf set to true, then
the getChild call will never be made on it.
@param path: a string, describing the child
@param request: a twisted.web.server.Request specifying meta-information
about the request that is being made for this child.
"""
return error.NoResource("No such child resource.")
def getChildWithDefault(self, path, request):
"""Retrieve a static or dynamically generated child resource from me.
First checks if a resource was added manually by putChild, and then
call getChild to check for dynamic resources. Only override if you want
to affect behaviour of all child lookups, rather than just dynamic
ones.
This will check to see if I have a pre-registered child resource of the
given name, and call getChild if I do not.
"""
if self.children.has_key(path):
return self.children[path]
return self.getChild(path, request)
def getChildForRequest(self, request):
import warnings
warnings.warn("Please use module level getChildForRequest.", DeprecationWarning, 2)
return getChildForRequest(self, request)
def putChild(self, path, child):
"""Register a static child.
You almost certainly don't want '/' in your path. If you
intended to have the root of a folder, e.g. /foo/, you want
path to be ''.
"""
self.children[path] = child
child.server = self.server
def render(self, request):
"""Render a given resource. See L{IResource}'s render method.
I delegate to methods of self with the form 'render_METHOD'
where METHOD is the HTTP that was used to make the
request. Examples: render_GET, render_HEAD, render_POST, and
so on. Generally you should implement those methods instead of
overriding this one.
render_METHOD methods are expected to return a string which
will be the rendered page, unless the return value is
twisted.web.server.NOT_DONE_YET, in which case it is this
class's responsibility to write the results to
request.write(data), then call request.finish().
Old code that overrides render() directly is likewise expected
to return a string or NOT_DONE_YET.
"""
m = getattr(self, 'render_' + request.method, None)
if not m:
from twisted.web.server import UnsupportedMethod
raise UnsupportedMethod(getattr(self, 'allowedMethods', ()))
return m(request)
def render_HEAD(self, request):
"""Default handling of HEAD method.
I just return self.render_GET(request). When method is HEAD,
the framework will handle this correctly.
"""
return self.render_GET(request)
#t.w imports
#This is ugly, I know, but since error.py directly access resource.Resource
#during import-time (it subclasses it), the Resource class must be defined
#by the time error is imported.
import error | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/resource.py | resource.py |
#
from __future__ import nested_scopes
from twisted.web import microdom
from microdom import getElementsByTagName, escape, unescape
try:
import cStringIO as StringIO
except ImportError:
import StringIO
class NodeLookupError(Exception): pass
def substitute(request, node, subs):
"""
Look through the given node's children for strings, and
attempt to do string substitution with the given parameter.
"""
for child in node.childNodes:
if hasattr(child, 'nodeValue') and child.nodeValue:
child.replaceData(0, len(child.nodeValue), child.nodeValue % subs)
substitute(request, child, subs)
def _get(node, nodeId, nodeAttrs=('id','class','model','pattern')):
"""
(internal) Get a node with the specified C{nodeId} as any of the C{class},
C{id} or C{pattern} attributes.
"""
if hasattr(node, 'hasAttributes') and node.hasAttributes():
for nodeAttr in nodeAttrs:
if (str (node.getAttribute(nodeAttr)) == nodeId):
return node
if node.hasChildNodes():
if hasattr(node.childNodes, 'length'):
length = node.childNodes.length
else:
length = len(node.childNodes)
for childNum in range(length):
result = _get(node.childNodes[childNum], nodeId)
if result: return result
def get(node, nodeId):
"""
Get a node with the specified C{nodeId} as any of the C{class},
C{id} or C{pattern} attributes. If there is no such node, raise
L{NodeLookupError}.
"""
result = _get(node, nodeId)
if result: return result
raise NodeLookupError, nodeId
def getIfExists(node, nodeId):
"""
Get a node with the specified C{nodeId} as any of the C{class},
C{id} or C{pattern} attributes. If there is no such node, return
C{None}.
"""
return _get(node, nodeId)
def getAndClear(node, nodeId):
"""Get a node with the specified C{nodeId} as any of the C{class},
C{id} or C{pattern} attributes. If there is no such node, raise
L{NodeLookupError}. Remove all child nodes before returning.
"""
result = get(node, nodeId)
if result:
clearNode(result)
return result
def clearNode(node):
"""
Remove all children from the given node.
"""
node.childNodes[:] = []
def locateNodes(nodeList, key, value, noNesting=1):
"""
Find subnodes in the given node where the given attribute
has the given value.
"""
returnList = []
if not isinstance(nodeList, type([])):
return locateNodes(nodeList.childNodes, key, value, noNesting)
for childNode in nodeList:
if not hasattr(childNode, 'getAttribute'):
continue
if str(childNode.getAttribute(key)) == value:
returnList.append(childNode)
if noNesting:
continue
returnList.extend(locateNodes(childNode, key, value, noNesting))
return returnList
def superSetAttribute(node, key, value):
if not hasattr(node, 'setAttribute'): return
node.setAttribute(key, value)
if node.hasChildNodes():
for child in node.childNodes:
superSetAttribute(child, key, value)
def superPrependAttribute(node, key, value):
if not hasattr(node, 'setAttribute'): return
old = node.getAttribute(key)
if old:
node.setAttribute(key, value+'/'+old)
else:
node.setAttribute(key, value)
if node.hasChildNodes():
for child in node.childNodes:
superPrependAttribute(child, key, value)
def superAppendAttribute(node, key, value):
if not hasattr(node, 'setAttribute'): return
old = node.getAttribute(key)
if old:
node.setAttribute(key, old + '/' + value)
else:
node.setAttribute(key, value)
if node.hasChildNodes():
for child in node.childNodes:
superAppendAttribute(child, key, value)
def gatherTextNodes(iNode, dounescape=0, joinWith=""):
"""Visit each child node and collect its text data, if any, into a string.
For example::
>>> doc=microdom.parseString('<a>1<b>2<c>3</c>4</b></a>')
>>> gatherTextNodes(doc.documentElement)
'1234'
With dounescape=1, also convert entities back into normal characters.
@return: the gathered nodes as a single string
@rtype: str
"""
gathered=[]
gathered_append=gathered.append
slice=[iNode]
while len(slice)>0:
c=slice.pop(0)
if hasattr(c, 'nodeValue') and c.nodeValue is not None:
if dounescape:
val=unescape(c.nodeValue)
else:
val=c.nodeValue
gathered_append(val)
slice[:0]=c.childNodes
return joinWith.join(gathered)
class RawText(microdom.Text):
"""This is an evil and horrible speed hack. Basically, if you have a big
chunk of XML that you want to insert into the DOM, but you don't want to
incur the cost of parsing it, you can construct one of these and insert it
into the DOM. This will most certainly only work with microdom as the API
for converting nodes to xml is different in every DOM implementation.
This could be improved by making this class a Lazy parser, so if you
inserted this into the DOM and then later actually tried to mutate this
node, it would be parsed then.
"""
def writexml(self, writer, indent="", addindent="", newl="", strip=0, nsprefixes=None, namespace=None):
writer.write("%s%s%s" % (indent, self.data, newl))
def findNodes(parent, matcher, accum=None):
if accum is None:
accum = []
if not parent.hasChildNodes():
return accum
for child in parent.childNodes:
# print child, child.nodeType, child.nodeName
if matcher(child):
accum.append(child)
findNodes(child, matcher, accum)
return accum
def findNodesShallowOnMatch(parent, matcher, recurseMatcher, accum=None):
if accum is None:
accum = []
if not parent.hasChildNodes():
return accum
for child in parent.childNodes:
# print child, child.nodeType, child.nodeName
if matcher(child):
accum.append(child)
if recurseMatcher(child):
findNodesShallowOnMatch(child, matcher, recurseMatcher, accum)
return accum
def findNodesShallow(parent, matcher, accum=None):
if accum is None:
accum = []
if not parent.hasChildNodes():
return accum
for child in parent.childNodes:
if matcher(child):
accum.append(child)
else:
findNodes(child, matcher, accum)
return accum
def findElementsWithAttributeShallow(parent, attribute):
return findNodesShallow(parent,
lambda n: isinstance(n, microdom.Element) and
n.hasAttribute(attribute))
def findElements(parent, matcher):
return findNodes(
parent,
lambda n, matcher=matcher: isinstance(n, microdom.Element) and
matcher(n))
def findElementsWithAttribute(parent, attribute, value=None):
if value:
return findElements(
parent,
lambda n, attribute=attribute, value=value:
n.hasAttribute(attribute) and n.getAttribute(attribute) == value)
else:
return findElements(
parent,
lambda n, attribute=attribute: n.hasAttribute(attribute))
def findNodesNamed(parent, name):
return findNodes(parent, lambda n, name=name: n.nodeName == name)
def writeNodeData(node, oldio):
for subnode in node.childNodes:
if hasattr(subnode, 'data'):
oldio.write(str(subnode.data))
else:
writeNodeData(subnode, oldio)
def getNodeText(node):
oldio = StringIO.StringIO()
writeNodeData(node, oldio)
return oldio.getvalue()
def getParents(node):
l = []
while node:
l.append(node)
node = node.parentNode
return l
def namedChildren(parent, nodeName):
"""namedChildren(parent, nodeName) -> children (not descendants) of parent
that have tagName == nodeName
"""
return [n for n in parent.childNodes if getattr(n, 'tagName', '')==nodeName] | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/domhelpers.py | domhelpers.py |
# SOAPpy
import SOAPpy
# twisted imports
from twisted.web import server, resource, client
from twisted.internet import defer
class SOAPPublisher(resource.Resource):
"""Publish SOAP methods.
By default, publish methods beginning with 'soap_'. If the method
has an attribute 'useKeywords', it well get the arguments passed
as keyword args.
"""
isLeaf = 1
# override to change the encoding used for responses
encoding = "UTF-8"
def lookupFunction(self, functionName):
"""Lookup published SOAP function.
Override in subclasses. Default behaviour - publish methods
starting with soap_.
@return: callable or None if not found.
"""
return getattr(self, "soap_%s" % functionName, None)
def render(self, request):
"""Handle a SOAP command."""
data = request.content.read()
p, header, body, attrs = SOAPpy.parseSOAPRPC(data, 1, 1, 1)
methodName, args, kwargs, ns = p._name, p._aslist, p._asdict, p._ns
# deal with changes in SOAPpy 0.11
if callable(args):
args = args()
if callable(kwargs):
kwargs = kwargs()
function = self.lookupFunction(methodName)
if not function:
self._methodNotFound(request, methodName)
return server.NOT_DONE_YET
else:
if hasattr(function, "useKeywords"):
keywords = {}
for k, v in kwargs.items():
keywords[str(k)] = v
d = defer.maybeDeferred(function, **keywords)
else:
d = defer.maybeDeferred(function, *args)
d.addCallback(self._gotResult, request, methodName)
d.addErrback(self._gotError, request, methodName)
return server.NOT_DONE_YET
def _methodNotFound(self, request, methodName):
response = SOAPpy.buildSOAP(SOAPpy.faultType("%s:Client" %
SOAPpy.NS.ENV_T, "Method %s not found" % methodName),
encoding=self.encoding)
self._sendResponse(request, response, status=500)
def _gotResult(self, result, request, methodName):
if not isinstance(result, SOAPpy.voidType):
result = {"Result": result}
response = SOAPpy.buildSOAP(kw={'%sResponse' % methodName: result},
encoding=self.encoding)
self._sendResponse(request, response)
def _gotError(self, failure, request, methodName):
e = failure.value
if isinstance(e, SOAPpy.faultType):
fault = e
else:
fault = SOAPpy.faultType("%s:Server" % SOAPpy.NS.ENV_T,
"Method %s failed." % methodName)
response = SOAPpy.buildSOAP(fault, encoding=self.encoding)
self._sendResponse(request, response, status=500)
def _sendResponse(self, request, response, status=200):
request.setResponseCode(status)
if self.encoding is not None:
mimeType = 'text/xml; charset="%s"' % self.encoding
else:
mimeType = "text/xml"
request.setHeader("Content-type", mimeType)
request.setHeader("Content-length", str(len(response)))
request.write(response)
request.finish()
class Proxy:
"""A Proxy for making remote SOAP calls.
Pass the URL of the remote SOAP server to the constructor.
Use proxy.callRemote('foobar', 1, 2) to call remote method
'foobar' with args 1 and 2, proxy.callRemote('foobar', x=1)
will call foobar with named argument 'x'.
"""
# at some point this should have encoding etc. kwargs
def __init__(self, url, namespace=None, header=None):
self.url = url
self.namespace = namespace
self.header = header
def _cbGotResult(self, result):
result = SOAPpy.parseSOAPRPC(result)
if hasattr(result, 'Result'):
return result.Result
elif len(result) == 1:
## SOAPpy 0.11.6 wraps the return results in a containing structure.
## This check added to make Proxy behaviour emulate SOAPProxy, which
## flattens the structure by default.
## This behaviour is OK because even singleton lists are wrapped in
## another singleton structType, which is almost always useless.
return result[0]
else:
return result
def callRemote(self, method, *args, **kwargs):
payload = SOAPpy.buildSOAP(args=args, kw=kwargs, method=method,
header=self.header, namespace=self.namespace)
return client.getPage(self.url, postdata=payload, method="POST",
headers={'content-type': 'text/xml',
'SOAPAction': method}
).addCallback(self._cbGotResult) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/soap.py | soap.py |
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
"""HyperText Transfer Protocol implementation.
This is used by twisted.web.
API Stability: stable
Future Plans:
- HTTP client support will at some point be refactored to support HTTP/1.1.
- Accept chunked data from clients in server.
- Other missing HTTP features from the RFC.
Maintainer: U{Itamar Shtull-Trauring<mailto:[email protected]>}
"""
# system imports
from cStringIO import StringIO
import tempfile
import base64, binascii
import cgi
import socket
import math
import time
import calendar
import warnings
import os
from zope.interface import implements
# twisted imports
from twisted.internet import interfaces, reactor, protocol, address, task
from twisted.protocols import policies, basic
from twisted.python import log
try: # try importing the fast, C version
from twisted.protocols._c_urlarg import unquote
except ImportError:
from urllib import unquote
protocol_version = "HTTP/1.1"
_CONTINUE = 100
SWITCHING = 101
OK = 200
CREATED = 201
ACCEPTED = 202
NON_AUTHORITATIVE_INFORMATION = 203
NO_CONTENT = 204
RESET_CONTENT = 205
PARTIAL_CONTENT = 206
MULTI_STATUS = 207
MULTIPLE_CHOICE = 300
MOVED_PERMANENTLY = 301
FOUND = 302
SEE_OTHER = 303
NOT_MODIFIED = 304
USE_PROXY = 305
TEMPORARY_REDIRECT = 307
BAD_REQUEST = 400
UNAUTHORIZED = 401
PAYMENT_REQUIRED = 402
FORBIDDEN = 403
NOT_FOUND = 404
NOT_ALLOWED = 405
NOT_ACCEPTABLE = 406
PROXY_AUTH_REQUIRED = 407
REQUEST_TIMEOUT = 408
CONFLICT = 409
GONE = 410
LENGTH_REQUIRED = 411
PRECONDITION_FAILED = 412
REQUEST_ENTITY_TOO_LARGE = 413
REQUEST_URI_TOO_LONG = 414
UNSUPPORTED_MEDIA_TYPE = 415
REQUESTED_RANGE_NOT_SATISFIABLE = 416
EXPECTATION_FAILED = 417
INTERNAL_SERVER_ERROR = 500
NOT_IMPLEMENTED = 501
BAD_GATEWAY = 502
SERVICE_UNAVAILABLE = 503
GATEWAY_TIMEOUT = 504
HTTP_VERSION_NOT_SUPPORTED = 505
INSUFFICIENT_STORAGE_SPACE = 507
NOT_EXTENDED = 510
RESPONSES = {
# 100
_CONTINUE: "Continue",
SWITCHING: "Switching Protocols",
# 200
OK: "OK",
CREATED: "Created",
ACCEPTED: "Accepted",
NON_AUTHORITATIVE_INFORMATION: "Non-Authoritative Information",
NO_CONTENT: "No Content",
RESET_CONTENT: "Reset Content.",
PARTIAL_CONTENT: "Partial Content",
MULTI_STATUS: "Multi-Status",
# 300
MULTIPLE_CHOICE: "Multiple Choices",
MOVED_PERMANENTLY: "Moved Permanently",
FOUND: "Found",
SEE_OTHER: "See Other",
NOT_MODIFIED: "Not Modified",
USE_PROXY: "Use Proxy",
# 306 not defined??
TEMPORARY_REDIRECT: "Temporary Redirect",
# 400
BAD_REQUEST: "Bad Request",
UNAUTHORIZED: "Unauthorized",
PAYMENT_REQUIRED: "Payment Required",
FORBIDDEN: "Forbidden",
NOT_FOUND: "Not Found",
NOT_ALLOWED: "Method Not Allowed",
NOT_ACCEPTABLE: "Not Acceptable",
PROXY_AUTH_REQUIRED: "Proxy Authentication Required",
REQUEST_TIMEOUT: "Request Time-out",
CONFLICT: "Conflict",
GONE: "Gone",
LENGTH_REQUIRED: "Length Required",
PRECONDITION_FAILED: "Precondition Failed",
REQUEST_ENTITY_TOO_LARGE: "Request Entity Too Large",
REQUEST_URI_TOO_LONG: "Request-URI Too Long",
UNSUPPORTED_MEDIA_TYPE: "Unsupported Media Type",
REQUESTED_RANGE_NOT_SATISFIABLE: "Requested Range not satisfiable",
EXPECTATION_FAILED: "Expectation Failed",
# 500
INTERNAL_SERVER_ERROR: "Internal Server Error",
NOT_IMPLEMENTED: "Not Implemented",
BAD_GATEWAY: "Bad Gateway",
SERVICE_UNAVAILABLE: "Service Unavailable",
GATEWAY_TIMEOUT: "Gateway Time-out",
HTTP_VERSION_NOT_SUPPORTED: "HTTP Version not supported",
INSUFFICIENT_STORAGE_SPACE: "Insufficient Storage Space",
NOT_EXTENDED: "Not Extended"
}
CACHED = """Magic constant returned by http.Request methods to set cache
validation headers when the request is conditional and the value fails
the condition."""
# backwards compatability
responses = RESPONSES
# datetime parsing and formatting
weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
monthname = [None,
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
weekdayname_lower = [name.lower() for name in weekdayname]
monthname_lower = [name and name.lower() for name in monthname]
def parse_qs(qs, keep_blank_values=0, strict_parsing=0, unquote=unquote):
"""like cgi.parse_qs, only with custom unquote function"""
d = {}
items = [s2 for s1 in qs.split("&") for s2 in s1.split(";")]
for item in items:
try:
k, v = item.split("=", 1)
except ValueError:
if strict_parsing:
raise
continue
if v or keep_blank_values:
k = unquote(k.replace("+", " "))
v = unquote(v.replace("+", " "))
if k in d:
d[k].append(v)
else:
d[k] = [v]
return d
def datetimeToString(msSinceEpoch=None):
"""Convert seconds since epoch to HTTP datetime string."""
if msSinceEpoch == None:
msSinceEpoch = time.time()
year, month, day, hh, mm, ss, wd, y, z = time.gmtime(msSinceEpoch)
s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
weekdayname[wd],
day, monthname[month], year,
hh, mm, ss)
return s
def datetimeToLogString(msSinceEpoch=None):
"""Convert seconds since epoch to log datetime string."""
if msSinceEpoch == None:
msSinceEpoch = time.time()
year, month, day, hh, mm, ss, wd, y, z = time.gmtime(msSinceEpoch)
s = "[%02d/%3s/%4d:%02d:%02d:%02d +0000]" % (
day, monthname[month], year,
hh, mm, ss)
return s
# a hack so we don't need to recalculate log datetime every hit,
# at the price of a small, unimportant, inaccuracy.
_logDateTime = None
_logDateTimeUsers = 0
_resetLogDateTimeID = None
def _resetLogDateTime():
global _logDateTime
global _resetLogDateTime
global _resetLogDateTimeID
_logDateTime = datetimeToLogString()
_resetLogDateTimeID = reactor.callLater(1, _resetLogDateTime)
def _logDateTimeStart():
global _logDateTimeUsers
if not _logDateTimeUsers:
_resetLogDateTime()
_logDateTimeUsers += 1
def _logDateTimeStop():
global _logDateTimeUsers
_logDateTimeUsers -= 1;
if (not _logDateTimeUsers and _resetLogDateTimeID
and _resetLogDateTimeID.active()):
_resetLogDateTimeID.cancel()
def timegm(year, month, day, hour, minute, second):
"""Convert time tuple in GMT to seconds since epoch, GMT"""
EPOCH = 1970
assert year >= EPOCH
assert 1 <= month <= 12
days = 365*(year-EPOCH) + calendar.leapdays(EPOCH, year)
for i in range(1, month):
days = days + calendar.mdays[i]
if month > 2 and calendar.isleap(year):
days = days + 1
days = days + day - 1
hours = days*24 + hour
minutes = hours*60 + minute
seconds = minutes*60 + second
return seconds
def stringToDatetime(dateString):
"""Convert an HTTP date string (one of three formats) to seconds since epoch."""
parts = dateString.split()
if not parts[0][0:3].lower() in weekdayname_lower:
# Weekday is stupid. Might have been omitted.
try:
return stringToDatetime("Sun, "+dateString)
except ValueError:
# Guess not.
pass
partlen = len(parts)
if (partlen == 5 or partlen == 6) and parts[1].isdigit():
# 1st date format: Sun, 06 Nov 1994 08:49:37 GMT
# (Note: "GMT" is literal, not a variable timezone)
# (also handles without "GMT")
# This is the normal format
day = parts[1]
month = parts[2]
year = parts[3]
time = parts[4]
elif (partlen == 3 or partlen == 4) and parts[1].find('-') != -1:
# 2nd date format: Sunday, 06-Nov-94 08:49:37 GMT
# (Note: "GMT" is literal, not a variable timezone)
# (also handles without without "GMT")
# Two digit year, yucko.
day, month, year = parts[1].split('-')
time = parts[2]
year=int(year)
if year < 69:
year = year + 2000
elif year < 100:
year = year + 1900
elif len(parts) == 5:
# 3rd date format: Sun Nov 6 08:49:37 1994
# ANSI C asctime() format.
day = parts[2]
month = parts[1]
year = parts[4]
time = parts[3]
else:
raise ValueError("Unknown datetime format %r" % dateString)
day = int(day)
month = int(monthname_lower.index(month.lower()))
year = int(year)
hour, min, sec = map(int, time.split(':'))
return int(timegm(year, month, day, hour, min, sec))
def toChunk(data):
"""Convert string to a chunk.
@returns: a tuple of strings representing the chunked encoding of data"""
return ("%x\r\n" % len(data), data, "\r\n")
def fromChunk(data):
"""Convert chunk to string.
@returns: tuple (result, remaining), may raise ValueError.
"""
prefix, rest = data.split('\r\n', 1)
length = int(prefix, 16)
if length < 0:
raise ValueError("Chunk length must be >= 0, not %d" % (length,))
if not rest[length:length + 2] == '\r\n':
raise ValueError, "chunk must end with CRLF"
return rest[:length], rest[length + 2:]
def parseContentRange(header):
"""Parse a content-range header into (start, end, realLength).
realLength might be None if real length is not known ('*').
"""
kind, other = header.strip().split()
if kind.lower() != "bytes":
raise ValueError, "a range of type %r is not supported"
startend, realLength = other.split("/")
start, end = map(int, startend.split("-"))
if realLength == "*":
realLength = None
else:
realLength = int(realLength)
return (start, end, realLength)
class StringTransport:
"""
I am a StringIO wrapper that conforms for the transport API. I support
the `writeSequence' method.
"""
def __init__(self):
self.s = StringIO()
def writeSequence(self, seq):
self.s.write(''.join(seq))
def __getattr__(self, attr):
return getattr(self.__dict__['s'], attr)
class HTTPClient(basic.LineReceiver):
"""A client for HTTP 1.0
Notes:
You probably want to send a 'Host' header with the name of
the site you're connecting to, in order to not break name
based virtual hosting.
"""
length = None
firstLine = 1
__buffer = None
def sendCommand(self, command, path):
self.transport.write('%s %s HTTP/1.0\r\n' % (command, path))
def sendHeader(self, name, value):
self.transport.write('%s: %s\r\n' % (name, value))
def endHeaders(self):
self.transport.write('\r\n')
def lineReceived(self, line):
if self.firstLine:
self.firstLine = 0
l = line.split(None, 2)
version = l[0]
status = l[1]
try:
message = l[2]
except IndexError:
# sometimes there is no message
message = ""
self.handleStatus(version, status, message)
return
if line:
key, val = line.split(':', 1)
val = val.lstrip()
self.handleHeader(key, val)
if key.lower() == 'content-length':
self.length = int(val)
else:
self.__buffer = StringIO()
self.handleEndHeaders()
self.setRawMode()
def connectionLost(self, reason):
self.handleResponseEnd()
def handleResponseEnd(self):
if self.__buffer is not None:
b = self.__buffer.getvalue()
self.__buffer = None
self.handleResponse(b)
def handleResponsePart(self, data):
self.__buffer.write(data)
def connectionMade(self):
pass
handleStatus = handleHeader = handleEndHeaders = lambda *args: None
def rawDataReceived(self, data):
if self.length is not None:
data, rest = data[:self.length], data[self.length:]
self.length -= len(data)
else:
rest = ''
self.handleResponsePart(data)
if self.length == 0:
self.handleResponseEnd()
self.setLineMode(rest)
# response codes that must have empty bodies
NO_BODY_CODES = (204, 304)
class Request:
"""A HTTP request.
Subclasses should override the process() method to determine how
the request will be processed.
@ivar method: The HTTP method that was used.
@ivar uri: The full URI that was requested (includes arguments).
@ivar path: The path only (arguments not included).
@ivar args: All of the arguments, including URL and POST arguments.
@type args: A mapping of strings (the argument names) to lists of values.
i.e., ?foo=bar&foo=baz&quux=spam results in
{'foo': ['bar', 'baz'], 'quux': ['spam']}.
@ivar received_headers: All received headers
"""
implements(interfaces.IConsumer)
producer = None
finished = 0
code = OK
code_message = RESPONSES[OK]
method = "(no method yet)"
clientproto = "(no clientproto yet)"
uri = "(no uri yet)"
startedWriting = 0
chunked = 0
sentLength = 0 # content-length of response, or total bytes sent via chunking
etag = None
lastModified = None
_forceSSL = 0
def __init__(self, channel, queued):
"""
@param channel: the channel we're connected to.
@param queued: are we in the request queue, or can we start writing to
the transport?
"""
self.channel = channel
self.queued = queued
self.received_headers = {}
self.received_cookies = {}
self.headers = {} # outgoing headers
self.cookies = [] # outgoing cookies
if queued:
self.transport = StringTransport()
else:
self.transport = self.channel.transport
def _cleanup(self):
"""Called when have finished responding and are no longer queued."""
if self.producer:
log.err(RuntimeError("Producer was not unregistered for %s" % self.uri))
self.unregisterProducer()
self.channel.requestDone(self)
del self.channel
try:
self.content.close()
except OSError:
# win32 suckiness, no idea why it does this
pass
del self.content
# methods for channel - end users should not use these
def noLongerQueued(self):
"""Notify the object that it is no longer queued.
We start writing whatever data we have to the transport, etc.
This method is not intended for users.
"""
if not self.queued:
raise RuntimeError, "noLongerQueued() got called unnecessarily."
self.queued = 0
# set transport to real one and send any buffer data
data = self.transport.getvalue()
self.transport = self.channel.transport
if data:
self.transport.write(data)
# if we have producer, register it with transport
if (self.producer is not None) and not self.finished:
self.transport.registerProducer(self.producer, self.streamingProducer)
# if we're finished, clean up
if self.finished:
self._cleanup()
def gotLength(self, length):
"""Called when HTTP channel got length of content in this request.
This method is not intended for users.
"""
if length < 100000:
self.content = StringIO()
else:
self.content = tempfile.TemporaryFile()
def parseCookies(self):
"""Parse cookie headers.
This method is not intended for users."""
cookietxt = self.getHeader("cookie")
if cookietxt:
for cook in cookietxt.split(';'):
cook = cook.lstrip()
try:
k, v = cook.split('=', 1)
self.received_cookies[k] = v
except ValueError:
pass
def handleContentChunk(self, data):
"""Write a chunk of data.
This method is not intended for users.
"""
self.content.write(data)
def requestReceived(self, command, path, version):
"""Called by channel when all data has been received.
This method is not intended for users.
"""
self.content.seek(0,0)
self.args = {}
self.stack = []
self.method, self.uri = command, path
self.clientproto = version
x = self.uri.split('?', 1)
if len(x) == 1:
self.path = self.uri
else:
self.path, argstring = x
self.args = parse_qs(argstring, 1)
# cache the client and server information, we'll need this later to be
# serialized and sent with the request so CGIs will work remotely
self.client = self.channel.transport.getPeer()
self.host = self.channel.transport.getHost()
# Argument processing
args = self.args
ctype = self.getHeader('content-type')
if self.method == "POST" and ctype:
mfd = 'multipart/form-data'
key, pdict = cgi.parse_header(ctype)
if key == 'application/x-www-form-urlencoded':
args.update(parse_qs(self.content.read(), 1))
elif key == mfd:
try:
args.update(cgi.parse_multipart(self.content, pdict))
except KeyError, e:
if e.args[0] == 'content-disposition':
# Parse_multipart can't cope with missing
# content-dispostion headers in multipart/form-data
# parts, so we catch the exception and tell the client
# it was a bad request.
self.channel.transport.write(
"HTTP/1.1 400 Bad Request\r\n\r\n")
self.channel.transport.loseConnection()
return
raise
self.process()
def __repr__(self):
return '<%s %s %s>'% (self.method, self.uri, self.clientproto)
def process(self):
"""Override in subclasses.
This method is not intended for users.
"""
pass
# consumer interface
def registerProducer(self, producer, streaming):
"""Register a producer."""
if self.producer:
raise ValueError, "registering producer %s before previous one (%s) was unregistered" % (producer, self.producer)
self.streamingProducer = streaming
self.producer = producer
if self.queued:
producer.pauseProducing()
else:
self.transport.registerProducer(producer, streaming)
def unregisterProducer(self):
"""Unregister the producer."""
if not self.queued:
self.transport.unregisterProducer()
self.producer = None
# private http response methods
def _sendError(self, code, resp=''):
self.transport.write('%s %s %s\r\n\r\n' % (self.clientproto, code, resp))
# The following is the public interface that people should be
# writing to.
def getHeader(self, key):
"""Get a header that was sent from the network.
"""
return self.received_headers.get(key.lower())
def getCookie(self, key):
"""Get a cookie that was sent from the network.
"""
return self.received_cookies.get(key)
def finish(self):
"""We are finished writing data."""
if self.finished:
warnings.warn("Warning! request.finish called twice.", stacklevel=2)
return
if not self.startedWriting:
# write headers
self.write('')
if self.chunked:
# write last chunk and closing CRLF
self.transport.write("0\r\n\r\n")
# log request
if hasattr(self.channel, "factory"):
self.channel.factory.log(self)
self.finished = 1
if not self.queued:
self._cleanup()
def write(self, data):
"""
Write some data as a result of an HTTP request. The first
time this is called, it writes out response data.
"""
if not self.startedWriting:
self.startedWriting = 1
version = self.clientproto
l = []
l.append('%s %s %s\r\n' % (version, self.code,
self.code_message))
# if we don't have a content length, we send data in
# chunked mode, so that we can support pipelining in
# persistent connections.
if ((version == "HTTP/1.1") and
(self.headers.get('content-length', None) is None) and
self.method != "HEAD" and self.code not in NO_BODY_CODES):
l.append("%s: %s\r\n" % ('Transfer-encoding', 'chunked'))
self.chunked = 1
if self.lastModified is not None:
if self.headers.has_key('last-modified'):
log.msg("Warning: last-modified specified both in"
" header list and lastModified attribute.")
else:
self.setHeader('last-modified',
datetimeToString(self.lastModified))
if self.etag is not None:
self.setHeader('ETag', self.etag)
for name, value in self.headers.items():
l.append("%s: %s\r\n" % (name.capitalize(), value))
for cookie in self.cookies:
l.append('%s: %s\r\n' % ("Set-Cookie", cookie))
l.append("\r\n")
self.transport.writeSequence(l)
# if this is a "HEAD" request, we shouldn't return any data
if self.method == "HEAD":
self.write = lambda data: None
return
# for certain result codes, we should never return any data
if self.code in NO_BODY_CODES:
self.write = lambda data: None
return
self.sentLength = self.sentLength + len(data)
if data:
if self.chunked:
self.transport.writeSequence(toChunk(data))
else:
self.transport.write(data)
def addCookie(self, k, v, expires=None, domain=None, path=None, max_age=None, comment=None, secure=None):
"""Set an outgoing HTTP cookie.
In general, you should consider using sessions instead of cookies, see
twisted.web.server.Request.getSession and the
twisted.web.server.Session class for details.
"""
cookie = '%s=%s' % (k, v)
if expires is not None:
cookie = cookie +"; Expires=%s" % expires
if domain is not None:
cookie = cookie +"; Domain=%s" % domain
if path is not None:
cookie = cookie +"; Path=%s" % path
if max_age is not None:
cookie = cookie +"; Max-Age=%s" % max_age
if comment is not None:
cookie = cookie +"; Comment=%s" % comment
if secure:
cookie = cookie +"; Secure"
self.cookies.append(cookie)
def setResponseCode(self, code, message=None):
"""Set the HTTP response code.
"""
self.code = code
if message:
self.code_message = message
else:
self.code_message = RESPONSES.get(code, "Unknown Status")
def setHeader(self, k, v):
"""Set an outgoing HTTP header.
"""
self.headers[k.lower()] = v
def redirect(self, url):
"""Utility function that does a redirect.
The request should have finish() called after this.
"""
self.setResponseCode(FOUND)
self.setHeader("location", url)
def setLastModified(self, when):
"""Set the X{Last-Modified} time for the response to this request.
If I am called more than once, I ignore attempts to set
Last-Modified earlier, only replacing the Last-Modified time
if it is to a later value.
If I am a conditional request, I may modify my response code
to L{NOT_MODIFIED} if appropriate for the time given.
@param when: The last time the resource being returned was
modified, in seconds since the epoch.
@type when: number
@return: If I am a X{If-Modified-Since} conditional request and
the time given is not newer than the condition, I return
L{http.CACHED<CACHED>} to indicate that you should write no
body. Otherwise, I return a false value.
"""
# time.time() may be a float, but the HTTP-date strings are
# only good for whole seconds.
when = long(math.ceil(when))
if (not self.lastModified) or (self.lastModified < when):
self.lastModified = when
modified_since = self.getHeader('if-modified-since')
if modified_since:
modified_since = stringToDatetime(modified_since.split(';', 1)[0])
if modified_since >= when:
self.setResponseCode(NOT_MODIFIED)
return CACHED
return None
def setETag(self, etag):
"""Set an X{entity tag} for the outgoing response.
That's \"entity tag\" as in the HTTP/1.1 X{ETag} header, \"used
for comparing two or more entities from the same requested
resource.\"
If I am a conditional request, I may modify my response code
to L{NOT_MODIFIED} or L{PRECONDITION_FAILED}, if appropriate
for the tag given.
@param etag: The entity tag for the resource being returned.
@type etag: string
@return: If I am a X{If-None-Match} conditional request and
the tag matches one in the request, I return
L{http.CACHED<CACHED>} to indicate that you should write
no body. Otherwise, I return a false value.
"""
if etag:
self.etag = etag
tags = self.getHeader("if-none-match")
if tags:
tags = tags.split()
if (etag in tags) or ('*' in tags):
self.setResponseCode(((self.method in ("HEAD", "GET"))
and NOT_MODIFIED)
or PRECONDITION_FAILED)
return CACHED
return None
def getAllHeaders(self):
"""Return dictionary of all headers the request received."""
return self.received_headers
def getRequestHostname(self):
"""Get the hostname that the user passed in to the request.
This will either use the Host: header (if it is available) or the
host we are listening on if the header is unavailable.
"""
return (self.getHeader('host') or
socket.gethostbyaddr(self.getHost()[1])[0]
).split(':')[0]
def getHost(self):
"""Get my originally requesting transport's host.
Don't rely on the 'transport' attribute, since Request objects may be
copied remotely. For information on this method's return value, see
twisted.internet.tcp.Port.
"""
return self.host
def setHost(self, host, port, ssl=0):
"""Change the host and port the request thinks it's using.
This method is useful for working with reverse HTTP proxies (e.g.
both Squid and Apache's mod_proxy can do this), when the address
the HTTP client is using is different than the one we're listening on.
For example, Apache may be listening on https://www.example.com, and then
forwarding requests to http://localhost:8080, but we don't want HTML produced
by Twisted to say 'http://localhost:8080', they should say 'https://www.example.com',
so we do::
request.setHost('www.example.com', 443, ssl=1)
This method is experimental.
"""
self._forceSSL = ssl
self.received_headers["host"] = host
self.host = address.IPv4Address("TCP", host, port)
def getClientIP(self):
if isinstance(self.client, address.IPv4Address):
return self.client.host
else:
return None
def isSecure(self):
if self._forceSSL:
return True
transport = getattr(getattr(self, 'channel', None), 'transport', None)
if interfaces.ISSLTransport(transport, None) is not None:
return True
return False
def _authorize(self):
# Authorization, (mostly) per the RFC
try:
authh = self.getHeader("Authorization")
if not authh:
self.user = self.password = ''
return
bas, upw = authh.split()
if bas.lower() != "basic":
raise ValueError
upw = base64.decodestring(upw)
self.user, self.password = upw.split(':', 1)
except (binascii.Error, ValueError):
self.user = self.password = ""
except:
log.err()
self.user = self.password = ""
def getUser(self):
try:
return self.user
except:
pass
self._authorize()
return self.user
def getPassword(self):
try:
return self.password
except:
pass
self._authorize()
return self.password
def getClient(self):
if self.client.type != 'TCP':
return None
host = self.client.host
try:
name, names, addresses = socket.gethostbyaddr(host)
except socket.error:
return host
names.insert(0, name)
for name in names:
if '.' in name:
return name
return names[0]
def connectionLost(self, reason):
"""connection was lost"""
pass
class HTTPChannel(basic.LineReceiver, policies.TimeoutMixin):
"""A receiver for HTTP requests."""
maxHeaders = 500 # max number of headers allowed per request
length = 0
persistent = 1
__header = ''
__first_line = 1
__content = None
# set in instances or subclasses
requestFactory = Request
_savedTimeOut = None
def __init__(self):
# the request queue
self.requests = []
def connectionMade(self):
self.setTimeout(self.timeOut)
def lineReceived(self, line):
self.resetTimeout()
if self.__first_line:
# if this connection is not persistent, drop any data which
# the client (illegally) sent after the last request.
if not self.persistent:
self.dataReceived = self.lineReceived = lambda *args: None
return
# IE sends an extraneous empty line (\r\n) after a POST request;
# eat up such a line, but only ONCE
if not line and self.__first_line == 1:
self.__first_line = 2
return
# create a new Request object
request = self.requestFactory(self, len(self.requests))
self.requests.append(request)
self.__first_line = 0
parts = line.split()
if len(parts) != 3:
self.transport.write("HTTP/1.1 400 Bad Request\r\n\r\n")
self.transport.loseConnection()
return
command, request, version = parts
self._command = command
self._path = request
self._version = version
elif line == '':
if self.__header:
self.headerReceived(self.__header)
self.__header = ''
self.allHeadersReceived()
if self.length == 0:
self.allContentReceived()
else:
self.setRawMode()
elif line[0] in ' \t':
self.__header = self.__header+'\n'+line
else:
if self.__header:
self.headerReceived(self.__header)
self.__header = line
def headerReceived(self, line):
"""Do pre-processing (for content-length) and store this header away.
"""
header, data = line.split(':', 1)
header = header.lower()
data = data.strip()
if header == 'content-length':
self.length = int(data)
reqHeaders = self.requests[-1].received_headers
reqHeaders[header] = data
if len(reqHeaders) > self.maxHeaders:
self.transport.write("HTTP/1.1 400 Bad Request\r\n\r\n")
self.transport.loseConnection()
def allContentReceived(self):
command = self._command
path = self._path
version = self._version
# reset ALL state variables, so we don't interfere with next request
self.length = 0
self._header = ''
self.__first_line = 1
del self._command, self._path, self._version
# Disable the idle timeout, in case this request takes a long
# time to finish generating output.
if self.timeOut:
self._savedTimeOut = self.setTimeout(None)
req = self.requests[-1]
req.requestReceived(command, path, version)
def rawDataReceived(self, data):
if len(data) < self.length:
self.requests[-1].handleContentChunk(data)
self.length = self.length - len(data)
else:
self.requests[-1].handleContentChunk(data[:self.length])
extraneous = data[self.length:]
self.allContentReceived()
self.setLineMode(extraneous)
def allHeadersReceived(self):
req = self.requests[-1]
req.parseCookies()
self.persistent = self.checkPersistence(req, self._version)
req.gotLength(self.length)
def checkPersistence(self, request, version):
"""Check if the channel should close or not."""
connection = request.getHeader('connection')
if connection:
tokens = map(str.lower, connection.split(' '))
else:
tokens = []
# HTTP 1.0 persistent connection support is currently disabled,
# since we need a way to disable pipelining. HTTP 1.0 can't do
# pipelining since we can't know in advance if we'll have a
# content-length header, if we don't have the header we need to close the
# connection. In HTTP 1.1 this is not an issue since we use chunked
# encoding if content-length is not available.
#if version == "HTTP/1.0":
# if 'keep-alive' in tokens:
# request.setHeader('connection', 'Keep-Alive')
# return 1
# else:
# return 0
if version == "HTTP/1.1":
if 'close' in tokens:
request.setHeader('connection', 'close')
return 0
else:
return 1
else:
return 0
def requestDone(self, request):
"""Called by first request in queue when it is done."""
if request != self.requests[0]: raise TypeError
del self.requests[0]
if self.persistent:
# notify next request it can start writing
if self.requests:
self.requests[0].noLongerQueued()
else:
if self._savedTimeOut:
self.setTimeout(self._savedTimeOut)
else:
self.transport.loseConnection()
def timeoutConnection(self):
log.msg("Timing out client: %s" % str(self.transport.getPeer()))
policies.TimeoutMixin.timeoutConnection(self)
def connectionLost(self, reason):
self.setTimeout(None)
for request in self.requests:
request.connectionLost(reason)
class HTTPFactory(protocol.ServerFactory):
"""Factory for HTTP server."""
protocol = HTTPChannel
logPath = None
timeOut = 60 * 60 * 12
def __init__(self, logPath=None, timeout=60*60*12):
if logPath is not None:
logPath = os.path.abspath(logPath)
self.logPath = logPath
self.timeOut = timeout
def buildProtocol(self, addr):
p = protocol.ServerFactory.buildProtocol(self, addr)
# timeOut needs to be on the Protocol instance cause
# TimeoutMixin expects it there
p.timeOut = self.timeOut
return p
def startFactory(self):
_logDateTimeStart()
if self.logPath:
self.logFile = self._openLogFile(self.logPath)
else:
self.logFile = log.logfile
def stopFactory(self):
if hasattr(self, "logFile"):
if self.logFile != log.logfile:
self.logFile.close()
del self.logFile
_logDateTimeStop()
def _openLogFile(self, path):
"""Override in subclasses, e.g. to use twisted.python.logfile."""
f = open(path, "a", 1)
return f
def _escape(self, s):
# pain in the ass. Return a string like python repr, but always
# escaped as if surrounding quotes were "".
r = repr(s)
if r[0] == "'":
return r[1:-1].replace('"', '\\"').replace("\\'", "'")
return r[1:-1]
def log(self, request):
"""Log a request's result to the logfile, by default in combined log format."""
if hasattr(self, "logFile"):
line = '%s - - %s "%s" %d %s "%s" "%s"\n' % (
request.getClientIP(),
# request.getUser() or "-", # the remote user is almost never important
_logDateTime,
'%s %s %s' % (self._escape(request.method),
self._escape(request.uri),
self._escape(request.clientproto)),
request.code,
request.sentLength or "-",
self._escape(request.getHeader("referer") or "-"),
self._escape(request.getHeader("user-agent") or "-"))
self.logFile.write(line) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/http.py | http.py |
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
#
"""HTTP client.
API Stability: stable
"""
import urlparse, os, types
from twisted.web import http
from twisted.internet import defer, protocol, reactor
from twisted.python import failure
from twisted.python.util import InsensitiveDict
from twisted.web import error
class PartialDownloadError(error.Error):
"""Page was only partially downloaded, we got disconnected in middle.
The bit that was downloaded is in the response attribute.
"""
class HTTPPageGetter(http.HTTPClient):
quietLoss = 0
followRedirect = 1
failed = 0
def connectionMade(self):
method = getattr(self.factory, 'method', 'GET')
self.sendCommand(method, self.factory.path)
self.sendHeader('Host', self.factory.headers.get("host", self.factory.host))
self.sendHeader('User-Agent', self.factory.agent)
if self.factory.cookies:
l=[]
for cookie, cookval in self.factory.cookies.items():
l.append('%s=%s' % (cookie, cookval))
self.sendHeader('Cookie', '; '.join(l))
data = getattr(self.factory, 'postdata', None)
if data is not None:
self.sendHeader("Content-Length", str(len(data)))
for (key, value) in self.factory.headers.items():
if key.lower() != "content-length":
# we calculated it on our own
self.sendHeader(key, value)
self.endHeaders()
self.headers = {}
if data is not None:
self.transport.write(data)
def handleHeader(self, key, value):
key = key.lower()
l = self.headers[key] = self.headers.get(key, [])
l.append(value)
def handleStatus(self, version, status, message):
self.version, self.status, self.message = version, status, message
self.factory.gotStatus(version, status, message)
def handleEndHeaders(self):
self.factory.gotHeaders(self.headers)
m = getattr(self, 'handleStatus_'+self.status, self.handleStatusDefault)
m()
def handleStatus_200(self):
pass
handleStatus_201 = lambda self: self.handleStatus_200()
handleStatus_202 = lambda self: self.handleStatus_200()
def handleStatusDefault(self):
self.failed = 1
def handleStatus_301(self):
l = self.headers.get('location')
if not l:
self.handleStatusDefault()
return
url = l[0]
if self.followRedirect:
scheme, host, port, path = \
_parse(url, defaultPort=self.transport.getPeer().port)
self.factory.setURL(url)
if self.factory.scheme == 'https':
from twisted.internet import ssl
contextFactory = ssl.ClientContextFactory()
reactor.connectSSL(self.factory.host, self.factory.port,
self.factory, contextFactory)
else:
reactor.connectTCP(self.factory.host, self.factory.port,
self.factory)
else:
self.handleStatusDefault()
self.factory.noPage(
failure.Failure(
error.PageRedirect(
self.status, self.message, location = url)))
self.quietLoss = 1
self.transport.loseConnection()
handleStatus_302 = lambda self: self.handleStatus_301()
def handleStatus_303(self):
self.factory.method = 'GET'
self.handleStatus_301()
def connectionLost(self, reason):
if not self.quietLoss:
http.HTTPClient.connectionLost(self, reason)
self.factory.noPage(reason)
def handleResponse(self, response):
if self.quietLoss:
return
if self.failed:
self.factory.noPage(
failure.Failure(
error.Error(
self.status, self.message, response)))
elif self.length != None and self.length != 0:
self.factory.noPage(failure.Failure(
PartialDownloadError(self.status, self.message, response)))
else:
self.factory.page(response)
# server might be stupid and not close connection. admittedly
# the fact we do only one request per connection is also
# stupid...
self.transport.loseConnection()
def timeout(self):
self.quietLoss = True
self.transport.loseConnection()
self.factory.noPage(defer.TimeoutError("Getting %s took longer than %s seconds." % (self.factory.url, self.factory.timeout)))
class HTTPPageDownloader(HTTPPageGetter):
transmittingPage = 0
def handleStatus_200(self, partialContent=0):
HTTPPageGetter.handleStatus_200(self)
self.transmittingPage = 1
self.factory.pageStart(partialContent)
def handleStatus_206(self):
self.handleStatus_200(partialContent=1)
def handleResponsePart(self, data):
if self.transmittingPage:
self.factory.pagePart(data)
def handleResponseEnd(self):
if self.transmittingPage:
self.factory.pageEnd()
self.transmittingPage = 0
if self.failed:
self.factory.noPage(
failure.Failure(
error.Error(
self.status, self.message, None)))
self.transport.loseConnection()
class HTTPClientFactory(protocol.ClientFactory):
"""Download a given URL.
@type deferred: Deferred
@ivar deferred: A Deferred that will fire when the content has
been retrieved. Once this is fired, the ivars `status', `version',
and `message' will be set.
@type status: str
@ivar status: The status of the response.
@type version: str
@ivar version: The version of the response.
@type message: str
@ivar message: The text message returned with the status.
@type response_headers: dict
@ivar response_headers: The headers that were specified in the
response from the server.
"""
protocol = HTTPPageGetter
url = None
scheme = None
host = ''
port = None
path = None
def __init__(self, url, method='GET', postdata=None, headers=None,
agent="Twisted PageGetter", timeout=0, cookies=None,
followRedirect=1):
self.protocol.followRedirect = followRedirect
self.timeout = timeout
self.agent = agent
if cookies is None:
cookies = {}
self.cookies = cookies
if headers is not None:
self.headers = InsensitiveDict(headers)
else:
self.headers = InsensitiveDict()
if postdata is not None:
self.headers.setdefault('Content-Length', len(postdata))
# just in case a broken http/1.1 decides to keep connection alive
self.headers.setdefault("connection", "close")
self.postdata = postdata
self.method = method
self.setURL(url)
self.waiting = 1
self.deferred = defer.Deferred()
self.response_headers = None
def __repr__(self):
return "<%s: %s>" % (self.__class__.__name__, self.url)
def setURL(self, url):
self.url = url
scheme, host, port, path = _parse(url)
if scheme and host:
self.scheme = scheme
self.host = host
self.port = port
self.path = path
def buildProtocol(self, addr):
p = protocol.ClientFactory.buildProtocol(self, addr)
if self.timeout:
timeoutCall = reactor.callLater(self.timeout, p.timeout)
self.deferred.addBoth(self._cancelTimeout, timeoutCall)
return p
def _cancelTimeout(self, result, timeoutCall):
if timeoutCall.active():
timeoutCall.cancel()
return result
def gotHeaders(self, headers):
self.response_headers = headers
if headers.has_key('set-cookie'):
for cookie in headers['set-cookie']:
cookparts = cookie.split(';')
cook = cookparts[0]
cook.lstrip()
k, v = cook.split('=', 1)
self.cookies[k.lstrip()] = v.lstrip()
def gotStatus(self, version, status, message):
self.version, self.status, self.message = version, status, message
def page(self, page):
if self.waiting:
self.waiting = 0
self.deferred.callback(page)
def noPage(self, reason):
if self.waiting:
self.waiting = 0
self.deferred.errback(reason)
def clientConnectionFailed(self, _, reason):
if self.waiting:
self.waiting = 0
self.deferred.errback(reason)
class HTTPDownloader(HTTPClientFactory):
"""Download to a file."""
protocol = HTTPPageDownloader
value = None
def __init__(self, url, fileOrName,
method='GET', postdata=None, headers=None,
agent="Twisted client", supportPartial=0):
self.requestedPartial = 0
if isinstance(fileOrName, types.StringTypes):
self.fileName = fileOrName
self.file = None
if supportPartial and os.path.exists(self.fileName):
fileLength = os.path.getsize(self.fileName)
if fileLength:
self.requestedPartial = fileLength
if headers == None:
headers = {}
headers["range"] = "bytes=%d-" % fileLength
else:
self.file = fileOrName
HTTPClientFactory.__init__(self, url, method=method, postdata=postdata, headers=headers, agent=agent)
self.deferred = defer.Deferred()
self.waiting = 1
def gotHeaders(self, headers):
if self.requestedPartial:
contentRange = headers.get("content-range", None)
if not contentRange:
# server doesn't support partial requests, oh well
self.requestedPartial = 0
return
start, end, realLength = http.parseContentRange(contentRange[0])
if start != self.requestedPartial:
# server is acting wierdly
self.requestedPartial = 0
def openFile(self, partialContent):
if partialContent:
file = open(self.fileName, 'rb+')
file.seek(0, 2)
else:
file = open(self.fileName, 'wb')
return file
def pageStart(self, partialContent):
"""Called on page download start.
@param partialContent: tells us if the download is partial download we requested.
"""
if partialContent and not self.requestedPartial:
raise ValueError, "we shouldn't get partial content response if we didn't want it!"
if self.waiting:
self.waiting = 0
try:
if not self.file:
self.file = self.openFile(partialContent)
except IOError:
#raise
self.deferred.errback(failure.Failure())
def pagePart(self, data):
if not self.file:
return
try:
self.file.write(data)
except IOError:
#raise
self.file = None
self.deferred.errback(failure.Failure())
def pageEnd(self):
if not self.file:
return
try:
self.file.close()
except IOError:
self.deferred.errback(failure.Failure())
return
self.deferred.callback(self.value)
def _parse(url, defaultPort=None):
url = url.strip()
parsed = urlparse.urlparse(url)
scheme = parsed[0]
path = urlparse.urlunparse(('','')+parsed[2:])
if defaultPort is None:
if scheme == 'https':
defaultPort = 443
else:
defaultPort = 80
host, port = parsed[1], defaultPort
if ':' in host:
host, port = host.split(':')
port = int(port)
if path == "":
path = "/"
return scheme, host, port, path
def getPage(url, contextFactory=None, *args, **kwargs):
"""Download a web page as a string.
Download a page. Return a deferred, which will callback with a
page (as a string) or errback with a description of the error.
See HTTPClientFactory to see what extra args can be passed.
"""
scheme, host, port, path = _parse(url)
factory = HTTPClientFactory(url, *args, **kwargs)
if scheme == 'https':
from twisted.internet import ssl
if contextFactory is None:
contextFactory = ssl.ClientContextFactory()
reactor.connectSSL(host, port, factory, contextFactory)
else:
reactor.connectTCP(host, port, factory)
return factory.deferred
def downloadPage(url, file, contextFactory=None, *args, **kwargs):
"""Download a web page to a file.
@param file: path to file on filesystem, or file-like object.
See HTTPDownloader to see what extra args can be passed.
"""
scheme, host, port, path = _parse(url)
factory = HTTPDownloader(url, file, *args, **kwargs)
if scheme == 'https':
from twisted.internet import ssl
if contextFactory is None:
contextFactory = ssl.ClientContextFactory()
reactor.connectSSL(host, port, factory, contextFactory)
else:
reactor.connectTCP(host, port, factory)
return factory.deferred | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/client.py | client.py |
# twisted imports
from twisted.internet import reactor, protocol
from twisted.web import resource, server, http
# system imports
import urlparse
class ProxyClient(http.HTTPClient):
"""Used by ProxyClientFactory to implement a simple web proxy."""
def __init__(self, command, rest, version, headers, data, father):
self.father = father
self.command = command
self.rest = rest
if headers.has_key("proxy-connection"):
del headers["proxy-connection"]
headers["connection"] = "close"
self.headers = headers
self.data = data
def connectionMade(self):
self.sendCommand(self.command, self.rest)
for header, value in self.headers.items():
self.sendHeader(header, value)
self.endHeaders()
self.transport.write(self.data)
def handleStatus(self, version, code, message):
self.father.transport.write("%s %s %s\r\n" % (version, code, message))
def handleHeader(self, key, value):
self.father.transport.write("%s: %s\r\n" % (key, value))
def handleEndHeaders(self):
self.father.transport.write("\r\n")
def handleResponsePart(self, buffer):
self.father.transport.write(buffer)
def handleResponseEnd(self):
self.transport.loseConnection()
self.father.channel.transport.loseConnection()
class ProxyClientFactory(protocol.ClientFactory):
"""Used by ProxyRequest to implement a simple web proxy."""
protocol = ProxyClient
def __init__(self, command, rest, version, headers, data, father):
self.father = father
self.command = command
self.rest = rest
self.headers = headers
self.data = data
self.version = version
def buildProtocol(self, addr):
return self.protocol(self.command, self.rest, self.version,
self.headers, self.data, self.father)
def clientConnectionFailed(self, connector, reason):
self.father.transport.write("HTTP/1.0 501 Gateway error\r\n")
self.father.transport.write("Content-Type: text/html\r\n")
self.father.transport.write("\r\n")
self.father.transport.write('''<H1>Could not connect</H1>''')
class ProxyRequest(http.Request):
"""Used by Proxy to implement a simple web proxy."""
protocols = {'http': ProxyClientFactory}
ports = {'http': 80}
def process(self):
parsed = urlparse.urlparse(self.uri)
protocol = parsed[0]
host = parsed[1]
port = self.ports[protocol]
if ':' in host:
host, port = host.split(':')
port = int(port)
rest = urlparse.urlunparse(('','')+parsed[2:])
if not rest:
rest = rest+'/'
class_ = self.protocols[protocol]
headers = self.getAllHeaders().copy()
if not headers.has_key('host'):
headers['host'] = host
self.content.seek(0, 0)
s = self.content.read()
clientFactory = class_(self.method, rest, self.clientproto, headers,
s, self)
reactor.connectTCP(host, port, clientFactory)
class Proxy(http.HTTPChannel):
"""This class implements a simple web proxy.
Since it inherits from twisted.protocols.http.HTTPChannel, to use it you
should do something like this::
from twisted.web import http
f = http.HTTPFactory()
f.protocol = Proxy
Make the HTTPFactory a listener on a port as per usual, and you have
a fully-functioning web proxy!
"""
requestFactory = ProxyRequest
class ReverseProxyRequest(http.Request):
"""Used by ReverseProxy to implement a simple reverse proxy."""
def process(self):
self.received_headers['host'] = self.factory.host
clientFactory = ProxyClientFactory(self.method, self.uri,
self.clientproto,
self.getAllHeaders(),
self.content.read(), self)
reactor.connectTCP(self.factory.host, self.factory.port,
clientFactory)
class ReverseProxy(http.HTTPChannel):
"""Implements a simple reverse proxy.
For details of usage, see the file examples/proxy.py"""
requestFactory = ReverseProxyRequest
class ReverseProxyResource(resource.Resource):
"""Resource that renders the results gotten from another server
Put this resource in the tree to cause everything below it to be relayed
to a different server.
"""
def __init__(self, host, port, path):
resource.Resource.__init__(self)
self.host = host
self.port = port
self.path = path
def getChild(self, path, request):
return ReverseProxyResource(self.host, self.port, self.path+'/'+path)
def render(self, request):
request.received_headers['host'] = self.host
request.content.seek(0, 0)
qs = urlparse.urlparse(request.uri)[4]
if qs:
rest = self.path + '?' + qs
else:
rest = self.path
clientFactory = ProxyClientFactory(request.method, rest,
request.clientproto,
request.getAllHeaders(),
request.content.read(),
request)
reactor.connectTCP(self.host, self.port, clientFactory)
return server.NOT_DONE_YET | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/proxy.py | proxy.py |
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
"""Distributed web servers.
This is going to have to be refactored so that argument parsing is done
by each subprocess and not by the main web server (i.e. GET, POST etc.).
"""
# System Imports
import types, os, copy, string, cStringIO
if (os.sys.platform != 'win32') and (os.name != 'java'):
import pwd
# Twisted Imports
from twisted.spread import pb
from twisted.web import http
from twisted.python import log
from twisted.persisted import styles
from twisted.web.woven import page
from twisted.internet import address, reactor
# Sibling Imports
import resource
import server
import error
import html
import static
from server import NOT_DONE_YET
class _ReferenceableProducerWrapper(pb.Referenceable):
def __init__(self, producer):
self.producer = producer
def remote_resumeProducing(self):
self.producer.resumeProducing()
def remote_pauseProducing(self):
self.producer.pauseProducing()
def remote_stopProducing(self):
self.producer.stopProducing()
class Request(pb.RemoteCopy, server.Request):
def setCopyableState(self, state):
for k in 'host', 'client':
tup = state[k]
addrdesc = {'INET': 'TCP', 'UNIX': 'UNIX'}[tup[0]]
addr = {'TCP': lambda: address.IPv4Address(addrdesc,
tup[1], tup[2],
_bwHack='INET'),
'UNIX': lambda: address.UNIXAddress(tup[1])}[addrdesc]()
state[k] = addr
pb.RemoteCopy.setCopyableState(self, state)
# Emulate the local request interface --
self.content = cStringIO.StringIO(self.content_data)
self.write = self.remote.remoteMethod('write')
self.finish = self.remote.remoteMethod('finish')
self.setHeader = self.remote.remoteMethod('setHeader')
self.addCookie = self.remote.remoteMethod('addCookie')
self.setETag = self.remote.remoteMethod('setETag')
self.setResponseCode = self.remote.remoteMethod('setResponseCode')
self.setLastModified = self.remote.remoteMethod('setLastModified')
def registerProducer(self, producer, streaming):
self.remote.callRemote("registerProducer",
_ReferenceableProducerWrapper(producer),
streaming).addErrback(self.fail)
def unregisterProducer(self):
self.remote.callRemote("unregisterProducer").addErrback(self.fail)
def fail(self, failure):
log.err(failure)
pb.setCopierForClass(server.Request, Request)
class Issue:
def __init__(self, request):
self.request = request
def finished(self, result):
if result != NOT_DONE_YET:
assert isinstance(result, types.StringType),\
"return value not a string"
self.request.write(result)
self.request.finish()
def failed(self, failure):
#XXX: Argh. FIXME.
failure = str(failure)
self.request.write(
error.ErrorPage(http.INTERNAL_SERVER_ERROR,
"Server Connection Lost",
"Connection to distributed server lost:" +
html.PRE(failure)).
render(self.request))
self.request.finish()
log.msg(failure)
class ResourceSubscription(resource.Resource):
isLeaf = 1
waiting = 0
def __init__(self, host, port):
resource.Resource.__init__(self)
self.host = host
self.port = port
self.pending = []
self.publisher = None
def __getstate__(self):
"""Get persistent state for this ResourceSubscription.
"""
# When I unserialize,
state = copy.copy(self.__dict__)
# Publisher won't be connected...
state['publisher'] = None
# I won't be making a connection
state['waiting'] = 0
# There will be no pending requests.
state['pending'] = []
return state
def connected(self, publisher):
"""I've connected to a publisher; I'll now send all my requests.
"""
log.msg('connected to publisher')
publisher.broker.notifyOnDisconnect(self.booted)
self.publisher = publisher
self.waiting = 0
for request in self.pending:
self.render(request)
self.pending = []
def notConnected(self, msg):
"""I can't connect to a publisher; I'll now reply to all pending
requests.
"""
log.msg("could not connect to distributed web service: %s" % msg)
self.waiting = 0
self.publisher = None
for request in self.pending:
request.write("Unable to connect to distributed server.")
request.finish()
self.pending = []
def booted(self):
self.notConnected("connection dropped")
def render(self, request):
"""Render this request, from my server.
This will always be asynchronous, and therefore return NOT_DONE_YET.
It spins off a request to the pb client, and either adds it to the list
of pending issues or requests it immediately, depending on if the
client is already connected.
"""
if not self.publisher:
self.pending.append(request)
if not self.waiting:
self.waiting = 1
bf = pb.PBClientFactory()
timeout = 10
if self.host == "unix":
reactor.connectUNIX(self.port, bf, timeout)
else:
reactor.connectTCP(self.host, self.port, bf, timeout)
d = bf.getRootObject()
d.addCallbacks(self.connected, self.notConnected)
else:
i = Issue(request)
self.publisher.callRemote('request', request).addCallbacks(i.finished, i.failed)
return NOT_DONE_YET
class ResourcePublisher(pb.Root, styles.Versioned):
def __init__(self, site):
self.site = site
persistenceVersion = 2
def upgradeToVersion2(self):
self.application.authorizer.removeIdentity("web")
del self.application.services[self.serviceName]
del self.serviceName
del self.application
del self.perspectiveName
def getPerspectiveNamed(self, name):
return self
def remote_request(self, request):
res = self.site.getResourceFor(request)
log.msg( request )
return res.render(request)
class UserDirectory(page.Page):
userDirName = 'public_html'
userSocketName = '.twistd-web-pb'
template = """
<html>
<head>
<title>twisted.web.distrib.UserDirectory</title>
<style>
a
{
font-family: Lucida, Verdana, Helvetica, Arial, sans-serif;
color: #369;
text-decoration: none;
}
th
{
font-family: Lucida, Verdana, Helvetica, Arial, sans-serif;
font-weight: bold;
text-decoration: none;
text-align: left;
}
pre, code
{
font-family: "Courier New", Courier, monospace;
}
p, body, td, ol, ul, menu, blockquote, div
{
font-family: Lucida, Verdana, Helvetica, Arial, sans-serif;
color: #000;
}
</style>
<base view="Attributes" model="base" />
</head>
<body>
<h1>twisted.web.distrib.UserDirectory</h1>
<ul view="List" model="directory">
<li pattern="listItem"><a view="Link" /> </li>
</ul>
</body>
</html>
"""
def wmfactory_base(self, request):
return {'href':request.prePathURL()}
def wmfactory_directory(self, request):
m = []
for user in pwd.getpwall():
pw_name, pw_passwd, pw_uid, pw_gid, pw_gecos, pw_dir, pw_shell \
= user
realname = string.split(pw_gecos,',')[0]
if not realname:
realname = pw_name
if os.path.exists(os.path.join(pw_dir, self.userDirName)):
m.append({
'href':'%s/'%pw_name,
'text':'%s (file)'%realname
})
twistdsock = os.path.join(pw_dir, self.userSocketName)
if os.path.exists(twistdsock):
linknm = '%s.twistd' % pw_name
m.append({
'href':'%s/'%linknm,
'text':'%s (twistd)'%realname})
return m
def getChild(self, name, request):
if name == '':
return self
td = '.twistd'
if name[-len(td):] == td:
username = name[:-len(td)]
sub = 1
else:
username = name
sub = 0
try:
pw_name, pw_passwd, pw_uid, pw_gid, pw_gecos, pw_dir, pw_shell \
= pwd.getpwnam(username)
except KeyError:
return error.NoResource()
if sub:
twistdsock = os.path.join(pw_dir, self.userSocketName)
rs = ResourceSubscription('unix',twistdsock)
self.putChild(name, rs)
return rs
else:
path = os.path.join(pw_dir, self.userDirName)
if not os.path.exists(path):
return error.NoResource()
return static.File(path) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/distrib.py | distrib.py |
# System Imports
import string
import os
import sys
import urllib
# Twisted Imports
from twisted.web import http
from twisted.internet import reactor, protocol
from twisted.spread import pb
from twisted.python import log, filepath
# Sibling Imports
import server
import error
import html
import resource
import static
from server import NOT_DONE_YET
class CGIDirectory(resource.Resource, filepath.FilePath):
def __init__(self, pathname):
resource.Resource.__init__(self)
filepath.FilePath.__init__(self, pathname)
def getChild(self, path, request):
fnp = self.child(path)
if not fnp.exists():
return static.File.childNotFound
elif fnp.isdir():
return CGIDirectory(fnp.path)
else:
return CGIScript(fnp.path)
return error.NoResource()
def render(self, request):
return error.NoResource("CGI directories do not support directory listing.").render(request)
class CGIScript(resource.Resource):
"""I represent a CGI script.
My implementation is complex due to the fact that it requires asynchronous
IPC with an external process with an unpleasant protocol.
"""
isLeaf = 1
def __init__(self, filename, registry=None):
"""Initialize, with the name of a CGI script file.
"""
self.filename = filename
def render(self, request):
"""Do various things to conform to the CGI specification.
I will set up the usual slew of environment variables, then spin off a
process.
"""
script_name = "/"+string.join(request.prepath, '/')
python_path = string.join(sys.path, os.pathsep)
serverName = string.split(request.getRequestHostname(), ':')[0]
env = {"SERVER_SOFTWARE": server.version,
"SERVER_NAME": serverName,
"GATEWAY_INTERFACE": "CGI/1.1",
"SERVER_PROTOCOL": request.clientproto,
"SERVER_PORT": str(request.getHost().port),
"REQUEST_METHOD": request.method,
"SCRIPT_NAME": script_name, # XXX
"SCRIPT_FILENAME": self.filename,
"REQUEST_URI": request.uri,
}
client = request.getClient()
if client is not None:
env['REMOTE_HOST'] = client
ip = request.getClientIP()
if ip is not None:
env['REMOTE_ADDR'] = ip
pp = request.postpath
if pp:
env["PATH_INFO"] = "/"+string.join(pp, '/')
if hasattr(request, "content"):
# request.content is either a StringIO or a TemporaryFile, and
# the file pointer is sitting at the beginning (seek(0,0))
request.content.seek(0,2)
length = request.content.tell()
request.content.seek(0,0)
env['CONTENT_LENGTH'] = str(length)
qindex = string.find(request.uri, '?')
if qindex != -1:
qs = env['QUERY_STRING'] = request.uri[qindex+1:]
if '=' in qs:
qargs = []
else:
qargs = [urllib.unquote(x) for x in qs.split('+')]
else:
env['QUERY_STRING'] = ''
qargs = []
# Propogate HTTP headers
for title, header in request.getAllHeaders().items():
envname = string.upper(string.replace(title, '-', '_'))
if title not in ('content-type', 'content-length'):
envname = "HTTP_" + envname
env[envname] = header
# Propogate our environment
for key, value in os.environ.items():
if not env.has_key(key):
env[key] = value
# And they're off!
self.runProcess(env, request, qargs)
return NOT_DONE_YET
def runProcess(self, env, request, qargs=[]):
p = CGIProcessProtocol(request)
reactor.spawnProcess(p, self.filename, [self.filename]+qargs, env, os.path.dirname(self.filename))
class FilteredScript(CGIScript):
"""I am a special version of a CGI script, that uses a specific executable.
This is useful for interfacing with other scripting languages that adhere
to the CGI standard (cf. PHPScript). My 'filter' attribute specifies what
executable to run, and my 'filename' init parameter describes which script
to pass to the first argument of that script.
"""
filter = '/usr/bin/cat'
def runProcess(self, env, request, qargs=[]):
p = CGIProcessProtocol(request)
reactor.spawnProcess(p, self.filter, [self.filter, self.filename]+qargs, env, os.path.dirname(self.filename))
class PHP3Script(FilteredScript):
"""I am a FilteredScript that uses the default PHP3 command on most systems.
"""
filter = '/usr/bin/php3'
class PHPScript(FilteredScript):
"""I am a FilteredScript that uses the PHP command on most systems.
Sometimes, php wants the path to itself as argv[0]. This is that time.
"""
filter = '/usr/bin/php4'
class CGIProcessProtocol(protocol.ProcessProtocol, pb.Viewable):
handling_headers = 1
headers_written = 0
headertext = ''
errortext = ''
# Remotely relay producer interface.
def view_resumeProducing(self, issuer):
self.resumeProducing()
def view_pauseProducing(self, issuer):
self.pauseProducing()
def view_stopProducing(self, issuer):
self.stopProducing()
def resumeProducing(self):
self.transport.resumeProducing()
def pauseProducing(self):
self.transport.pauseProducing()
def stopProducing(self):
self.transport.loseConnection()
def __init__(self, request):
self.request = request
def connectionMade(self):
self.request.registerProducer(self, 1)
self.request.content.seek(0, 0)
content = self.request.content.read()
if content:
self.transport.write(content)
self.transport.closeStdin()
def errReceived(self, error):
self.errortext = self.errortext + error
def outReceived(self, output):
"""
Handle a chunk of input
"""
# First, make sure that the headers from the script are sorted
# out (we'll want to do some parsing on these later.)
if self.handling_headers:
text = self.headertext + output
headerEnds = []
for delimiter in '\n\n','\r\n\r\n','\r\r', '\n\r\n':
headerend = string.find(text,delimiter)
if headerend != -1:
headerEnds.append((headerend, delimiter))
if headerEnds:
headerEnds.sort()
headerend, delimiter = headerEnds[0]
self.headertext = text[:headerend]
# This is a final version of the header text.
linebreak = delimiter[:len(delimiter)/2]
headers = string.split(self.headertext, linebreak)
for header in headers:
br = string.find(header,': ')
if br == -1:
log.msg( 'ignoring malformed CGI header: %s' % header )
else:
headerName = string.lower(header[:br])
headerText = header[br+2:]
if headerName == 'location':
self.request.setResponseCode(http.FOUND)
if headerName == 'status':
try:
statusNum = int(headerText[:3]) #"XXX <description>" sometimes happens.
except:
log.msg( "malformed status header" )
else:
self.request.setResponseCode(statusNum)
else:
self.request.setHeader(headerName,headerText)
output = text[headerend+len(delimiter):]
self.handling_headers = 0
if self.handling_headers:
self.headertext = text
if not self.handling_headers:
self.request.write(output)
def processEnded(self, reason):
if reason.value.exitCode != 0:
log.msg("CGI %s exited with exit code %s" %
(self.request.uri, reason.value.exitCode))
if self.errortext:
log.msg("Errors from CGI %s: %s" % (self.request.uri, self.errortext))
if self.handling_headers:
log.msg("Premature end of headers in %s: %s" % (self.request.uri, self.headertext))
self.request.write(
error.ErrorPage(http.INTERNAL_SERVER_ERROR,
"CGI Script Error",
"Premature end of script headers.").render(self.request))
self.request.unregisterProducer()
self.request.finish() | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/twcgi.py | twcgi.py |
from __future__ import nested_scopes
# System Imports
import os, stat, string
import cStringIO
import traceback
import warnings
import types
StringIO = cStringIO
del cStringIO
import urllib
# Sibling Imports
from twisted.web import server
from twisted.web import error
from twisted.web import resource
from twisted.web.util import redirectTo
# Twisted Imports
from twisted.web import http
from twisted.python import threadable, log, components, failure, filepath
from twisted.internet import abstract, interfaces, defer
from twisted.spread import pb
from twisted.persisted import styles
from twisted.python.util import InsensitiveDict
from twisted.python.runtime import platformType
dangerousPathError = error.NoResource("Invalid request URL.")
def isDangerous(path):
return path == '..' or '/' in path or os.sep in path
class Data(resource.Resource):
"""
This is a static, in-memory resource.
"""
def __init__(self, data, type):
resource.Resource.__init__(self)
self.data = data
self.type = type
def render(self, request):
request.setHeader("content-type", self.type)
request.setHeader("content-length", str(len(self.data)))
if request.method == "HEAD":
return ''
return self.data
def addSlash(request):
qs = ''
qindex = string.find(request.uri, '?')
if qindex != -1:
qs = request.uri[qindex:]
return "http%s://%s%s/%s" % (
request.isSecure() and 's' or '',
request.getHeader("host"),
(string.split(request.uri,'?')[0]),
qs)
class Redirect(resource.Resource):
def __init__(self, request):
resource.Resource.__init__(self)
self.url = addSlash(request)
def render(self, request):
return redirectTo(self.url, request)
class Registry(components.Componentized, styles.Versioned):
"""
I am a Componentized object that will be made available to internal Twisted
file-based dynamic web content such as .rpy and .epy scripts.
"""
def __init__(self):
components.Componentized.__init__(self)
self._pathCache = {}
persistenceVersion = 1
def upgradeToVersion1(self):
self._pathCache = {}
def cachePath(self, path, rsrc):
self._pathCache[path] = rsrc
def getCachedPath(self, path):
return self._pathCache.get(path)
def loadMimeTypes(mimetype_locations=['/etc/mime.types']):
"""
Multiple file locations containing mime-types can be passed as a list.
The files will be sourced in that order, overriding mime-types from the
files sourced beforehand, but only if a new entry explicitly overrides
the current entry.
"""
import mimetypes
# Grab Python's built-in mimetypes dictionary.
contentTypes = mimetypes.types_map
# Update Python's semi-erroneous dictionary with a few of the
# usual suspects.
contentTypes.update(
{
'.conf': 'text/plain',
'.diff': 'text/plain',
'.exe': 'application/x-executable',
'.flac': 'audio/x-flac',
'.java': 'text/plain',
'.ogg': 'application/ogg',
'.oz': 'text/x-oz',
'.swf': 'application/x-shockwave-flash',
'.tgz': 'application/x-gtar',
'.wml': 'text/vnd.wap.wml',
'.xul': 'application/vnd.mozilla.xul+xml',
'.py': 'text/plain',
'.patch': 'text/plain',
}
)
# Users can override these mime-types by loading them out configuration
# files (this defaults to ['/etc/mime.types']).
for location in mimetype_locations:
if os.path.exists(location):
more = mimetypes.read_mime_types(location)
if more is not None:
contentTypes.update(more)
return contentTypes
def getTypeAndEncoding(filename, types, encodings, defaultType):
p, ext = os.path.splitext(filename)
ext = ext.lower()
if encodings.has_key(ext):
enc = encodings[ext]
ext = os.path.splitext(p)[1].lower()
else:
enc = None
type = types.get(ext, defaultType)
return type, enc
class File(resource.Resource, styles.Versioned, filepath.FilePath):
"""
File is a resource that represents a plain non-interpreted file
(although it can look for an extension like .rpy or .cgi and hand the
file to a processor for interpretation if you wish). Its constructor
takes a file path.
Alternatively, you can give a directory path to the constructor. In this
case the resource will represent that directory, and its children will
be files underneath that directory. This provides access to an entire
filesystem tree with a single Resource.
If you map the URL 'http://server/FILE' to a resource created as
File('/tmp'), then http://server/FILE/ will return an HTML-formatted
listing of the /tmp/ directory, and http://server/FILE/foo/bar.html will
return the contents of /tmp/foo/bar.html .
@cvar childNotFound: L{Resource} used to render 404 Not Found error pages.
"""
contentTypes = loadMimeTypes()
contentEncodings = {
".gz" : "gzip",
".bz2": "bzip2"
}
processors = {}
indexNames = ["index", "index.html", "index.htm", "index.trp", "index.rpy"]
type = None
### Versioning
persistenceVersion = 6
def upgradeToVersion6(self):
self.ignoredExts = []
if self.allowExt:
self.ignoreExt("*")
del self.allowExt
def upgradeToVersion5(self):
if not isinstance(self.registry, Registry):
self.registry = Registry()
def upgradeToVersion4(self):
if not hasattr(self, 'registry'):
self.registry = {}
def upgradeToVersion3(self):
if not hasattr(self, 'allowExt'):
self.allowExt = 0
def upgradeToVersion2(self):
self.defaultType = "text/html"
def upgradeToVersion1(self):
if hasattr(self, 'indexName'):
self.indexNames = [self.indexName]
del self.indexName
def __init__(self, path, defaultType="text/html", ignoredExts=(), registry=None, allowExt=0):
"""Create a file with the given path.
"""
resource.Resource.__init__(self)
filepath.FilePath.__init__(self, path)
# Remove the dots from the path to split
self.defaultType = defaultType
if ignoredExts in (0, 1) or allowExt:
warnings.warn("ignoredExts should receive a list, not a boolean")
if ignoredExts or allowExt:
self.ignoredExts = ['*']
else:
self.ignoredExts = []
else:
self.ignoredExts = list(ignoredExts)
self.registry = registry or Registry()
def ignoreExt(self, ext):
"""Ignore the given extension.
Serve file.ext if file is requested
"""
self.ignoredExts.append(ext)
childNotFound = error.NoResource("File not found.")
def directoryListing(self):
from twisted.web.woven import dirlist
return dirlist.DirectoryLister(self.path,
self.listNames(),
self.contentTypes,
self.contentEncodings,
self.defaultType)
def getChild(self, path, request):
"""See twisted.web.Resource.getChild.
"""
self.restat()
if not self.isdir():
return self.childNotFound
if path:
fpath = self.child(path)
else:
fpath = self.childSearchPreauth(*self.indexNames)
if fpath is None:
return self.directoryListing()
if not fpath.exists():
fpath = fpath.siblingExtensionSearch(*self.ignoredExts)
if fpath is None:
return self.childNotFound
if platformType == "win32":
# don't want .RPY to be different than .rpy, since that would allow
# source disclosure.
processor = InsensitiveDict(self.processors).get(fpath.splitext()[1])
else:
processor = self.processors.get(fpath.splitext()[1])
if processor:
return resource.IResource(processor(fpath.path, self.registry))
return self.createSimilarFile(fpath.path)
# methods to allow subclasses to e.g. decrypt files on the fly:
def openForReading(self):
"""Open a file and return it."""
return self.open()
def getFileSize(self):
"""Return file size."""
return self.getsize()
def render(self, request):
"""You know what you doing."""
self.restat()
if self.type is None:
self.type, self.encoding = getTypeAndEncoding(self.basename(),
self.contentTypes,
self.contentEncodings,
self.defaultType)
if not self.exists():
return self.childNotFound.render(request)
if self.isdir():
return self.redirect(request)
#for content-length
fsize = size = self.getFileSize()
# request.setHeader('accept-ranges','bytes')
if self.type:
request.setHeader('content-type', self.type)
if self.encoding:
request.setHeader('content-encoding', self.encoding)
try:
f = self.openForReading()
except IOError, e:
import errno
if e[0] == errno.EACCES:
return error.ForbiddenResource().render(request)
else:
raise
if request.setLastModified(self.getmtime()) is http.CACHED:
return ''
# Commented out because it's totally broken. --jknight 11/29/04
# try:
# range = request.getHeader('range')
#
# if range is not None:
# # This is a request for partial data...
# bytesrange = string.split(range, '=')
# assert bytesrange[0] == 'bytes',\
# "Syntactically invalid http range header!"
# start, end = string.split(bytesrange[1],'-')
# if start:
# f.seek(int(start))
# if end:
# end = int(end)
# size = end
# else:
# end = size
# request.setResponseCode(http.PARTIAL_CONTENT)
# request.setHeader('content-range',"bytes %s-%s/%s " % (
# str(start), str(end), str(size)))
# #content-length should be the actual size of the stuff we're
# #sending, not the full size of the on-server entity.
# fsize = end - int(start)
#
# request.setHeader('content-length', str(fsize))
# except:
# traceback.print_exc(file=log.logfile)
request.setHeader('content-length', str(fsize))
if request.method == 'HEAD':
return ''
# return data
FileTransfer(f, size, request)
# and make sure the connection doesn't get closed
return server.NOT_DONE_YET
def redirect(self, request):
return redirectTo(addSlash(request), request)
def listNames(self):
if not self.isdir():
return []
directory = self.listdir()
directory.sort()
return directory
def listEntities(self):
return map(lambda fileName, self=self: self.createSimilarFile(os.path.join(self.path, fileName)), self.listNames())
def createPickleChild(self, name, child):
if not os.path.isdir(self.path):
resource.Resource.putChild(self, name, child)
# xxx use a file-extension-to-save-function dictionary instead
if type(child) == type(""):
fl = open(os.path.join(self.path, name), 'wb')
fl.write(child)
else:
if '.' not in name:
name = name + '.trp'
fl = open(os.path.join(self.path, name), 'wb')
from pickle import Pickler
pk = Pickler(fl)
pk.dump(child)
fl.close()
def createSimilarFile(self, path):
f = self.__class__(path, self.defaultType, self.ignoredExts, self.registry)
# refactoring by steps, here - constructor should almost certainly take these
f.processors = self.processors
f.indexNames = self.indexNames[:]
f.childNotFound = self.childNotFound
return f
class FileTransfer(pb.Viewable):
"""
A class to represent the transfer of a file over the network.
"""
request = None
def __init__(self, file, size, request):
self.file = file
self.size = size
self.request = request
self.written = self.file.tell()
request.registerProducer(self, 0)
def resumeProducing(self):
if not self.request:
return
data = self.file.read(min(abstract.FileDescriptor.bufferSize, self.size - self.written))
if data:
self.written += len(data)
# this .write will spin the reactor, calling .doWrite and then
# .resumeProducing again, so be prepared for a re-entrant call
self.request.write(data)
if self.request and self.file.tell() == self.size:
self.request.unregisterProducer()
self.request.finish()
self.request = None
def pauseProducing(self):
pass
def stopProducing(self):
self.file.close()
self.request = None
# Remotely relay producer interface.
def view_resumeProducing(self, issuer):
self.resumeProducing()
def view_pauseProducing(self, issuer):
self.pauseProducing()
def view_stopProducing(self, issuer):
self.stopProducing()
synchronized = ['resumeProducing', 'stopProducing']
threadable.synchronize(FileTransfer)
"""I contain AsIsProcessor, which serves files 'As Is'
Inspired by Apache's mod_asis
"""
class ASISProcessor(resource.Resource):
def __init__(self, path, registry=None):
resource.Resource.__init__(self)
self.path = path
self.registry = registry or Registry()
def render(self, request):
request.startedWriting = 1
res = File(self.path, registry=self.registry)
return res.render(request) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/static.py | static.py |
import server
import resource
import html
import error
try:
import cStringIO as StringIO
except ImportError:
import StringIO
from twisted.web import http
from twisted import copyright
import traceback
import os
from twisted.web import resource
from twisted.web import static
rpyNoResource = """<p>You forgot to assign to the variable "resource" in your script. For example:</p>
<pre>
# MyCoolWebApp.rpy
import mygreatresource
resource = mygreatresource.MyGreatResource()
</pre>
"""
class AlreadyCached(Exception):
"""This exception is raised when a path has already been cached.
"""
class CacheScanner:
def __init__(self, path, registry):
self.path = path
self.registry = registry
self.doCache = 0
def cache(self):
c = self.registry.getCachedPath(self.path)
if c is not None:
raise AlreadyCached(c)
self.recache()
def recache(self):
self.doCache = 1
noRsrc = error.ErrorPage(500, "Whoops! Internal Error", rpyNoResource)
def ResourceScript(path, registry):
"""
I am a normal py file which must define a 'resource' global, which should
be an instance of (a subclass of) web.resource.Resource; it will be
renderred.
"""
cs = CacheScanner(path, registry)
glob = {'__file__': path,
'resource': noRsrc,
'registry': registry,
'cache': cs.cache,
'recache': cs.recache}
try:
execfile(path, glob, glob)
except AlreadyCached, ac:
return ac.args[0]
rsrc = glob['resource']
if cs.doCache and rsrc is not noRsrc:
registry.cachePath(path, rsrc)
return rsrc
def ResourceTemplate(path, registry):
from quixote import ptl_compile
glob = {'__file__': path,
'resource': error.ErrorPage(500, "Whoops! Internal Error",
rpyNoResource),
'registry': registry}
e = ptl_compile.compile_template(open(path), path)
exec e in glob
return glob['resource']
class ResourceScriptWrapper(resource.Resource):
def __init__(self, path, registry=None):
resource.Resource.__init__(self)
self.path = path
self.registry = registry or static.Registry()
def render(self, request):
res = ResourceScript(self.path, self.registry)
return res.render(request)
def getChildWithDefault(self, path, request):
res = ResourceScript(self.path, self.registry)
return res.getChildWithDefault(path, request)
class ResourceScriptDirectory(resource.Resource):
def __init__(self, pathname, registry=None):
resource.Resource.__init__(self)
self.path = pathname
self.registry = registry or static.Registry()
def getChild(self, path, request):
fn = os.path.join(self.path, path)
if os.path.isdir(fn):
return ResourceScriptDirectory(fn, self.registry)
if os.path.exists(fn):
return ResourceScript(fn, self.registry)
return error.NoResource()
def render(self, request):
return error.NoResource().render(request)
class PythonScript(resource.Resource):
"""I am an extremely simple dynamic resource; an embedded python script.
This will execute a file (usually of the extension '.epy') as Python code,
internal to the webserver.
"""
isLeaf = 1
def __init__(self, filename, registry):
"""Initialize me with a script name.
"""
self.filename = filename
self.registry = registry
def render(self, request):
"""Render me to a web client.
Load my file, execute it in a special namespace (with 'request' and
'__file__' global vars) and finish the request. Output to the web-page
will NOT be handled with print - standard output goes to the log - but
with request.write.
"""
request.setHeader("x-powered-by","Twisted/%s" % copyright.version)
namespace = {'request': request,
'__file__': self.filename,
'registry': self.registry}
try:
execfile(self.filename, namespace, namespace)
except IOError, e:
if e.errno == 2: #file not found
request.setResponseCode(http.NOT_FOUND)
request.write(error.NoResource("File not found.").render(request))
except:
io = StringIO.StringIO()
traceback.print_exc(file=io)
request.write(html.PRE(io.getvalue()))
request.finish()
return server.NOT_DONE_YET | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/script.py | script.py |
# System Imports
import string, traceback
from cStringIO import StringIO
from twisted.python import log
# Sibling Imports
import error
import html
import resource
import widgets
from server import NOT_DONE_YET
import warnings
warnings.warn("Please use twisted.web.woven.guard", DeprecationWarning, 2)
class _Detacher:
"""Detach a web session from an attached perspective.
This will happen when the session expires.
"""
def __init__(self, session, identity, perspective):
self.session = session
self.identity = identity
self.perspective = perspective
session.notifyOnExpire(self.detach)
def detach(self):
self.perspective.detached(self.session, self.identity)
del self.session
del self.identity
del self.perspective
class AuthForm(widgets.Form):
formFields = [
['string','Identity','username',''],
['password','Password','password',''],
['string','Perspective','perspective','']
]
formAcceptExtraArgs = 1
def __init__(self, reqauth, sessionIdentity=None, sessionPerspective=None):
"""Initialize, specifying various options.
@param reqauth: a web.resource.Resource instance, indicating which
resource a user will be logging into with this form; this must
specify a serviceName attribute which indicates the name of the
service from which perspectives will be requested.
@param sessionIdentity: if specified, the name of the attribute on
the user's session to set for the identity they get from logging
in to this form.
@param sessionPerspective: if specified, the name of the attribute on
the user's session to set for the perspective they get from
logging in to this form.
"""
self.reqauth = reqauth
self.sessionPerspective = sessionPerspective
self.sessionIdentity = sessionIdentity
def gotPerspective(self, perspective, request, ident):
# TODO: fix this...
resKey = string.join(['AUTH',self.reqauth.service.serviceName], '_')
sess = request.getSession()
setattr(sess, resKey, perspective)
if self.sessionPerspective:
setattr(sess, self.sessionPerspective, perspective)
if self.sessionIdentity:
setattr(sess, self.sessionIdentity, ident)
p = perspective.attached(sess, ident)
_Detacher(sess, ident, p)
return self.reqauth.reallyRender(request)
def didntGetPerspective(self, error, request):
log.msg('Password not verified! Error: %s' % error)
io = StringIO()
io.write(self.formatError("Login incorrect."))
self.format(self.getFormFields(request), io.write, request)
return [io.getvalue()]
def gotIdentity(self, ident, password, request, perspectiveName):
pwrq = ident.verifyPlainPassword(password)
pwrq.addCallback(self.passwordIsOk, ident, password,
request, perspectiveName)
pwrq.addErrback(self.didntGetPerspective, request)
pwrq.needsHeader = 1
return [pwrq]
def passwordIsOk(self, msg, ident, password, request, perspectiveName):
ret = ident.requestPerspectiveForKey(self.reqauth.service.serviceName,
perspectiveName).addCallbacks(
self.gotPerspective, self.didntGetPerspective,
callbackArgs=(request,ident),
errbackArgs=(request,))
ret.needsHeader = 1
return [ret]
def didntGetIdentity(self, unauth, request):
io = StringIO()
io.write(self.formatError("Login incorrect."))
self.format(self.getFormFields(request), io.write, request)
return io.getvalue()
def process(self, write, request, submit, username, password, perspective):
"""Process the form results.
"""
# must be done before page is displayed so cookie can get set!
request.getSession()
# this site must be tagged with an application.
idrq = self.reqauth.service.authorizer.getIdentityRequest(username)
idrq.needsHeader = 1
idrq.addCallbacks(self.gotIdentity, self.didntGetIdentity,
callbackArgs=(password,request,perspective or username),
errbackArgs=(request,))
return [idrq]
class AuthPage(widgets.Page):
template = '''
<html><head><title>Authorization Required</title></head>
<body>
<center>
%%%%authForm%%%%
</center>
</body>
</html>
'''
authForm = None
def __init__(self, reqauth, sessionIdentity=None, sessionPerspective=None):
widgets.Page.__init__(self)
self.authForm = AuthForm(reqauth, sessionPerspective, sessionIdentity)
class WidgetGuard(widgets.Widget):
def __init__(self, wid, service,
sessionIdentity=None,
sessionPerspective=None):
self.wid = wid
self.service = service
self.sessionPerspective = sessionPerspective
self.sessionIdentity = sessionIdentity
def reallyRender(self, request):
return widgets.possiblyDeferWidget(self.wid, request)
def display(self, request):
session = request.getSession()
resKey = string.join(['AUTH',self.service.serviceName], '_')
if hasattr(session, resKey):
return self.wid.display(request)
else:
return AuthForm(self).display(request)
# TODO hiding forms behind a ResourceGuard sucks, because if
# ResourceGuard needs to authenticate the user, it will 1) complain
# about the form submitted, 2) throw the data away. This happens if
# you use "foo?a=b" -style URLs and the user hasn't authenticated yet,
# or with session expiry.
class ResourceGuard(resource.Resource):
isLeaf = 1
def __init__(self, res, service, sessionIdentity=None, sessionPerspective=None):
resource.Resource.__init__(self)
self.res = res
self.service = service
self.sessionPerspective = sessionPerspective
self.sessionIdentity = sessionIdentity
def __getattr__(self, k):
if not self.__dict__.has_key("res"):
raise AttributeError, k
return getattr(self.res, k)
def __getstate__(self):
return self.__dict__.copy()
def listNames(self):
return self.res.listNames()
def reallyRender(self, request):
# it's authenticated already...
res = resource.getChildForRequest(self.res, request)
val = res.render(request)
if val != NOT_DONE_YET:
request.write(val)
request.finish()
return widgets.FORGET_IT
def render(self, request):
session = request.getSession()
resKey = string.join(['AUTH',self.service.serviceName], '_')
if hasattr(session, resKey):
self.reallyRender(request)
return NOT_DONE_YET
else:
return AuthPage(self,
self.sessionPerspective,
self.sessionIdentity).render(request) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/guard.py | guard.py |
#
"""Micro Document Object Model: a partial DOM implementation with SUX.
This is an implementation of what we consider to be the useful subset of the
DOM. The chief advantage of this library is that, not being burdened with
standards compliance, it can remain very stable between versions. We can also
implement utility 'pythonic' ways to access and mutate the XML tree.
Since this has not subjected to a serious trial by fire, it is not recommended
to use this outside of Twisted applications. However, it seems to work just
fine for the documentation generator, which parses a fairly representative
sample of XML.
Microdom mainly focuses on working with HTML and XHTML.
"""
from __future__ import nested_scopes
# System Imports
import re
from cStringIO import StringIO
# Twisted Imports
from twisted.web.sux import XMLParser, ParseError
from twisted.python.util import InsensitiveDict
# create NodeList class
from types import ListType as NodeList
from types import StringTypes, UnicodeType
def getElementsByTagName(iNode, name):
matches = []
matches_append = matches.append # faster lookup. don't do this at home
slice=[iNode]
while len(slice)>0:
c = slice.pop(0)
if c.nodeName == name:
matches_append(c)
slice[:0] = c.childNodes
return matches
def getElementsByTagNameNoCase(iNode, name):
name = name.lower()
matches = []
matches_append = matches.append
slice=[iNode]
while len(slice)>0:
c = slice.pop(0)
if c.nodeName.lower() == name:
matches_append(c)
slice[:0] = c.childNodes
return matches
# order is important
HTML_ESCAPE_CHARS = (('&', '&'), # don't add any entities before this one
('<', '<'),
('>', '>'),
('"', '"'))
REV_HTML_ESCAPE_CHARS = list(HTML_ESCAPE_CHARS)
REV_HTML_ESCAPE_CHARS.reverse()
XML_ESCAPE_CHARS = HTML_ESCAPE_CHARS + (("'", '''),)
REV_XML_ESCAPE_CHARS = list(XML_ESCAPE_CHARS)
REV_XML_ESCAPE_CHARS.reverse()
def unescape(text, chars=REV_HTML_ESCAPE_CHARS):
"Perform the exact opposite of 'escape'."
for s, h in chars:
text = text.replace(h, s)
return text
def escape(text, chars=HTML_ESCAPE_CHARS):
"Escape a few XML special chars with XML entities."
for s, h in chars:
text = text.replace(s, h)
return text
class MismatchedTags(Exception):
def __init__(self, filename, expect, got, endLine, endCol, begLine, begCol):
(self.filename, self.expect, self.got, self.begLine, self.begCol, self.endLine,
self.endCol) = filename, expect, got, begLine, begCol, endLine, endCol
def __str__(self):
return ("expected </%s>, got </%s> line: %s col: %s, began line: %s col: %s"
% (self.expect, self.got, self.endLine, self.endCol, self.begLine,
self.begCol))
class Node(object):
nodeName = "Node"
def __init__(self, parentNode=None):
self.parentNode = parentNode
self.childNodes = []
def isEqualToNode(self, n):
for a, b in zip(self.childNodes, n.childNodes):
if not a.isEqualToNode(b):
return 0
return 1
def writexml(self, stream, indent='', addindent='', newl='', strip=0,
nsprefixes={}, namespace=''):
raise NotImplementedError()
def toxml(self, indent='', addindent='', newl='', strip=0, nsprefixes={},
namespace=''):
s = StringIO()
self.writexml(s, indent, addindent, newl, strip, nsprefixes, namespace)
rv = s.getvalue()
return rv
def writeprettyxml(self, stream, indent='', addindent=' ', newl='\n', strip=0):
return self.writexml(stream, indent, addindent, newl, strip)
def toprettyxml(self, indent='', addindent=' ', newl='\n', strip=0):
return self.toxml(indent, addindent, newl, strip)
def cloneNode(self, deep=0, parent=None):
raise NotImplementedError()
def hasChildNodes(self):
if self.childNodes:
return 1
else:
return 0
def appendChild(self, child):
assert isinstance(child, Node)
self.childNodes.append(child)
child.parentNode = self
def insertBefore(self, new, ref):
i = self.childNodes.index(ref)
new.parentNode = self
self.childNodes.insert(i, new)
return new
def removeChild(self, child):
if child in self.childNodes:
self.childNodes.remove(child)
child.parentNode = None
return child
def replaceChild(self, newChild, oldChild):
assert isinstance(newChild, Node)
#if newChild.parentNode:
# newChild.parentNode.removeChild(newChild)
assert (oldChild.parentNode is self,
('oldChild (%s): oldChild.parentNode (%s) != self (%s)'
% (oldChild, oldChild.parentNode, self)))
self.childNodes[self.childNodes.index(oldChild)] = newChild
oldChild.parentNode = None
newChild.parentNode = self
def lastChild(self):
return self.childNodes[-1]
def firstChild(self):
if len(self.childNodes):
return self.childNodes[0]
return None
#def get_ownerDocument(self):
# """This doesn't really get the owner document; microdom nodes
# don't even have one necessarily. This gets the root node,
# which is usually what you really meant.
# *NOT DOM COMPLIANT.*
# """
# node=self
# while (node.parentNode): node=node.parentNode
# return node
#ownerDocument=node.get_ownerDocument()
# leaving commented for discussion; see also domhelpers.getParents(node)
class Document(Node):
def __init__(self, documentElement=None):
Node.__init__(self)
if documentElement:
self.appendChild(documentElement)
def cloneNode(self, deep=0, parent=None):
d = Document()
d.doctype = self.doctype
if deep:
newEl = self.documentElement.cloneNode(1, self)
else:
newEl = self.documentElement
d.appendChild(newEl)
return d
doctype = None
def isEqualToDocument(self, n):
return (self.doctype == n.doctype) and self.isEqualToNode(n)
def get_documentElement(self):
return self.childNodes[0]
documentElement=property(get_documentElement)
def appendChild(self, c):
assert not self.childNodes, "Only one element per document."
Node.appendChild(self, c)
def writexml(self, stream, indent='', addindent='', newl='', strip=0,
nsprefixes={}, namespace=''):
stream.write('<?xml version="1.0"?>' + newl)
if self.doctype:
stream.write("<!DOCTYPE "+self.doctype+">" + newl)
self.documentElement.writexml(stream, indent, addindent, newl, strip,
nsprefixes, namespace)
# of dubious utility (?)
def createElement(self, name, **kw):
return Element(name, **kw)
def createTextNode(self, text):
return Text(text)
def createComment(self, text):
return Comment(text)
def getElementsByTagName(self, name):
if self.documentElement.caseInsensitive:
return getElementsByTagNameNoCase(self, name)
return getElementsByTagName(self, name)
def getElementById(self, id):
childNodes = self.childNodes[:]
while childNodes:
node = childNodes.pop(0)
if node.childNodes:
childNodes.extend(node.childNodes)
if hasattr(node, 'getAttribute') and node.getAttribute("id") == id:
return node
class EntityReference(Node):
def __init__(self, eref, parentNode=None):
Node.__init__(self, parentNode)
self.eref = eref
self.nodeValue = self.data = "&" + eref + ";"
def isEqualToEntityReference(self, n):
if not isinstance(n, EntityReference):
return 0
return (self.eref == n.eref) and (self.nodeValue == n.nodeValue)
def writexml(self, stream, indent='', addindent='', newl='', strip=0,
nsprefixes={}, namespace=''):
stream.write(self.nodeValue)
def cloneNode(self, deep=0, parent=None):
return EntityReference(self.eref, parent)
class CharacterData(Node):
def __init__(self, data, parentNode=None):
Node.__init__(self, parentNode)
self.value = self.data = self.nodeValue = data
def isEqualToCharacterData(self, n):
return self.value == n.value
class Comment(CharacterData):
"""A comment node."""
def writexml(self, stream, indent='', addindent='', newl='', strip=0,
nsprefixes={}, namespace=''):
val=self.data
if isinstance(val, UnicodeType):
val=val.encode('utf8')
stream.write("<!--%s-->" % val)
def cloneNode(self, deep=0, parent=None):
return Comment(self.nodeValue, parent)
class Text(CharacterData):
def __init__(self, data, parentNode=None, raw=0):
CharacterData.__init__(self, data, parentNode)
self.raw = raw
def cloneNode(self, deep=0, parent=None):
return Text(self.nodeValue, parent, self.raw)
def writexml(self, stream, indent='', addindent='', newl='', strip=0,
nsprefixes={}, namespace=''):
if self.raw:
val = self.nodeValue
if not isinstance(val, StringTypes):
val = str(self.nodeValue)
else:
v = self.nodeValue
if not isinstance(v, StringTypes):
v = str(v)
if strip:
v = ' '.join(v.split())
val = escape(v)
if isinstance(val, UnicodeType):
val = val.encode('utf8')
stream.write(val)
def __repr__(self):
return "Text(%s" % repr(self.nodeValue) + ')'
class CDATASection(CharacterData):
def cloneNode(self, deep=0, parent=None):
return CDATASection(self.nodeValue, parent)
def writexml(self, stream, indent='', addindent='', newl='', strip=0,
nsprefixes={}, namespace=''):
stream.write("<![CDATA[")
stream.write(self.nodeValue)
stream.write("]]>")
def _genprefix():
i = 0
while True:
yield 'p' + str(i)
i = i + 1
genprefix = _genprefix().next
class _Attr(CharacterData):
"Support class for getAttributeNode."
class Element(Node):
preserveCase = 0
caseInsensitive = 1
nsprefixes = None
def __init__(self, tagName, attributes=None, parentNode=None,
filename=None, markpos=None,
caseInsensitive=1, preserveCase=0,
namespace=None):
Node.__init__(self, parentNode)
self.preserveCase = preserveCase or not caseInsensitive
self.caseInsensitive = caseInsensitive
if not preserveCase:
tagName = tagName.lower()
if attributes is None:
self.attributes = {}
else:
self.attributes = attributes
for k, v in self.attributes.items():
self.attributes[k] = unescape(v)
if caseInsensitive:
self.attributes = InsensitiveDict(self.attributes,
preserve=preserveCase)
self.endTagName = self.nodeName = self.tagName = tagName
self._filename = filename
self._markpos = markpos
self.namespace = namespace
def addPrefixes(self, pfxs):
if self.nsprefixes is None:
self.nsprefixes = pfxs
else:
self.nsprefixes.update(pfxs)
def endTag(self, endTagName):
if not self.preserveCase:
endTagName = endTagName.lower()
self.endTagName = endTagName
def isEqualToElement(self, n):
if self.caseInsensitive:
return ((self.attributes == n.attributes)
and (self.nodeName.lower() == n.nodeName.lower()))
return (self.attributes == n.attributes) and (self.nodeName == n.nodeName)
def cloneNode(self, deep=0, parent=None):
clone = Element(
self.tagName, parentNode=parent, namespace=self.namespace,
preserveCase=self.preserveCase, caseInsensitive=self.caseInsensitive)
clone.attributes.update(self.attributes)
if deep:
clone.childNodes = [child.cloneNode(1, clone) for child in self.childNodes]
else:
clone.childNodes = []
return clone
def getElementsByTagName(self, name):
if self.caseInsensitive:
return getElementsByTagNameNoCase(self, name)
return getElementsByTagName(self, name)
def hasAttributes(self):
return 1
def getAttribute(self, name, default=None):
return self.attributes.get(name, default)
def getAttributeNS(self, ns, name, default=None):
nsk = (ns, name)
if self.attributes.has_key(nsk):
return self.attributes[nsk]
if ns == self.namespace:
return self.attributes.get(name, default)
return default
def getAttributeNode(self, name):
return _Attr(self.getAttribute(name), self)
def setAttribute(self, name, attr):
self.attributes[name] = attr
def removeAttribute(self, name):
if name in self.attributes:
del self.attributes[name]
def hasAttribute(self, name):
return name in self.attributes
def writexml(self, stream, indent='', addindent='', newl='', strip=0,
nsprefixes={}, namespace=''):
# write beginning
ALLOWSINGLETON = ('img', 'br', 'hr', 'base', 'meta', 'link', 'param',
'area', 'input', 'col', 'basefont', 'isindex',
'frame')
BLOCKELEMENTS = ('html', 'head', 'body', 'noscript', 'ins', 'del',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'script',
'ul', 'ol', 'dl', 'pre', 'hr', 'blockquote',
'address', 'p', 'div', 'fieldset', 'table', 'tr',
'form', 'object', 'fieldset', 'applet', 'map')
FORMATNICELY = ('tr', 'ul', 'ol', 'head')
# this should never be necessary unless people start
# changing .tagName on the fly(?)
if not self.preserveCase:
self.endTagName = self.tagName
w = stream.write
if self.nsprefixes:
newprefixes = self.nsprefixes.copy()
for ns in nsprefixes.keys():
if ns in newprefixes:
del newprefixes[ns]
else:
newprefixes = {}
begin = ['<']
if self.tagName in BLOCKELEMENTS:
begin = [newl, indent] + begin
bext = begin.extend
writeattr = lambda _atr, _val: bext((' ', _atr, '="', escape(_val), '"'))
if namespace != self.namespace and self.namespace is not None:
if nsprefixes.has_key(self.namespace):
prefix = nsprefixes[self.namespace]
bext(prefix+':'+self.tagName)
else:
bext(self.tagName)
writeattr("xmlns", self.namespace)
else:
bext(self.tagName)
j = ''.join
for attr, val in self.attributes.iteritems():
if isinstance(attr, tuple):
ns, key = attr
if nsprefixes.has_key(ns):
prefix = nsprefixes[ns]
else:
prefix = genprefix()
newprefixes[ns] = prefix
assert val is not None
writeattr(prefix+':'+key,val)
else:
assert val is not None
writeattr(attr, val)
if newprefixes:
for ns, prefix in newprefixes.iteritems():
if prefix:
writeattr('xmlns:'+prefix, ns)
newprefixes.update(nsprefixes)
downprefixes = newprefixes
else:
downprefixes = nsprefixes
w(j(begin))
if self.childNodes:
w(">")
newindent = indent + addindent
for child in self.childNodes:
if self.tagName in BLOCKELEMENTS and \
self.tagName in FORMATNICELY:
w(j((newl, newindent)))
child.writexml(stream, newindent, addindent, newl, strip,
downprefixes, self.namespace)
if self.tagName in BLOCKELEMENTS:
w(j((newl, indent)))
w(j(("</", self.endTagName, '>')))
elif self.tagName.lower() not in ALLOWSINGLETON:
w(j(('></', self.endTagName, '>')))
else:
w(" />")
def __repr__(self):
rep = "Element(%s" % repr(self.nodeName)
if self.attributes:
rep += ", attributes=%r" % (self.attributes,)
if self._filename:
rep += ", filename=%r" % (self._filename,)
if self._markpos:
rep += ", markpos=%r" % (self._markpos,)
return rep + ')'
def __str__(self):
rep = "<" + self.nodeName
if self._filename or self._markpos:
rep += " ("
if self._filename:
rep += repr(self._filename)
if self._markpos:
rep += " line %s column %s" % self._markpos
if self._filename or self._markpos:
rep += ")"
for item in self.attributes.items():
rep += " %s=%r" % item
if self.hasChildNodes():
rep += " >...</%s>" % self.nodeName
else:
rep += " />"
return rep
def _unescapeDict(d):
dd = {}
for k, v in d.items():
dd[k] = unescape(v)
return dd
def _reverseDict(d):
dd = {}
for k, v in d.items():
dd[v]=k
return dd
class MicroDOMParser(XMLParser):
# <dash> glyph: a quick scan thru the DTD says BODY, AREA, LINK, IMG, HR,
# P, DT, DD, LI, INPUT, OPTION, THEAD, TFOOT, TBODY, COLGROUP, COL, TR, TH,
# TD, HEAD, BASE, META, HTML all have optional closing tags
soonClosers = 'area link br img hr input base meta'.split()
laterClosers = {'p': ['p', 'dt'],
'dt': ['dt','dd'],
'dd': ['dt', 'dd'],
'li': ['li'],
'tbody': ['thead', 'tfoot', 'tbody'],
'thead': ['thead', 'tfoot', 'tbody'],
'tfoot': ['thead', 'tfoot', 'tbody'],
'colgroup': ['colgroup'],
'col': ['col'],
'tr': ['tr'],
'td': ['td'],
'th': ['th'],
'head': ['body'],
'title': ['head', 'body'], # this looks wrong...
'option': ['option'],
}
def __init__(self, beExtremelyLenient=0, caseInsensitive=1, preserveCase=0,
soonClosers=soonClosers, laterClosers=laterClosers):
self.elementstack = []
d = {'xmlns': 'xmlns', '': None}
dr = _reverseDict(d)
self.nsstack = [(d,None,dr)]
self.documents = []
self._mddoctype = None
self.beExtremelyLenient = beExtremelyLenient
self.caseInsensitive = caseInsensitive
self.preserveCase = preserveCase or not caseInsensitive
self.soonClosers = soonClosers
self.laterClosers = laterClosers
# self.indentlevel = 0
def shouldPreserveSpace(self):
for edx in xrange(len(self.elementstack)):
el = self.elementstack[-edx]
if el.tagName == 'pre' or el.getAttribute("xml:space", '') == 'preserve':
return 1
return 0
def _getparent(self):
if self.elementstack:
return self.elementstack[-1]
else:
return None
COMMENT = re.compile(r"\s*/[/*]\s*")
def _fixScriptElement(self, el):
# this deals with case where there is comment or CDATA inside
# <script> tag and we want to do the right thing with it
if not self.beExtremelyLenient or not len(el.childNodes) == 1:
return
c = el.firstChild()
if isinstance(c, Text):
# deal with nasty people who do stuff like:
# <script> // <!--
# x = 1;
# // --></script>
# tidy does this, for example.
prefix = ""
oldvalue = c.value
match = self.COMMENT.match(oldvalue)
if match:
prefix = match.group()
oldvalue = oldvalue[len(prefix):]
# now see if contents are actual node and comment or CDATA
try:
e = parseString("<a>%s</a>" % oldvalue).childNodes[0]
except (ParseError, MismatchedTags):
return
if len(e.childNodes) != 1:
return
e = e.firstChild()
if isinstance(e, (CDATASection, Comment)):
el.childNodes = []
if prefix:
el.childNodes.append(Text(prefix))
el.childNodes.append(e)
def gotDoctype(self, doctype):
self._mddoctype = doctype
def gotTagStart(self, name, attributes):
# print ' '*self.indentlevel, 'start tag',name
# self.indentlevel += 1
parent = self._getparent()
if (self.beExtremelyLenient and isinstance(parent, Element)):
parentName = parent.tagName
myName = name
if self.caseInsensitive:
parentName = parentName.lower()
myName = myName.lower()
if myName in self.laterClosers.get(parentName, []):
self.gotTagEnd(parent.tagName)
parent = self._getparent()
attributes = _unescapeDict(attributes)
namespaces = self.nsstack[-1][0]
newspaces = {}
for k, v in attributes.items():
if k.startswith('xmlns'):
spacenames = k.split(':',1)
if len(spacenames) == 2:
newspaces[spacenames[1]] = v
else:
newspaces[''] = v
del attributes[k]
if newspaces:
namespaces = namespaces.copy()
namespaces.update(newspaces)
for k, v in attributes.items():
ksplit = k.split(':', 1)
if len(ksplit) == 2:
pfx, tv = ksplit
if pfx != 'xml' and namespaces.has_key(pfx):
attributes[namespaces[pfx], tv] = v
del attributes[k]
el = Element(name, attributes, parent,
self.filename, self.saveMark(),
caseInsensitive=self.caseInsensitive,
preserveCase=self.preserveCase,
namespace=namespaces.get(''))
revspaces = _reverseDict(newspaces)
el.addPrefixes(revspaces)
if newspaces:
rscopy = self.nsstack[-1][2].copy()
rscopy.update(revspaces)
self.nsstack.append((namespaces, el, rscopy))
self.elementstack.append(el)
if parent:
parent.appendChild(el)
if (self.beExtremelyLenient and el.tagName in self.soonClosers):
self.gotTagEnd(name)
def _gotStandalone(self, factory, data):
parent = self._getparent()
te = factory(data, parent)
if parent:
parent.appendChild(te)
elif self.beExtremelyLenient:
self.documents.append(te)
def gotText(self, data):
if data.strip() or self.shouldPreserveSpace():
self._gotStandalone(Text, data)
def gotComment(self, data):
self._gotStandalone(Comment, data)
def gotEntityReference(self, entityRef):
self._gotStandalone(EntityReference, entityRef)
def gotCData(self, cdata):
self._gotStandalone(CDATASection, cdata)
def gotTagEnd(self, name):
# print ' '*self.indentlevel, 'end tag',name
# self.indentlevel -= 1
if not self.elementstack:
if self.beExtremelyLenient:
return
raise MismatchedTags(*((self.filename, "NOTHING", name)
+self.saveMark()+(0,0)))
el = self.elementstack.pop()
pfxdix = self.nsstack[-1][2]
if self.nsstack[-1][1] is el:
nstuple = self.nsstack.pop()
else:
nstuple = None
if self.caseInsensitive:
tn = el.tagName.lower()
cname = name.lower()
else:
tn = el.tagName
cname = name
nsplit = name.split(':',1)
if len(nsplit) == 2:
pfx, newname = nsplit
ns = pfxdix.get(pfx,None)
if ns is not None:
if el.namespace != ns:
if not self.beExtremelyLenient:
raise MismatchedTags(*((self.filename, el.tagName, name)
+self.saveMark()+el._markpos))
if not (tn == cname):
if self.beExtremelyLenient:
if self.elementstack:
lastEl = self.elementstack[0]
for idx in xrange(len(self.elementstack)):
if self.elementstack[-(idx+1)].tagName == cname:
self.elementstack[-(idx+1)].endTag(name)
break
else:
# this was a garbage close tag; wait for a real one
self.elementstack.append(el)
if nstuple is not None:
self.nsstack.append(nstuple)
return
del self.elementstack[-(idx+1):]
if not self.elementstack:
self.documents.append(lastEl)
return
else:
raise MismatchedTags(*((self.filename, el.tagName, name)
+self.saveMark()+el._markpos))
el.endTag(name)
if not self.elementstack:
self.documents.append(el)
if self.beExtremelyLenient and el.tagName == "script":
self._fixScriptElement(el)
def connectionLost(self, reason):
XMLParser.connectionLost(self, reason) # This can cause more events!
if self.elementstack:
if self.beExtremelyLenient:
self.documents.append(self.elementstack[0])
else:
raise MismatchedTags(*((self.filename, self.elementstack[-1],
"END_OF_FILE")
+self.saveMark()
+self.elementstack[-1]._markpos))
def parse(readable, *args, **kwargs):
"""Parse HTML or XML readable."""
if not hasattr(readable, "read"):
readable = open(readable, "rb")
mdp = MicroDOMParser(*args, **kwargs)
mdp.filename = getattr(readable, "name", "<xmlfile />")
mdp.makeConnection(None)
if hasattr(readable,"getvalue"):
mdp.dataReceived(readable.getvalue())
else:
r = readable.read(1024)
while r:
mdp.dataReceived(r)
r = readable.read(1024)
mdp.connectionLost(None)
if not mdp.documents:
raise ParseError(mdp.filename, 0, 0, "No top-level Nodes in document")
if mdp.beExtremelyLenient:
if len(mdp.documents) == 1:
d = mdp.documents[0]
if not isinstance(d, Element):
el = Element("html")
el.appendChild(d)
d = el
else:
d = Element("html")
for child in mdp.documents:
d.appendChild(child)
else:
d = mdp.documents[0]
doc = Document(d)
doc.doctype = mdp._mddoctype
return doc
def parseString(st, *args, **kw):
if isinstance(st, UnicodeType):
# this isn't particularly ideal, but it does work.
return parse(StringIO(st.encode('UTF-16')), *args, **kw)
return parse(StringIO(st), *args, **kw)
def parseXML(readable):
"""Parse an XML readable object."""
return parse(readable, caseInsensitive=0, preserveCase=1)
def parseXMLString(st):
"""Parse an XML readable object."""
return parseString(st, caseInsensitive=0, preserveCase=1)
# Utility
class lmx:
"""Easy creation of XML."""
def __init__(self, node='div'):
if isinstance(node, StringTypes):
node = Element(node)
self.node = node
def __getattr__(self, name):
if name[0] == '_':
raise AttributeError("no private attrs")
return lambda **kw: self.add(name,**kw)
def __setitem__(self, key, val):
self.node.setAttribute(key, val)
def __getitem__(self, key):
return self.node.getAttribute(key)
def text(self, txt, raw=0):
nn = Text(txt, raw=raw)
self.node.appendChild(nn)
return self
def add(self, tagName, **kw):
newNode = Element(tagName, caseInsensitive=0, preserveCase=0)
self.node.appendChild(newNode)
xf = lmx(newNode)
for k, v in kw.items():
if k[0] == '_':
k = k[1:]
xf[k]=v
return xf | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/microdom.py | microdom.py |
import warnings
warnings.warn("This module is deprecated, please use Woven instead.", DeprecationWarning)
# System Imports
import string, time, types, traceback, pprint, sys, os
import linecache
import re
from cStringIO import StringIO
# Twisted Imports
from twisted.python import failure, log, rebuild, reflect, util
from twisted.internet import defer
from twisted.web import http
# Sibling Imports
import html, resource, error
import util as webutil
#backwards compatibility
from util import formatFailure, htmlrepr, htmlUnknown, htmlDict, htmlList,\
htmlInst, htmlString, htmlReprTypes
from server import NOT_DONE_YET
True = (1==1)
False = not True
# magic value that sez a widget needs to take over the whole page.
FORGET_IT = 99
def listify(x):
return [x]
def _ellipsize(x):
y = repr(x)
if len(y) > 1024:
return y[:1024]+"..."
return y
class Widget:
"""A component of a web page.
"""
title = None
def getTitle(self, request):
return self.title or reflect.qual(self.__class__)
def display(self, request):
"""Implement me to represent your widget.
I must return a list of strings and twisted.internet.defer.Deferred
instances.
"""
raise NotImplementedError("%s.display" % reflect.qual(self.__class__))
class StreamWidget(Widget):
"""A 'streamable' component of a webpage.
"""
def stream(self, write, request):
"""Call 'write' multiple times with a string argument to represent this widget.
"""
raise NotImplementedError("%s.stream" % reflect.qual(self.__class__))
def display(self, request):
"""Produce a list containing a single string.
"""
l = []
try:
result = self.stream(l.append, request)
if result is not None:
return result
return l
except:
return [webutil.formatFailure(failure.Failure())]
class WidgetMixin(Widget):
"""A mix-in wrapper for a Widget.
This mixin can be used to wrap functionality in any other widget with a
method of your choosing. It is designed to be used for mix-in classes that
can be mixed in to Form, StreamWidget, Presentation, etc, to augment the
data available to the 'display' methods of those classes, usually by adding
it to a Session.
"""
def display(self):
raise NotImplementedError("%s.display" % self.__class__)
def displayMixedWidget(self, request):
for base in reflect.allYourBase(self.__class__):
if issubclass(base, Widget) and not issubclass(base, WidgetMixin):
return base.display(self, request)
class Presentation(Widget):
"""I am a widget which formats a template with interspersed python expressions.
"""
template = '''
Hello, %%%%world%%%%.
'''
world = "you didn't assign to the 'template' attribute"
def __init__(self, template=None, filename=None):
if filename:
self.template = open(filename).read()
elif template:
self.template = template
self.variables = {}
self.tmpl = string.split(self.template, "%%%%")
def addClassVars(self, namespace, Class):
for base in Class.__bases__:
# Traverse only superclasses that know about Presentation.
if issubclass(base, Presentation) and base is not Presentation:
self.addClassVars(namespace, base)
# 'lower' classes in the class heirarchy take precedence.
for k in Class.__dict__.keys():
namespace[k] = getattr(self, k)
def addVariables(self, namespace, request):
self.addClassVars(namespace, self.__class__)
def prePresent(self, request):
"""Perform any tasks which must be done before presenting the page.
"""
def formatTraceback(self, tb):
return [html.PRE(tb)]
def streamCall(self, call, *args, **kw):
"""Utility: Call a method like StreamWidget's 'stream'.
"""
io = StringIO()
apply(call, (io.write,) + args, kw)
return io.getvalue()
def display(self, request):
tm = []
flip = 0
namespace = {}
self.prePresent(request)
self.addVariables(namespace, request)
# This variable may not be obscured...
namespace['request'] = request
namespace['self'] = self
for elem in self.tmpl:
flip = not flip
if flip:
if elem:
tm.append(elem)
else:
try:
x = eval(elem, namespace, namespace)
except:
log.deferr()
tm.append(webutil.formatFailure(failure.Failure()))
else:
if isinstance(x, types.ListType):
tm.extend(x)
elif isinstance(x, Widget):
val = x.display(request)
if not isinstance(val, types.ListType):
raise Exception("%s.display did not return a list, it returned %s!" % (x.__class__, repr(val)))
tm.extend(val)
else:
# Only two allowed types here should be deferred and
# string.
tm.append(x)
return tm
def htmlFor_hidden(write, name, value):
write('<INPUT TYPE="hidden" NAME="%s" VALUE="%s" />' % (name, value))
def htmlFor_file(write, name, value):
write('<INPUT SIZE="60" TYPE="file" NAME="%s" />' % name)
def htmlFor_string(write, name, value):
write('<INPUT SIZE="60" TYPE="text" NAME="%s" VALUE="%s" />' % (name, value))
def htmlFor_password(write, name, value):
write('<INPUT SIZE="60" TYPE="password" NAME="%s" />' % name)
def htmlFor_text(write, name, value):
write('<textarea COLS="60" ROWS="10" NAME="%s" WRAP="virtual">%s</textarea>' % (name, value))
def htmlFor_menu(write, name, value, allowMultiple=False):
"Value of the format [(optionName, displayName[, selected]), ...]"
write(' <select NAME="%s"%s>\n' %
(name, (allowMultiple and " multiple") or ''))
for v in value:
optionName, displayName, selected = util.padTo(3, v)
selected = (selected and " selected") or ''
write(' <option VALUE="%s"%s>%s</option>\n' %
(optionName, selected, displayName))
if not value:
write(' <option VALUE=""></option>\n')
write(" </select>\n")
def htmlFor_multimenu(write, name, value):
"Value of the format [(optionName, displayName[, selected]), ...]"
return htmlFor_menu(write, name, value, True)
def htmlFor_checkbox(write, name, value):
"A checkbox."
if value:
value = 'checked = "1"'
else:
value = ''
write('<INPUT TYPE="checkbox" NAME="__checkboxes__" VALUE="%s" %s />\n' % (name, value))
def htmlFor_checkgroup(write, name, value):
"A check-group."
for optionName, displayName, checked in value:
checked = (checked and 'checked = "1"') or ''
write('<INPUT TYPE="checkbox" NAME="%s" VALUE="%s" %s />%s<br />\n' % (name, optionName, checked, displayName))
def htmlFor_radio(write, name, value):
"A radio button group."
for optionName, displayName, checked in value:
checked = (checked and 'checked = "1"') or ''
write('<INPUT TYPE="radio" NAME="%s" VALUE="%s" %s />%s<br />\n' % (name, optionName, checked, displayName))
class FormInputError(Exception):
pass
class Form(Widget):
"""I am a web form.
In order to use me, you probably want to set self.formFields (or override
'getFormFields') and override 'process'. In order to demonstrate how this
is done, here is a small sample Form subclass::
| from twisted.web import widgets
| class HelloForm(widgets.Form):
| formFields = [
| ['string', 'Who to greet?', 'whoToGreet', 'World',
| 'This is for choosing who to greet.'],
| ['menu', 'How to greet?', 'how', [('cheerfully', 'with a smile'),
| ('sullenly', 'without enthusiasm'),
| ('spontaneously', 'on the spur of the moment')]]
| 'This is for choosing how to greet them.']
| def process(self, write, request, submit, whoToGreet, how):
| write('The web wakes up and %s says, \"Hello, %s!\"' % (how, whoToGreet))
If you load this widget, you will see that it displays a form with 2 inputs
derived from data in formFields. Note the argument names to 'process':
after 'write' and 'request', they are the same as the 3rd elements ('Input
Name' parameters) of the formFields list.
"""
formGen = {
'hidden': htmlFor_hidden,
'file': htmlFor_file,
'string': htmlFor_string,
'int': htmlFor_string,
'float': htmlFor_string,
'text': htmlFor_text,
'menu': htmlFor_menu,
'multimenu': htmlFor_multimenu,
'password': htmlFor_password,
'checkbox': htmlFor_checkbox,
'checkgroup': htmlFor_checkgroup,
'radio': htmlFor_radio,
}
formParse = {
'int': int,
'float': float,
}
formFields = [
]
# do we raise an error when we get extra args or not?
formAcceptExtraArgs = 0
def getFormFields(self, request, fieldSet = None):
"""I return a list of lists describing this form, or a Deferred.
This information is used both to display the form and to process it.
The list is in the following format::
| [['Input Type', 'Display Name', 'Input Name', 'Input Value', 'Description'],
| ['Input Type 2', 'Display Name 2', 'Input Name 2', 'Input Value 2', 'Description 2']
| ...]
Valid values for 'Input Type' are:
- 'hidden': a hidden field that contains a string that the user won't change
- 'string': a short string
- 'int': an integer, e.g. 1, 0, 25 or -23
- 'float': a float, e.g. 1.0, 2, -3.45, or 28.4324231
- 'text': a longer text field, suitable for entering paragraphs
- 'menu': an HTML SELECT input, a list of choices
- 'multimenu': an HTML SELECT input allowing multiple choices
- 'checkgroup': a group of checkboxes
- 'radio': a group of radio buttons
- 'password': a 'string' field where the contents are not visible as the user types
- 'file': a file-upload form (EXPERIMENTAL)
'Display Name' is a descriptive string that will be used to
identify the field to the user.
The 'Input Name' must be a legal Python identifier that describes both
the value's name on the HTML form and the name of an argument to
'self.process()'.
The 'Input Value' is usually a string, but its value can depend on the
'Input Type'. 'int' it is an integer, 'menu' it is a list of pairs of
strings, representing (value, name) pairs for the menu options. Input
value for 'checkgroup' and 'radio' should be a list of ('inputName',
'Display Name', 'checked') triplets.
The 'Description' field is an (optional) string which describes the form
item to the user.
If this result is statically determined for your Form subclass, you can
assign it to FormSubclass.formFields; if you need to determine it
dynamically, you can override this method.
Note: In many cases it is desirable to use user input for defaults in
the form rather than those supplied by your calculations, which is what
this method will do to self.formFields. If this is the case for you,
but you still need to dynamically calculate some fields, pass your
results back through this method by doing::
| def getFormFields(self, request):
| myFormFields = [self.myFieldCalculator()]
| return widgets.Form.getFormFields(self, request, myFormFields)
"""
fields = []
if fieldSet is None:
fieldSet = self.formFields
if not self.shouldProcess(request):
return fieldSet
for field in fieldSet:
if len(field)==5:
inputType, displayName, inputName, inputValue, description = field
else:
inputType, displayName, inputName, inputValue = field
description = ""
if inputType == 'checkbox':
if request.args.has_key('__checkboxes__'):
if inputName in request.args['__checkboxes__']:
inputValue = 1
else:
inputValue = 0
else:
inputValue = 0
elif inputType in ('checkgroup', 'radio'):
if request.args.has_key(inputName):
keys = request.args[inputName]
else:
keys = []
iv = inputValue
inputValue = []
for optionName, optionDisplayName, checked in iv:
checked = optionName in keys
inputValue.append([optionName, optionDisplayName, checked])
elif request.args.has_key(inputName):
iv = request.args[inputName][0]
if inputType in ['menu', 'multimenu']:
if iv in inputValue:
inputValue.remove(iv)
inputValue.insert(0, iv)
else:
inputValue = iv
fields.append([inputType, displayName, inputName, inputValue, description])
return fields
submitNames = ['Submit']
actionURI = ''
def format(self, form, write, request):
"""I display an HTML FORM according to the result of self.getFormFields.
"""
write('<form ENCTYPE="multipart/form-data" METHOD="post" ACTION="%s">\n'
'<table BORDER="0">\n' % (self.actionURI or request.uri))
for field in form:
if len(field) == 5:
inputType, displayName, inputName, inputValue, description = field
else:
inputType, displayName, inputName, inputValue = field
description = ""
write('<tr>\n<td ALIGN="right" VALIGN="top"><B>%s</B></td>\n'
'<td VALIGN="%s">\n' %
(displayName, ((inputType == 'text') and 'top') or 'middle'))
self.formGen[inputType](write, inputName, inputValue)
write('\n<br />\n<font size="-1">%s</font></td>\n</tr>\n' % description)
write('<tr><td></td><td ALIGN="left"><hr />\n')
for submitName in self.submitNames:
write('<INPUT TYPE="submit" NAME="submit" VALUE="%s" />\n' % submitName)
write('</td></tr>\n</table>\n'
'<INPUT TYPE="hidden" NAME="__formtype__" VALUE="%s" />\n'
% (reflect.qual(self.__class__)))
fid = self.getFormID()
if fid:
write('<INPUT TYPE="hidden" NAME="__formid__" VALUE="%s" />\n' % fid)
write("</form>\n")
def getFormID(self):
"""Override me: I disambiguate between multiple forms of the same type.
In order to determine which form an HTTP POST request is for, you must
have some unique identifier which distinguishes your form from other
forms of the same class. An example of such a unique identifier would
be: on a page with multiple FrobConf forms, each FrobConf form refers
to a particular Frobnitz instance, which has a unique id(). The
FrobConf form's getFormID would probably look like this::
| def getFormID(self):
| return str(id(self.frobnitz))
By default, this method will return None, since distinct Form instances
may be identical as far as the application is concerned.
"""
def process(self, write, request, submit, **kw):
"""Override me: I process a form.
I will only be called when the correct form input data to process this
form has been received.
I take a variable number of arguments, beginning with 'write',
'request', and 'submit'. 'write' is a callable object that will append
a string to the response, 'request' is a twisted.web.request.Request
instance, and 'submit' is the name of the submit action taken.
The remainder of my arguments must be correctly named. They will each be named after one of the
"""
write("<pre>Submit: %s <br /> %s</pre>" % (submit, html.PRE(pprint.PrettyPrinter().pformat(kw))))
def _doProcess(self, form, write, request):
"""(internal) Prepare arguments for self.process.
"""
args = request.args.copy()
kw = {}
for field in form:
inputType, displayName, inputName, inputValue = field[:4]
if inputType == 'checkbox':
if request.args.has_key('__checkboxes__'):
if inputName in request.args['__checkboxes__']:
formData = 1
else:
formData = 0
else:
formData = 0
elif inputType in ['checkgroup', 'radio', 'multimenu']:
if args.has_key(inputName):
formData = args[inputName]
del args[inputName]
else:
formData = []
else:
if not args.has_key(inputName):
raise FormInputError("missing field %s." % repr(inputName))
formData = args[inputName]
del args[inputName]
if not len(formData) == 1:
raise FormInputError("multiple values for field %s." %repr(inputName))
formData = formData[0]
method = self.formParse.get(inputType)
if method:
try:
formData = method(formData)
except:
raise FormInputError("%s: %s" % (displayName, "error"))
kw[inputName] = formData
submitAction = args.get('submit')
if submitAction:
submitAction = submitAction[0]
for field in ['submit', '__formtype__', '__checkboxes__']:
if args.has_key(field):
del args[field]
if args and not self.formAcceptExtraArgs:
raise FormInputError("unknown fields: %s" % repr(args))
return apply(self.process, (write, request, submitAction), kw)
def formatError(self,error):
"""Format an error message.
By default, this will make the message appear in red, bold italics.
"""
return '<font color="#f00"><b><i>%s</i></b></font><br />\n' % error
def shouldProcess(self, request):
args = request.args
fid = self.getFormID()
return (args and # there are arguments to the request
args.has_key('__formtype__') and # this is a widgets.Form request
args['__formtype__'][0] == reflect.qual(self.__class__) and # it is for a form of my type
((not fid) or # I am only allowed one form per page
(args.has_key('__formid__') and # if I distinguish myself from others, the request must too
args['__formid__'][0] == fid))) # I am in fact the same
def tryAgain(self, err, req):
"""Utility method for re-drawing the form with an error message.
This is handy in forms that process Deferred results. Normally you can
just raise a FormInputError() and this will happen by default.
"""
l = []
w = l.append
w(self.formatError(err))
self.format(self.getFormFields(req), w, req)
return l
def display(self, request):
"""Display the form."""
form = self.getFormFields(request)
if isinstance(form, defer.Deferred):
if self.shouldProcess(request):
form.addCallback(lambda form, f=self._displayProcess, r=request: f(r, form))
else:
form.addCallback(lambda form, f=self._displayFormat, r=request: f(r, form))
return [form]
else:
if self.shouldProcess(request):
return self._displayProcess(request, form)
else:
return self._displayFormat(request, form)
def _displayProcess(self, request, form):
l = []
write = l.append
try:
val = self._doProcess(form, write, request)
if val:
l.extend(val)
except FormInputError, fie:
write(self.formatError(str(fie)))
return l
def _displayFormat(self, request, form):
l = []
self.format(form, l.append, request)
return l
class DataWidget(Widget):
def __init__(self, data):
self.data = data
def display(self, request):
return [self.data]
class Time(Widget):
def display(self, request):
return [time.ctime(time.time())]
class Container(Widget):
def __init__(self, *widgets):
self.widgets = widgets
def display(self, request):
value = []
for widget in self.widgets:
d = widget.display(request)
value.extend(d)
return value
class _RequestDeferral:
def __init__(self):
self.deferred = defer.Deferred()
self.io = StringIO()
self.write = self.io.write
def finish(self):
self.deferred.callback([self.io.getvalue()])
def possiblyDeferWidget(widget, request):
# web in my head get it out get it out
try:
disp = widget.display(request)
# if this widget wants to defer anything -- well, I guess we've got to
# defer it.
for elem in disp:
if isinstance(elem, defer.Deferred):
req = _RequestDeferral()
RenderSession(disp, req)
return req.deferred
return string.join(disp, '')
except:
io = StringIO()
traceback.print_exc(file=io)
return html.PRE(io.getvalue())
class RenderSession:
"""I handle rendering of a list of deferreds, outputting their
results in correct order."""
class Sentinel:
pass
def __init__(self, lst, request):
self.lst = lst
self.request = request
self.needsHeaders = 0
self.beforeBody = 1
self.forgotten = 0
self.pauseList = []
for i in range(len(self.lst)):
item = self.lst[i]
if isinstance(item, defer.Deferred):
self._addDeferred(item, self.lst, i)
self.keepRendering()
def _addDeferred(self, deferred, lst, idx):
sentinel = self.Sentinel()
if hasattr(deferred, 'needsHeader'):
# You might want to set a header from a deferred, in which
# case you have to set an attribute -- needsHeader.
self.needsHeaders = self.needsHeaders + 1
args = (sentinel, 1)
else:
args = (sentinel, 0)
lst[idx] = sentinel, deferred
deferred.pause()
self.pauseList.append(deferred)
deferred.addCallbacks(self.callback, self.callback,
callbackArgs=args, errbackArgs=args)
def callback(self, result, sentinel, decNeedsHeaders):
if self.forgotten:
return
if result != FORGET_IT:
self.needsHeaders = self.needsHeaders - decNeedsHeaders
else:
result = [FORGET_IT]
# Make sure result is a sequence,
if not type(result) in (types.ListType, types.TupleType):
result = [result]
# If the deferred does not wish to produce its result all at
# once, it can give us a partial result as
# (NOT_DONE_YET, partial_result)
## XXX: How would a deferred go about producing the result in multiple
## stages?? --glyph
if result[0] is NOT_DONE_YET:
done = 0
result = result[1]
if not type(result) in (types.ListType, types.TupleType):
result = [result]
else:
done = 1
for i in xrange(len(result)):
item = result[i]
if isinstance(item, defer.Deferred):
self._addDeferred(item, result, i)
for position in range(len(self.lst)):
item = self.lst[position]
if type(item) is types.TupleType and len(item) > 0:
if item[0] is sentinel:
break
else:
raise AssertionError('Sentinel for Deferred not found!')
if done:
self.lst[position:position+1] = result
else:
self.lst[position:position] = result
self.keepRendering()
def keepRendering(self):
while self.pauseList:
pl = self.pauseList
self.pauseList = []
for deferred in pl:
deferred.unpause()
return
if self.needsHeaders:
# short circuit actual rendering process until we're sure no
# more deferreds need to set headers...
return
assert self.lst is not None, "This shouldn't happen."
while 1:
item = self.lst[0]
if self.beforeBody and FORGET_IT in self.lst:
# If I haven't moved yet, and the widget wants to take
# over the page, let it do so!
self.forgotten = 1
return
if isinstance(item, types.StringType):
self.beforeBody = 0
self.request.write(item)
elif type(item) is types.TupleType and len(item) > 0:
if isinstance(item[0], self.Sentinel):
return
elif isinstance(item, failure.Failure):
self.request.write(webutil.formatFailure(item))
else:
self.beforeBody = 0
unknown = html.PRE(repr(item))
self.request.write("RENDERING UNKNOWN: %s" % unknown)
del self.lst[0]
if len(self.lst) == 0:
self.lst = None
self.request.finish()
return
## XXX: is this needed?
class WidgetResource(resource.Resource):
def __init__(self, widget):
self.widget = widget
resource.Resource.__init__(self)
def render(self, request):
RenderSession(self.widget.display(request), request)
return NOT_DONE_YET
class Page(resource.Resource, Presentation):
def __init__(self):
resource.Resource.__init__(self)
Presentation.__init__(self)
def render(self, request):
displayed = self.display(request)
RenderSession(displayed, request)
return NOT_DONE_YET
class WidgetPage(Page):
"""
I am a Page that takes a Widget in its constructor, and displays that
Widget wrapped up in a simple HTML template.
"""
stylesheet = '''
a
{
font-family: Lucida, Verdana, Helvetica, Arial, sans-serif;
color: #369;
text-decoration: none;
}
th
{
font-family: Lucida, Verdana, Helvetica, Arial, sans-serif;
font-weight: bold;
text-decoration: none;
text-align: left;
}
pre, code
{
font-family: "Courier New", Courier, monospace;
}
p, body, td, ol, ul, menu, blockquote, div
{
font-family: Lucida, Verdana, Helvetica, Arial, sans-serif;
color: #000;
}
'''
template = '''<html>
<head>
<title>%%%%self.title%%%%</title>
<style>
%%%%self.stylesheet%%%%
</style>
<base href="%%%%request.prePathURL()%%%%">
</head>
<body>
<h1>%%%%self.title%%%%</h1>
%%%%self.widget%%%%
</body>
</html>
'''
title = 'No Title'
widget = 'No Widget'
def __init__(self, widget):
Page.__init__(self)
self.widget = widget
if hasattr(widget, 'stylesheet'):
self.stylesheet = widget.stylesheet
def prePresent(self, request):
self.title = self.widget.getTitle(request)
def render(self, request):
displayed = self.display(request)
RenderSession(displayed, request)
return NOT_DONE_YET
class Gadget(resource.Resource):
"""I am a collection of Widgets, to be rendered through a Page Factory.
self.pageFactory should be a Resource that takes a Widget in its
constructor. The default is twisted.web.widgets.WidgetPage.
"""
isLeaf = 0
def __init__(self):
resource.Resource.__init__(self)
self.widgets = {}
self.files = []
self.modules = []
self.paths = {}
def render(self, request):
#Redirect to view this entity as a collection.
request.setResponseCode(http.FOUND)
# TODO who says it's not https?
request.setHeader("location","http%s://%s%s/" % (
request.isSecure() and 's' or '',
request.getHeader("host"),
(string.split(request.uri,'?')[0])))
return "NO DICE!"
def putWidget(self, path, widget):
"""
Gadget.putWidget(path, widget)
Add a Widget to this Gadget. It will be rendered through the
pageFactory associated with this Gadget, whenever 'path' is requested.
"""
self.widgets[path] = widget
#this is an obsolete function
def addFile(self, path):
"""
Gadget.addFile(path)
Add a static path to this Gadget. This method is obsolete, use
Gadget.putPath instead.
"""
log.msg("Gadget.addFile() is deprecated.")
self.paths[path] = path
def putPath(self, path, pathname):
"""
Gadget.putPath(path, pathname)
Add a static path to this Gadget. Whenever 'path' is requested,
twisted.web.static.File(pathname) is sent.
"""
self.paths[path] = pathname
def getWidget(self, path, request):
return self.widgets.get(path)
def pageFactory(self, *args, **kwargs):
"""
Gadget.pageFactory(*args, **kwargs) -> Resource
By default, this method returns self.page(*args, **kwargs). It
is only for backwards-compatibility -- you should set the 'pageFactory'
attribute on your Gadget inside of its __init__ method.
"""
#XXX: delete this after a while.
if hasattr(self, "page"):
log.msg("Gadget.page is deprecated, use Gadget.pageFactory instead")
return apply(self.page, args, kwargs)
else:
return apply(WidgetPage, args, kwargs)
def getChild(self, path, request):
if path == '':
# ZOOP!
if isinstance(self, Widget):
return self.pageFactory(self)
widget = self.getWidget(path, request)
if widget:
if isinstance(widget, resource.Resource):
return widget
else:
p = self.pageFactory(widget)
p.isLeaf = getattr(widget,'isLeaf',0)
return p
elif self.paths.has_key(path):
prefix = getattr(sys.modules[self.__module__], '__file__', '')
if prefix:
prefix = os.path.abspath(os.path.dirname(prefix))
return static.File(os.path.join(prefix, self.paths[path]))
elif path == '__reload__':
return self.pageFactory(Reloader(map(reflect.namedModule, [self.__module__] + self.modules)))
else:
return error.NoResource("No such child resource in gadget.")
class TitleBox(Presentation):
template = '''\
<table %%%%self.widthOption%%%% cellpadding="1" cellspacing="0" border="0"><tr>\
<td bgcolor="%%%%self.borderColor%%%%"><center><font color="%%%%self.titleTextColor%%%%">%%%%self.title%%%%</font></center>\
<table width="100%" cellpadding="3" cellspacing="0" border="0"><tr>\
<td bgcolor="%%%%self.boxColor%%%%"><font color="%%%%self.boxTextColor%%%%">%%%%self.widget%%%%</font></td>\
</tr></table></td></tr></table>\
'''
borderColor = '#000000'
titleTextColor = '#ffffff'
boxTextColor = '#000000'
boxColor = '#ffffff'
widthOption = 'width="100%"'
title = 'No Title'
widget = 'No Widget'
def __init__(self, title, widget):
"""Wrap a widget with a given title.
"""
self.widget = widget
self.title = title
Presentation.__init__(self)
class Reloader(Presentation):
template = '''
Reloading...
<ul>
%%%%reload(request)%%%%
</ul> ... reloaded!
'''
def __init__(self, modules):
Presentation.__init__(self)
self.modules = modules
def reload(self, request):
request.redirect("..")
x = []
write = x.append
for module in self.modules:
rebuild.rebuild(module)
write('<li>reloaded %s<br />' % module.__name__)
return x
class Sidebar(StreamWidget):
bar = [
['Twisted',
['mirror', 'http://coopweb.org/ssd/twisted/'],
['mailing list', 'cgi-bin/mailman/listinfo/twisted-python']
]
]
headingColor = 'ffffff'
headingTextColor = '000000'
activeHeadingColor = '000000'
activeHeadingTextColor = 'ffffff'
sectionColor = '000088'
sectionTextColor = '008888'
activeSectionColor = '0000ff'
activeSectionTextColor = '00ffff'
def __init__(self, highlightHeading, highlightSection):
self.highlightHeading = highlightHeading
self.highlightSection = highlightSection
def getList(self):
return self.bar
def stream(self, write, request):
write("<table width=120 cellspacing=1 cellpadding=1 border=0>")
for each in self.getList():
if each[0] == self.highlightHeading:
headingColor = self.activeHeadingColor
headingTextColor = self.activeHeadingTextColor
canHighlight = 1
else:
headingColor = self.headingColor
headingTextColor = self.headingTextColor
canHighlight = 0
write('<tr><td colspan=2 bgcolor="#%s"><font color="%s">'
'<strong>%s</strong>'
'</font></td></td></tr>\n' % (headingColor, headingTextColor, each[0]))
for name, link in each[1:]:
if canHighlight and (name == self.highlightSection):
sectionColor = self.activeSectionColor
sectionTextColor = self.activeSectionTextColor
else:
sectionColor = self.sectionColor
sectionTextColor = self.sectionTextColor
write('<tr><td align=right bgcolor="#%s" width=6>-</td>'
'<td bgcolor="#%s"><a href="%s"><font color="#%s">%s'
'</font></a></td></tr>'
% (sectionColor, sectionColor, request.sibLink(link), sectionTextColor, name))
write("</table>")
# moved from template.py
from twisted.web.woven import template
from twisted.python import components
class WebWidgetNodeMutator(template.NodeMutator):
"""A WebWidgetNodeMutator replaces the node that is passed in to generate
with the result of generating the twisted.web.widget instance it adapts.
"""
def generate(self, request, node):
widget = self.data
displayed = widget.display(request)
try:
html = string.join(displayed)
except:
pr = Presentation()
pr.tmpl = displayed
#strList = pr.display(request)
html = string.join(displayed)
stringMutator = template.StringNodeMutator(html)
return stringMutator.generate(request, node)
components.registerAdapter(WebWidgetNodeMutator, Widget, template.INodeMutator)
import static | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/widgets.py | widgets.py |
import string, os
# Twisted Imports
from twisted.web import server, static, twcgi, script, demo, distrib, trp
from twisted.internet import interfaces
from twisted.python import usage, reflect
from twisted.spread import pb
from twisted.application import internet, service, strports
class Options(usage.Options):
synopsis = "Usage: mktap web [options]"
optParameters = [["port", "p", "8080","Port to start the server on."],
["logfile", "l", None, "Path to web CLF (Combined Log Format) log file."],
["https", None, None, "Port to listen on for Secure HTTP."],
["certificate", "c", "server.pem", "SSL certificate to use for HTTPS. "],
["privkey", "k", "server.pem", "SSL certificate to use for HTTPS."],
]
optFlags = [["personal", "",
"Instead of generating a webserver, generate a "
"ResourcePublisher which listens on "
"~/%s" % distrib.UserDirectory.userSocketName],
["notracebacks", "n", "Display tracebacks in broken web pages. " +
"Displaying tracebacks to users may be security risk!"],
]
zsh_actions = {"logfile" : "_files -g '*.log'", "certificate" : "_files -g '*.pem'",
"privkey" : "_files -g '*.pem'"}
longdesc = """\
This creates a web.tap file that can be used by twistd. If you specify
no arguments, it will be a demo webserver that has the Test class from
twisted.web.demo in it."""
def __init__(self):
usage.Options.__init__(self)
self['indexes'] = []
self['root'] = None
def opt_index(self, indexName):
"""Add the name of a file used to check for directory indexes.
[default: index, index.html]
"""
self['indexes'].append(indexName)
opt_i = opt_index
def opt_user(self):
"""Makes a server with ~/public_html and ~/.twistd-web-pb support for
users.
"""
self['root'] = distrib.UserDirectory()
opt_u = opt_user
def opt_path(self, path):
"""<path> is either a specific file or a directory to
be set as the root of the web server. Use this if you
have a directory full of HTML, cgi, php3, epy, or rpy files or
any other files that you want to be served up raw.
"""
self['root'] = static.File(os.path.abspath(path))
self['root'].processors = {
'.cgi': twcgi.CGIScript,
'.php3': twcgi.PHP3Script,
'.php': twcgi.PHPScript,
'.epy': script.PythonScript,
'.rpy': script.ResourceScript,
'.trp': trp.ResourceUnpickler,
}
def opt_processor(self, proc):
"""`ext=class' where `class' is added as a Processor for files ending
with `ext'.
"""
if not isinstance(self['root'], static.File):
raise usage.UsageError("You can only use --processor after --path.")
ext, klass = proc.split('=', 1)
self['root'].processors[ext] = reflect.namedClass(klass)
def opt_static(self, path):
"""Same as --path, this is deprecated and will be removed in a
future release."""
print ("WARNING: --static is deprecated and will be removed in"
"a future release. Please use --path.")
self.opt_path(path)
opt_s = opt_static
def opt_class(self, className):
"""Create a Resource subclass with a zero-argument constructor.
"""
classObj = reflect.namedClass(className)
self['root'] = classObj()
def opt_resource_script(self, name):
"""An .rpy file to be used as the root resource of the webserver."""
self['root'] = script.ResourceScriptWrapper(name)
def opt_mime_type(self, defaultType):
"""Specify the default mime-type for static files."""
if not isinstance(self['root'], static.File):
raise usage.UsageError("You can only use --mime_type after --path.")
self['root'].defaultType = defaultType
opt_m = opt_mime_type
def opt_allow_ignore_ext(self):
"""Specify whether or not a request for 'foo' should return 'foo.ext'"""
if not isinstance(self['root'], static.File):
raise usage.UsageError("You can only use --allow_ignore_ext "
"after --path.")
self['root'].ignoreExt('*')
def opt_ignore_ext(self, ext):
"""Specify an extension to ignore. These will be processed in order.
"""
if not isinstance(self['root'], static.File):
raise usage.UsageError("You can only use --ignore_ext "
"after --path.")
self['root'].ignoreExt(ext)
def opt_flashconduit(self, port=None):
"""Start a flashconduit on the specified port.
"""
if not port:
port = "4321"
self['flashconduit'] = port
def postOptions(self):
if self['https']:
try:
from twisted.internet.ssl import DefaultOpenSSLContextFactory
except ImportError:
raise usage.UsageError("SSL support not installed")
def makeService(config):
s = service.MultiService()
if config['root']:
root = config['root']
if config['indexes']:
config['root'].indexNames = config['indexes']
else:
# This really ought to be web.Admin or something
root = demo.Test()
if isinstance(root, static.File):
root.registry.setComponent(interfaces.IServiceCollection, s)
if config['logfile']:
site = server.Site(root, logPath=config['logfile'])
else:
site = server.Site(root)
site.displayTracebacks = not config["notracebacks"]
if config['personal']:
import pwd,os
pw_name, pw_passwd, pw_uid, pw_gid, pw_gecos, pw_dir, pw_shell \
= pwd.getpwuid(os.getuid())
i = internet.UNIXServer(os.path.join(pw_dir,
distrib.UserDirectory.userSocketName),
pb.BrokerFactory(distrib.ResourcePublisher(site)))
i.setServiceParent(s)
else:
if config['https']:
from twisted.internet.ssl import DefaultOpenSSLContextFactory
i = internet.SSLServer(int(config['https']), site,
DefaultOpenSSLContextFactory(config['privkey'],
config['certificate']))
i.setServiceParent(s)
strports.service(config['port'], site).setServiceParent(s)
flashport = config.get('flashconduit', None)
if flashport:
from twisted.web.woven.flashconduit import FlashConduitFactory
i = internet.TCPServer(int(flashport), FlashConduitFactory(site))
i.setServiceParent(s)
return s | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/tap.py | tap.py |
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
"""This is a web-server which integrates with the twisted.internet
infrastructure.
"""
# System Imports
try:
import cStringIO as StringIO
except ImportError:
import StringIO
import base64
import string
import socket
import types
import operator
import cgi
import copy
import time
import os
from urllib import quote
try:
from twisted.protocols._c_urlarg import unquote
except ImportError:
from urllib import unquote
#some useful constants
NOT_DONE_YET = 1
# Twisted Imports
from twisted.spread import pb
from twisted.internet import reactor, protocol, defer, address, task
from twisted.web import http
from twisted.python import log, reflect, roots, failure, components
from twisted import copyright
from twisted.cred import util
from twisted.persisted import styles
# Sibling Imports
import error, resource
from twisted.web import util as webutil
# backwards compatability
date_time_string = http.datetimeToString
string_date_time = http.stringToDatetime
# Support for other methods may be implemented on a per-resource basis.
supportedMethods = ('GET', 'HEAD', 'POST')
class UnsupportedMethod(Exception):
"""Raised by a resource when faced with a strange request method.
RFC 2616 (HTTP 1.1) gives us two choices when faced with this situtation:
If the type of request is known to us, but not allowed for the requested
resource, respond with NOT_ALLOWED. Otherwise, if the request is something
we don't know how to deal with in any case, respond with NOT_IMPLEMENTED.
When this exception is raised by a Resource's render method, the server
will make the appropriate response.
This exception's first argument MUST be a sequence of the methods the
resource *does* support.
"""
allowedMethods = ()
def __init__(self, allowedMethods, *args):
Exception.__init__(self, allowedMethods, *args)
self.allowedMethods = allowedMethods
if not operator.isSequenceType(allowedMethods):
why = "but my first argument is not a sequence."
s = ("First argument must be a sequence of"
" supported methods, %s" % (why,))
raise TypeError, s
def _addressToTuple(addr):
if isinstance(addr, address.IPv4Address):
return ('INET', addr.host, addr.port)
elif isinstance(addr, address.UNIXAddress):
return ('UNIX', addr.name)
else:
return tuple(addr)
class Request(pb.Copyable, http.Request, components.Componentized):
site = None
appRootURL = None
__pychecker__ = 'unusednames=issuer'
def __init__(self, *args, **kw):
http.Request.__init__(self, *args, **kw)
components.Componentized.__init__(self)
self.notifications = []
def getStateToCopyFor(self, issuer):
x = self.__dict__.copy()
del x['transport']
# XXX refactor this attribute out; it's from protocol
# del x['server']
del x['channel']
del x['content']
del x['site']
self.content.seek(0, 0)
x['content_data'] = self.content.read()
x['remote'] = pb.ViewPoint(issuer, self)
# Address objects aren't jellyable
x['host'] = _addressToTuple(x['host'])
x['client'] = _addressToTuple(x['client'])
return x
# HTML generation helpers
def sibLink(self, name):
"Return the text that links to a sibling of the requested resource."
if self.postpath:
return (len(self.postpath)*"../") + name
else:
return name
def childLink(self, name):
"Return the text that links to a child of the requested resource."
lpp = len(self.postpath)
if lpp > 1:
return ((lpp-1)*"../") + name
elif lpp == 1:
return name
else: # lpp == 0
if len(self.prepath) and self.prepath[-1]:
return self.prepath[-1] + '/' + name
else:
return name
def process(self):
"Process a request."
# get site from channel
self.site = self.channel.site
# set various default headers
self.setHeader('server', version)
self.setHeader('date', http.datetimeToString())
self.setHeader('content-type', "text/html")
# Resource Identification
self.prepath = []
self.postpath = map(unquote, string.split(self.path[1:], '/'))
try:
resrc = self.site.getResourceFor(self)
self.render(resrc)
except:
self.processingFailed(failure.Failure())
def render(self, resrc):
try:
body = resrc.render(self)
except UnsupportedMethod, e:
allowedMethods = e.allowedMethods
if (self.method == "HEAD") and ("GET" in allowedMethods):
# We must support HEAD (RFC 2616, 5.1.1). If the
# resource doesn't, fake it by giving the resource
# a 'GET' request and then return only the headers,
# not the body.
log.msg("Using GET to fake a HEAD request for %s" %
(resrc,))
self.method = "GET"
body = resrc.render(self)
if body is NOT_DONE_YET:
log.msg("Tried to fake a HEAD request for %s, but "
"it got away from me." % resrc)
# Oh well, I guess we won't include the content length.
else:
self.setHeader('content-length', str(len(body)))
self.write('')
self.finish()
return
if self.method in (supportedMethods):
# We MUST include an Allow header
# (RFC 2616, 10.4.6 and 14.7)
self.setHeader('Allow', allowedMethods)
s = ('''Your browser approached me (at %(URI)s) with'''
''' the method "%(method)s". I only allow'''
''' the method%(plural)s %(allowed)s here.''' % {
'URI': self.uri,
'method': self.method,
'plural': ((len(allowedMethods) > 1) and 's') or '',
'allowed': string.join(allowedMethods, ', ')
})
epage = error.ErrorPage(http.NOT_ALLOWED,
"Method Not Allowed", s)
body = epage.render(self)
else:
epage = error.ErrorPage(http.NOT_IMPLEMENTED, "Huh?",
"""I don't know how to treat a"""
""" %s request."""
% (self.method))
body = epage.render(self)
# end except UnsupportedMethod
if body == NOT_DONE_YET:
return
if type(body) is not types.StringType:
body = error.ErrorPage(http.INTERNAL_SERVER_ERROR,
"Request did not return a string",
"Request: "+html.PRE(reflect.safe_repr(self))+"<br />"+
"Resource: "+html.PRE(reflect.safe_repr(resrc))+"<br />"+
"Value: "+html.PRE(reflect.safe_repr(body))).render(self)
if self.method == "HEAD":
if len(body) > 0:
# This is a Bad Thing (RFC 2616, 9.4)
log.msg("Warning: HEAD request %s for resource %s is"
" returning a message body."
" I think I'll eat it."
% (self, resrc))
self.setHeader('content-length', str(len(body)))
self.write('')
else:
self.setHeader('content-length', str(len(body)))
self.write(body)
self.finish()
def processingFailed(self, reason):
log.err(reason)
if self.site.displayTracebacks:
body = ("<html><head><title>web.Server Traceback (most recent call last)</title></head>"
"<body><b>web.Server Traceback (most recent call last):</b>\n\n"
"%s\n\n</body></html>\n"
% webutil.formatFailure(reason))
else:
body = ("<html><head><title>Processing Failed</title></head><body>"
"<b>Processing Failed</b></body></html>")
self.setResponseCode(http.INTERNAL_SERVER_ERROR)
self.setHeader('content-type',"text/html")
self.setHeader('content-length', str(len(body)))
self.write(body)
self.finish()
return reason
def notifyFinish(self):
"""Notify when finishing the request
@return: A deferred. The deferred will be triggered when the
request is finished -- with a C{None} value if the request
finishes successfully or with an error if the request is stopped
by the client.
"""
self.notifications.append(defer.Deferred())
return self.notifications[-1]
def connectionLost(self, reason):
for d in self.notifications:
d.errback(reason)
self.notifications = []
def finish(self):
http.Request.finish(self)
for d in self.notifications:
d.callback(None)
self.notifications = []
def view_write(self, issuer, data):
"""Remote version of write; same interface.
"""
self.write(data)
def view_finish(self, issuer):
"""Remote version of finish; same interface.
"""
self.finish()
def view_addCookie(self, issuer, k, v, **kwargs):
"""Remote version of addCookie; same interface.
"""
self.addCookie(k, v, **kwargs)
def view_setHeader(self, issuer, k, v):
"""Remote version of setHeader; same interface.
"""
self.setHeader(k, v)
def view_setLastModified(self, issuer, when):
"""Remote version of setLastModified; same interface.
"""
self.setLastModified(when)
def view_setETag(self, issuer, tag):
"""Remote version of setETag; same interface.
"""
self.setETag(tag)
def view_setResponseCode(self, issuer, code):
"""Remote version of setResponseCode; same interface.
"""
self.setResponseCode(code)
def view_registerProducer(self, issuer, producer, streaming):
"""Remote version of registerProducer; same interface.
(requires a remote producer.)
"""
self.registerProducer(_RemoteProducerWrapper(producer), streaming)
def view_unregisterProducer(self, issuer):
self.unregisterProducer()
### these calls remain local
session = None
def getSession(self, sessionInterface = None):
# Session management
if not self.session:
cookiename = string.join(['TWISTED_SESSION'] + self.sitepath, "_")
sessionCookie = self.getCookie(cookiename)
if sessionCookie:
try:
self.session = self.site.getSession(sessionCookie)
except KeyError:
pass
# if it still hasn't been set, fix it up.
if not self.session:
self.session = self.site.makeSession()
self.addCookie(cookiename, self.session.uid, path='/')
self.session.touch()
if sessionInterface:
return self.session.getComponent(sessionInterface)
return self.session
def _prePathURL(self, prepath):
port = self.getHost().port
if self.isSecure():
default = 443
else:
default = 80
if port == default:
hostport = ''
else:
hostport = ':%d' % port
return quote('http%s://%s%s/%s' % (
self.isSecure() and 's' or '',
self.getRequestHostname(),
hostport,
string.join(prepath, '/')), "/:")
def prePathURL(self):
return self._prePathURL(self.prepath)
def URLPath(self):
from twisted.python import urlpath
return urlpath.URLPath.fromRequest(self)
def rememberRootURL(self):
"""
Remember the currently-processed part of the URL for later
recalling.
"""
url = self._prePathURL(self.prepath[:-1])
self.appRootURL = url
def getRootURL(self):
"""
Get a previously-remembered URL.
"""
return self.appRootURL
class _RemoteProducerWrapper:
def __init__(self, remote):
self.resumeProducing = remote.remoteMethod("resumeProducing")
self.pauseProducing = remote.remoteMethod("pauseProducing")
self.stopProducing = remote.remoteMethod("stopProducing")
class Session(components.Componentized):
"""A user's session with a system.
This utility class contains no functionality, but is used to
represent a session.
"""
def __init__(self, site, uid):
"""Initialize a session with a unique ID for that session.
"""
components.Componentized.__init__(self)
self.site = site
self.uid = uid
self.expireCallbacks = []
self.checkExpiredLoop = task.LoopingCall(self.checkExpired)
self.touch()
self.sessionNamespaces = {}
def notifyOnExpire(self, callback):
"""Call this callback when the session expires or logs out.
"""
self.expireCallbacks.append(callback)
def expire(self):
"""Expire/logout of the session.
"""
#log.msg("expired session %s" % self.uid)
del self.site.sessions[self.uid]
for c in self.expireCallbacks:
c()
self.expireCallbacks = []
self.checkExpiredLoop.stop()
# Break reference cycle.
self.checkExpiredLoop = None
def touch(self):
self.lastModified = time.time()
def checkExpired(self):
"""Is it time for me to expire?
If I haven't been touched in fifteen minutes, I will call my
expire method.
"""
# If I haven't been touched in 15 minutes:
if time.time() - self.lastModified > 900:
if self.site.sessions.has_key(self.uid):
self.expire()
version = "TwistedWeb/%s" % copyright.version
class Site(http.HTTPFactory):
counter = 0
requestFactory = Request
displayTracebacks = True
def __init__(self, resource, logPath=None, timeout=60*60*12):
"""Initialize.
"""
http.HTTPFactory.__init__(self, logPath=logPath, timeout=timeout)
self.sessions = {}
self.resource = resource
def _openLogFile(self, path):
from twisted.python import logfile
return logfile.LogFile(os.path.basename(path), os.path.dirname(path))
def __getstate__(self):
d = self.__dict__.copy()
d['sessions'] = {}
return d
def _mkuid(self):
"""(internal) Generate an opaque, unique ID for a user's session.
"""
import md5, random
self.counter = self.counter + 1
return md5.new("%s_%s" % (str(random.random()) , str(self.counter))).hexdigest()
def makeSession(self):
"""Generate a new Session instance, and store it for future reference.
"""
uid = self._mkuid()
session = self.sessions[uid] = Session(self, uid)
session.checkExpiredLoop.start(1800)
return session
def getSession(self, uid):
"""Get a previously generated session, by its unique ID.
This raises a KeyError if the session is not found.
"""
return self.sessions[uid]
def buildProtocol(self, addr):
"""Generate a channel attached to this site.
"""
channel = http.HTTPFactory.buildProtocol(self, addr)
channel.requestFactory = self.requestFactory
channel.site = self
return channel
isLeaf = 0
def render(self, request):
"""Redirect because a Site is always a directory.
"""
request.redirect(request.prePathURL() + '/')
request.finish()
def getChildWithDefault(self, pathEl, request):
"""Emulate a resource's getChild method.
"""
request.site = self
return self.resource.getChildWithDefault(pathEl, request)
def getResourceFor(self, request):
"""Get a resource for a request.
This iterates through the resource heirarchy, calling
getChildWithDefault on each resource it finds for a path element,
stopping when it hits an element where isLeaf is true.
"""
request.site = self
# Sitepath is used to determine cookie names between distributed
# servers and disconnected sites.
request.sitepath = copy.copy(request.prepath)
return resource.getChildForRequest(self.resource, request)
import html | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/server.py | server.py |
from __future__ import nested_scopes
__version__ = "$Revision: 1.91 $"[11:-2]
# Sibling imports
import interfaces
import utils
import controller
from utils import doSendPage
import model
# Twisted imports
from twisted.internet import defer
from twisted.python import components
from twisted.python import log
from twisted.web import resource, microdom, html, error
from twisted.web.server import NOT_DONE_YET
from zope.interface import implements
try:
import cPickle as pickle
except ImportError:
import pickle
import os
import sys
import stat
import warnings
import types
def peek(stack):
if stack is None:
return None
it = None
while it is None and stack is not None:
it, stack = stack
return it
def poke(stack, new):
it, stack = stack
return (new, stack)
def filterStack(stack):
returnVal = []
while stack is not None:
it, stack = stack
if it is not None:
returnVal.append(it)
return returnVal
def viewFactory(viewClass):
return lambda request, node, model: viewClass(model)
def viewMethod(viewClass):
return lambda self, request, node, model: viewClass(model)
templateCache = {}
class View:
implements(resource.IResource, interfaces.IView)
# wvfactory_xxx method signature: request, node, model; returns Widget
# wvupdate_xxx method signature: request, widget, data; mutates widget
# based on data (not necessarily an IModel;
# has been unwrapped at this point)
wantsAllNotifications = 0
templateFile = ''
templateDirectory = ''
template = ''
isLeaf = 1
def getChild(self, path, request):
return error.NoResource("No such child resource.")
def getChildWithDefault(self, path, request):
return self.getChild(path, request)
viewLibraries = []
setupStacks = 1
livePage = 0
doneCallback = None
templateNode = None
def __init__(self, m, templateFile=None, templateDirectory=None, template=None, controller=None, doneCallback=None, modelStack=None, viewStack=None, controllerStack=None):
"""
A view must be told what its model is, and may be told what its
controller is, but can also look up its controller if none specified.
"""
if not interfaces.IModel.providedBy(m):
m = model.adaptToIModel(m, None, None)
self.model = self.mainModel = m
# It's the responsibility of the calling code to make sure
# setController is called on this view before it's rendered.
self.controller = None
self.subviews = {}
if self.setupStacks:
self.modelStack = None
self.viewStack = None
self.controllerStack = None
if doneCallback is None and self.doneCallback is None:
self.doneCallback = doSendPage
else:
print "DoneCallback", doneCallback
self.doneCallback = doneCallback
if template is not None:
self.template = template
if templateFile is not None:
self.templateFile = templateFile
if templateDirectory is not None:
self.templateDirectory = templateDirectory
self.outstandingCallbacks = 0
self.outstandingNodes = []
self.failed = 0
self.setupMethods = []
def setupAllStacks(self):
self.modelStack = (self.model, None)
self.controllerStack = (self.controller, (input, None))
self.setupViewStack()
def setUp(self, request, d):
pass
def setupViewStack(self):
self.viewStack = None
if widgets not in self.viewLibraries:
self.viewLibraries.append(widgets)
for library in self.viewLibraries:
if not hasattr(library, 'getSubview'):
library.getSubview = utils.createGetFunction(library)
self.viewStack = (library, self.viewStack)
self.viewStack = (self, self.viewStack)
def importViewLibrary(self, namespace):
self.viewLibraries.append(namespace)
return self
def render(self, request, doneCallback=None):
if not getattr(request, 'currentId', 0):
request.currentId = 0
request.currentPage = self
if self.controller is None:
self.controller = controller.Controller(self.model)
if doneCallback is not None:
self.doneCallback = doneCallback
else:
self.doneCallback = doSendPage
self.setupAllStacks()
template = self.getTemplate(request)
if template:
self.d = microdom.parseString(template, caseInsensitive=0, preserveCase=0)
else:
if not self.templateFile:
raise AttributeError, "%s does not define self.templateFile to operate on" % self.__class__
self.d = self.lookupTemplate(request)
request.d = self.d
self.handleDocument(request, self.d)
return NOT_DONE_YET
def getTemplate(self, request):
"""
Override this if you want to have your subclass look up its template
using a different method.
"""
return self.template
def lookupTemplate(self, request):
"""
Use acquisition to look up the template named by self.templateFile,
located anywhere above this object in the heirarchy, and use it
as the template. The first time the template is used it is cached
for speed.
"""
if self.template:
return microdom.parseString(self.template, caseInsensitive=0, preserveCase=0)
if not self.templateDirectory:
mod = sys.modules[self.__module__]
if hasattr(mod, '__file__'):
self.templateDirectory = os.path.split(mod.__file__)[0]
# First see if templateDirectory + templateFile is a file
templatePath = os.path.join(self.templateDirectory, self.templateFile)
if not os.path.exists(templatePath):
raise RuntimeError, "The template %r was not found." % templatePath
# Check to see if there is an already parsed copy of it
mtime = os.path.getmtime(templatePath)
cachedTemplate = templateCache.get(templatePath, None)
compiledTemplate = None
if cachedTemplate is not None:
if cachedTemplate[0] == mtime:
compiledTemplate = templateCache[templatePath][1].cloneNode(deep=1)
if compiledTemplate is None:
compiledTemplate = microdom.parse(templatePath, caseInsensitive=0, preserveCase=0)
templateCache[templatePath] = (mtime, compiledTemplate.cloneNode(deep=1))
return compiledTemplate
def handleDocument(self, request, document):
"""Handle the root node, and send the page if there are no
outstanding callbacks when it returns.
"""
try:
request.d = document
self.setUp(request, document)
# Don't let outstandingCallbacks get to 0 until the
# entire tree has been recursed
# If you don't do this, and any callback has already
# completed by the time the dispatchResultCallback
# is added in dispachResult, then sendPage will be
# called prematurely within dispatchResultCallback
# resulting in much gnashing of teeth.
self.outstandingNodes = document.childNodes[:] + [1]
self.outstandingNodes.reverse()
self.outstandingCallbacks += 1
self.handleOutstanding(request)
self.outstandingCallbacks -= 1
if not self.outstandingCallbacks:
return self.sendPage(request)
except:
self.renderFailure(None, request)
def handleOutstanding(self, request):
while self.outstandingNodes:
node = self.outstandingNodes.pop()
if node is 1:
self.modelStack = self.modelStack[1]
self.viewStack = self.viewStack[1]
if self.controllerStack is not None:
controller, self.controllerStack = self.controllerStack
if controller is not None:
controller.exit(request)
attrs = getattr(node, 'attributes', None)
if (attrs is not None and
(attrs.get('model') or attrs.get('view') or attrs.get('controller'))):
self.outstandingNodes.append(1)
self.handleNode(request, node)
else:
if attrs is not None and (attrs.get('view') or attrs.get('controller')):
self.outstandingNodes.append(node)
if hasattr(node, 'childNodes') and node.childNodes:
self.recurseChildren(request, node)
def recurseChildren(self, request, node):
"""If this node has children, handle them.
"""
new = node.childNodes[:]
new.reverse()
self.outstandingNodes.extend(new)
def dispatchResult(self, request, node, result):
"""Check a given result from handling a node and look up a NodeMutator
adapter which will convert the result into a node and insert it
into the DOM tree. Return the new node.
"""
if not isinstance(result, defer.Deferred):
if node.parentNode is not None:
node.parentNode.replaceChild(result, node)
else:
raise RuntimeError, "We're dying here, please report this immediately"
else:
self.outstandingCallbacks += 1
result.addCallback(self.dispatchResultCallback, request, node)
result.addErrback(self.renderFailure, request)
# Got to wait until the callback comes in
return result
def modelChanged(self, changed):
"""Rerender this view, because our model has changed.
"""
# arg. this needs to go away.
request = changed.get('request', None)
oldNode = self.node
#import pdb; pdb.set_trace()
newNode = self.generate(request, oldNode)
returnNode = self.dispatchResult(request, oldNode, newNode)
self.handleNewNode(request, returnNode)
self.handleOutstanding(request)
self.controller.domChanged(request, self, returnNode)
def generate(self, request, node):
"""Allow a view to be used like a widget. Will look up the template
file and return it in place of the incoming node.
"""
newNode = self.lookupTemplate(request).childNodes[0]
newNode.setAttribute('id', 'woven_id_%s' % id(self))
self.node = newNode
return newNode
def setController(self, controller):
self.controller = controller
self.controllerStack = (controller, self.controllerStack)
def setNode(self, node):
if self.templateNode == None:
self.templateNode = node
self.node = node
def setSubmodel(self, name):
self.submodel = name
def getNodeModel(self, request, node, submodel):
"""
Get the model object associated with this node. If this node has a
model= attribute, call getSubmodel on the current model object.
If not, return the top of the model stack.
"""
parent = None
if submodel:
if submodel == '.':
m = peek(self.modelStack)
else:
modelStack = self.modelStack
while modelStack is not None:
parent, modelStack = modelStack
if parent is None:
continue
m = parent.lookupSubmodel(request, submodel)
if m is not None:
#print "model", m
break
else:
raise Exception("Node had a model=%s "
"attribute, but the submodel was not "
"found in %s." % (submodel,
filterStack(self.modelStack)))
else:
m = None
self.modelStack = (m, self.modelStack)
if m is not None:
# print "M NAME", m.name
# if parent is not m:
# m.parent = parent
# if not getattr(m, 'name', None):
# m.name = submodel
return m
#print `submodel`, self.getTopOfModelStack()
if submodel:
return peek(self.modelStack)
return None
def getNodeController(self, request, node, submodel, model):
"""
Get a controller object to handle this node. If the node has no
controller= attribute, first check to see if there is an IController
adapter for our model.
"""
controllerName = node.attributes.get('controller')
controller = None
if model is None:
model = peek(self.modelStack)
# Look up a controller factory.
if controllerName:
#if not node.hasAttribute('name'):
# warnings.warn("POTENTIAL ERROR: %s had a controller, but not a "
# "'name' attribute." % node)
controllerStack = self.controllerStack
while controllerStack is not None:
namespace, controllerStack = controllerStack
if namespace is None:
continue
controller = namespace.getSubcontroller(request, node, model, controllerName)
if controller is not None:
break
else:
raise NotImplementedError("You specified controller name %s on "
"a node, but no wcfactory_%s method "
"was found in %s." % (controllerName,
controllerName,
filterStack(self.controllerStack)
))
elif node.attributes.get("model"):
# If no "controller" attribute was specified on the node, see if
# there is a IController adapter registerred for the model.
controller = interfaces.IController(
model,
None)
return controller
def getSubview(self, request, node, model, viewName):
"""Get a sub-view from me.
@returns: L{widgets.Widget}
"""
view = None
vm = getattr(self, 'wvfactory_' + viewName, None)
if vm is None:
vm = getattr(self, 'factory_' + viewName, None)
if vm is not None:
warnings.warn("factory_ methods are deprecated; please use "
"wvfactory_ instead", DeprecationWarning)
if vm:
if vm.func_code.co_argcount == 3 and not type(vm) == types.LambdaType:
warnings.warn("wvfactory_ methods take (request, node, "
"model) instead of (request, node) now. \n"
"Please instantiate your widgets with a "
"reference to model instead of self.model",
DeprecationWarning)
self.model = model
view = vm(request, node)
self.model = self.mainModel
else:
view = vm(request, node, model)
setupMethod = getattr(self, 'wvupdate_' + viewName, None)
if setupMethod:
if view is None:
view = widgets.Widget(model)
view.setupMethods.append(setupMethod)
return view
def getNodeView(self, request, node, submodel, model):
view = None
viewName = node.attributes.get('view')
if model is None:
model = peek(self.modelStack)
# Look up a view factory.
if viewName:
viewStack = self.viewStack
while viewStack is not None:
namespace, viewStack = viewStack
if namespace is None:
continue
try:
view = namespace.getSubview(request, node, model, viewName)
except AttributeError:
# Was that from something in the viewStack that didn't
# have a getSubview?
if not hasattr(namespace, "getSubview"):
log.msg("Warning: There is no getSubview on %r" %
(namespace,))
continue
else:
# No, something else is really broken.
raise
if view is not None:
break
else:
raise NotImplementedError(
"You specified view name %s on a node %s, but no "
"wvfactory_%s method was found in %s. (Or maybe they were "
"found but they returned None.)" % (
viewName, node, viewName,
filterStack(self.viewStack)))
elif node.attributes.get("model"):
# If no "view" attribute was specified on the node, see if there
# is a IView adapter registerred for the model.
# First, see if the model is Componentized.
if isinstance(model, components.Componentized):
view = model.getAdapter(interfaces.IView)
if not view and hasattr(model, '__class__'):
view = interfaces.IView(model, None)
return view
def handleNode(self, request, node):
submodelName = node.attributes.get('model')
if submodelName is None:
submodelName = ""
model = self.getNodeModel(request, node, submodelName)
view = self.getNodeView(request, node, submodelName, model)
controller = self.getNodeController(request, node, submodelName, model)
if view or controller:
if model is None:
model = peek(self.modelStack)
if not view or not isinstance(view, View):
view = widgets.DefaultWidget(model)
if not controller:
controller = input.DefaultHandler(model)
prevView, stack = self.viewStack
while isinstance(prevView, widgets.DefaultWidget) and stack is not None:
prevView, stack = stack
if prevView is None:
prevMod = None
else:
prevMod = prevView.model
if model is not prevMod and not isinstance(view, widgets.DefaultWidget):
model.addView(view)
submodelList = [x.name for x in filterStack(self.modelStack) if x.name]
submodelList.reverse()
submodelName = '/'.join(submodelList)
if not getattr(view, 'submodel', None):
view.submodel = submodelName
theId = node.attributes.get("id")
if self.livePage and not theId:
theId = "woven_id_%d" % id(view)
view.setupMethods.append(utils.createSetIdFunction(theId))
view.outgoingId = theId
#print "SET AN ID", theId
self.subviews[theId] = view
view.parent = peek(self.viewStack)
view.parent.subviews[theId] = view
# If a Widget was constructed directly with a model that so far
# is not in modelspace, we should put it on the stack so other
# Widgets below this one can find it.
if view.model is not peek(self.modelStack):
self.modelStack = poke(self.modelStack, view.model)
cParent = peek(self.controllerStack)
if controller._parent is None or cParent != controller:
controller._parent = cParent
self.controllerStack = (controller, self.controllerStack)
self.viewStack = (view, self.viewStack)
view.viewStack = self.viewStack
view.controllerStack = self.controllerStack
view.modelStack = self.modelStack
view.setController(controller)
view.setNode(node)
if not getattr(controller, 'submodel', None):
controller.setSubmodel(submodelName)
controller.setView(view)
controller.setNode(node)
controllerResult = controller.handle(request)
if controllerResult is not None:
## It's a deferred
controller
self.outstandingCallbacks += 1
controllerResult.addCallback(
self.handleControllerResults,
request,
node,
controller,
view)
controllerResult.addErrback(self.renderFailure, request)
else:
viewResult = view.generate(request, node)
returnNode = self.dispatchResult(request, node, viewResult)
self.handleNewNode(request, returnNode)
else:
self.controllerStack = (controller, self.controllerStack)
self.viewStack = (view, self.viewStack)
def handleControllerResults(self,
controllerResult, request, node, controller, view):
"""Handle a deferred from a controller.
"""
self.outstandingCallbacks -= 1
if isinstance(controllerResult, defer.Deferred):
self.outstandingCallbacks += 1
controllerResult.addCallback(
self.handleControllerResults,
request,
node,
controller,
view)
controllerResult.addErrback(self.renderFailure, request)
else:
viewResult = view.generate(request, node)
returnNode = self.dispatchResult(request, node, viewResult)
self.handleNewNode(request, returnNode)
return controllerResult
def handleNewNode(self, request, returnNode):
if not isinstance(returnNode, defer.Deferred):
self.recurseChildren(request, returnNode)
else:
# TODO: Need to handle deferreds here?
pass
def sendPage(self, request):
"""
Check to see if handlers recorded any errors before sending the page
"""
self.doneCallback(self, self.d, request)
def setSubviewFactory(self, name, factory, setup=None, *args, **kwargs):
setattr(self, "wvfactory_" + name, lambda request, node, m:
factory(m, *args, **kwargs))
if setup:
setattr(self, "wvupdate_" + name, setup)
def __setitem__(self, key, value):
pass
def unlinkViews(self):
#print "unlinking views"
self.model.removeView(self)
for key, value in self.subviews.items():
value.unlinkViews()
# value.model.removeView(value)
def dispatchResultCallback(self, result, request, node):
"""Deal with a callback from a deferred, checking to see if it is
ok to send the page yet or not.
"""
self.outstandingCallbacks -= 1
#node = self.dispatchResult(request, node, result)
#self.recurseChildren(request, node)
if not self.outstandingCallbacks:
self.sendPage(request)
return result
def renderFailure(self, failure, request):
try:
xml = request.d.toprettyxml()
except:
xml = ""
# if not hasattr(request, 'channel'):
# log.msg("The request got away from me before I could render an error page.")
# log.err(failure)
# return failure
if not self.failed:
self.failed = 1
if failure:
request.write("<html><head><title>%s: %s</title></head><body>\n" % (html.escape(str(failure.type)), html.escape(str(failure.value))))
else:
request.write("<html><head><title>Failure!</title></head><body>\n")
utils.renderFailure(failure, request)
request.write("<h3>Here is the partially processed DOM:</h3>")
request.write("\n<pre>\n")
request.write(html.escape(xml))
request.write("\n</pre>\n")
request.write("</body></html>")
request.finish()
return failure
class LiveView(View):
livePage = 1
def wvfactory_webConduitGlue(self, request, node, m):
if request.getHeader("user-agent").count("MSIE"):
return View(m, templateFile="FlashConduitGlue.html")
else:
return View(m, templateFile="WebConduitGlue.html")
def wvupdate_woven_flashConduitSessionView(self, request, wid, mod):
#print "updating flash thingie"
uid = request.getSession().uid
n = wid.templateNode
if n.attributes.has_key('src'):
n.attributes['src'] = n.attributes.get('src') + '?twisted_session=' + str(uid)
else:
n.attributes['value'] = n.attributes.get('value') + '?twisted_session=' + str(uid)
#print wid.templateNode.toxml()
#backwards compatibility
WView = View
def registerViewForModel(view, model):
"""
Registers `view' as an adapter of `model' for L{interfaces.IView}.
"""
components.registerAdapter(view, model, interfaces.IView)
# adapter = resource.IResource(model, None)
# if adapter is None and resource.IResource.providedBy(view):
# components.registerAdapter(view, model, resource.IResource)
#sibling imports::
# If no widget/handler was found in the container controller or view, these
# modules will be searched.
import input
import widgets | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/woven/view.py | view.py |
from __future__ import nested_scopes
# Twisted Imports
from twisted.python import formmethod, failure
from twisted.python.components import registerAdapter
from twisted.web import domhelpers, resource, util
from twisted.internet import defer
# Sibling Imports
from twisted.web.woven import model, view, controller, widgets, input, interfaces
from twisted.web.microdom import parseString, lmx, Element
#other imports
import math
# map formmethod.Argument to functions that render them:
_renderers = {}
def registerRenderer(argumentClass, renderer):
"""Register a renderer for a given argument class.
The renderer function should act in the same way
as the 'input_XXX' methods of C{FormFillerWidget}.
"""
assert callable(renderer)
global _renderers
_renderers[argumentClass] = renderer
class FormFillerWidget(widgets.Widget):
SPANNING_TYPES = ["hidden", "submit"]
def getValue(self, request, argument):
"""Return value for form input."""
if not self.model.alwaysDefault:
values = request.args.get(argument.name, None)
if values:
try:
return argument.coerce(values[0])
except formmethod.InputError:
return values[0]
return argument.default
def getValues(self, request, argument):
"""Return values for form input."""
if not self.model.alwaysDefault:
values = request.args.get(argument.name, None)
if values:
try:
return argument.coerce(values)
except formmethod.InputError:
return values
return argument.default
def createShell(self, request, node, data):
"""Create a `shell' node that will hold the additional form
elements, if one is required.
"""
return lmx(node).table(border="0")
def input_single(self, request, content, model, templateAttributes={}):
"""
Returns a text input node built based upon the node model.
Optionally takes an already-coded DOM node merges that
information with the model's information. Returns a new (??)
lmx node.
"""
#in a text field, only the following options are allowed (well, more
#are, but they're not supported yet - can add them in later)
attribs = ['type', 'name', 'value', 'size', 'maxlength',
'readonly'] #only MSIE recognizes readonly and disabled
arguments = {}
for attrib in attribs:
#model hints and values override anything in the template
val = model.getHint(attrib, templateAttributes.get(attrib, None))
if val:
arguments[attrib] = str(val)
value = self.getValue(request, model)
if value:
arguments["value"] = str(value)
arguments["type"] = "text" #these are default
arguments["name"] = model.name
return content.input(**arguments)
def input_string(self, request, content, model, templateAttributes={}):
if not templateAttributes.has_key("size"):
templateAttributes["size"] = '60'
return self.input_single(request, content, model, templateAttributes)
input_integer = input_single
input_integerrange = input_single
input_float = input_single
def input_text(self, request, content, model, templateAttributes={}):
r = content.textarea(
cols=str(model.getHint('cols',
templateAttributes.get('cols', '60'))),
rows=str(model.getHint('rows',
templateAttributes.get('rows', '10'))),
name=model.name,
wrap=str(model.getHint('wrap',
templateAttributes.get('wrap', "virtual"))))
r.text(str(self.getValue(request, model)))
return r
def input_hidden(self, request, content, model, templateAttributes={}):
return content.input(type="hidden",
name=model.name,
value=str(self.getValue(request, model)))
def input_submit(self, request, content, model, templateAttributes={}):
arguments = {}
val = model.getHint("onClick", templateAttributes.get("onClick", None))
if val:
arguments["onClick"] = val
arguments["type"] = "submit"
arguments["name"] = model.name
div = content.div()
for tag, value, desc in model.choices:
args = arguments.copy()
args["value"] = tag
div.input(**args)
div.text(" ")
if model.reset:
div.input(type="reset")
return div
def input_choice(self, request, content, model, templateAttributes={}):
# am I not evil? allow onChange js events
arguments = {}
val = model.getHint("onChange", templateAttributes.get("onChange", None))
if val:
arguments["onChange"] = val
arguments["name"] = model.name
s = content.select(**arguments)
default = self.getValues(request, model)
for tag, value, desc in model.choices:
kw = {}
if value in default:
kw = {'selected' : '1'}
s.option(value=tag, **kw).text(desc)
return s
def input_group(self, request, content, model, groupValues, inputType,
templateAttributes={}):
"""
Base code for a group of objects. Checkgroup will use this, as
well as radiogroup. In the attributes, rows means how many rows
the group should be arranged into, cols means how many cols the
group should be arranged into. Columns take precedence over
rows: if both are specified, the output will always generate the
correct number of columns. However, if the number of elements
in the group exceed (or is smaller than) rows*cols, then the
number of rows will be off. A cols attribute of 1 will mean that
all the elements will be listed one underneath another. The
default is a rows attribute of 1: everything listed next to each
other.
"""
rows = model.getHint('rows', templateAttributes.get('rows', None))
cols = model.getHint('cols', templateAttributes.get('cols', None))
if rows:
rows = int(rows)
if cols:
cols = int(cols)
defaults = self.getValues(request, model)
if (rows and rows>1) or (cols and cols>1): #build a table
s = content.table(border="0")
if cols:
breakat = cols
else:
breakat = math.ceil(float(len(groupValues))/rows)
for i in range(0, len(groupValues), breakat):
tr = s.tr()
for j in range(0, breakat):
if i+j >= len(groupValues):
break
tag, value, desc = groupValues[i+j]
kw = {}
if value in defaults:
kw = {'checked' : '1'}
tr.td().input(type=inputType, name=model.name,
value=tag, **kw).text(desc)
else:
s = content.div()
for tag, value, desc in groupValues:
kw = {}
if value in defaults:
kw = {'checked' : '1'}
s.input(type=inputType, name=model.name,
value=tag, **kw).text(desc)
if cols:
s.br()
return s
def input_checkgroup(self, request, content, model, templateAttributes={}):
return self.input_group(request, content, model, model.flags,
"checkbox", templateAttributes)
def input_radiogroup(self, request, content, model, templateAttributes={}):
return self.input_group(request, content, model, model.choices,
"radio", templateAttributes)
#I don't know why they're the same, but they were. So I removed the
#excess code. Maybe someone should look into removing it entirely.
input_flags = input_checkgroup
def input_boolean(self, request, content, model, templateAttributes={}):
kw = {}
if self.getValue(request, model):
kw = {'checked' : '1'}
return content.input(type="checkbox", name=model.name, **kw)
def input_file(self, request, content, model, templateAttributes={}):
kw = {}
for attrib in ['size', 'accept']:
val = model.getHint(attrib, templateAttributes.get(attrib, None))
if val:
kw[attrib] = str(val)
return content.input(type="file", name=model.name, **kw)
def input_date(self, request, content, model, templateAttributes={}):
breakLines = model.getHint('breaklines', 1)
date = self.getValues(request, model)
if date == None:
year, month, day = "", "", ""
else:
year, month, day = date
div = content.div()
div.text("Year: ")
div.input(type="text", size="4", maxlength="4", name=model.name, value=str(year))
if breakLines:
div.br()
div.text("Month: ")
div.input(type="text", size="2", maxlength="2", name=model.name, value=str(month))
if breakLines:
div.br()
div.text("Day: ")
div.input(type="text", size="2", maxlength="2", name=model.name, value=str(day))
return div
def input_password(self, request, content, model, templateAttributes={}):
return content.input(
type="password",
size=str(templateAttributes.get('size', "60")),
name=model.name)
def input_verifiedpassword(self, request, content, model, templateAttributes={}):
breakLines = model.getHint('breaklines', 1)
values = self.getValues(request, model)
if isinstance(values, (str, unicode)):
values = (values, values)
if not values:
p1, p2 = "", ""
elif len(values) == 1:
p1, p2 = values, ""
elif len(values) == 2:
p1, p2 = values
else:
p1, p2 = "", ""
div = content.div()
div.text("Password: ")
div.input(type="password", size="20", name=model.name, value=str(p1))
if breakLines:
div.br()
div.text("Verify: ")
div.input(type="password", size="20", name=model.name, value=str(p2))
return div
def convergeInput(self, request, content, model, templateNode):
name = model.__class__.__name__.lower()
if _renderers.has_key(model.__class__):
imeth = _renderers[model.__class__]
else:
imeth = getattr(self,"input_"+name)
return imeth(request, content, model, templateNode.attributes).node
def createInput(self, request, shell, model, templateAttributes={}):
name = model.__class__.__name__.lower()
if _renderers.has_key(model.__class__):
imeth = _renderers[model.__class__]
else:
imeth = getattr(self,"input_"+name)
if name in self.SPANNING_TYPES:
td = shell.tr().td(valign="top", colspan="2")
return (imeth(request, td, model).node, shell.tr().td(colspan="2").node)
else:
if model.allowNone:
required = ""
else:
required = " *"
tr = shell.tr()
tr.td(align="right", valign="top").text(model.getShortDescription()+":"+required)
content = tr.td(valign="top")
return (imeth(request, content, model).node,
content.div(_class="formDescription"). # because class is a keyword
text(model.getLongDescription()).node)
def setUp(self, request, node, data):
# node = widgets.Widget.generateDOM(self,request,node)
lmn = lmx(node)
if not node.hasAttribute('action'):
lmn['action'] = (request.prepath+request.postpath)[-1]
if not node.hasAttribute("method"):
lmn['method'] = 'post'
lmn['enctype'] = 'multipart/form-data'
self.errorNodes = errorNodes = {} # name: nodes which trap errors
self.inputNodes = inputNodes = {}
for errorNode in domhelpers.findElementsWithAttribute(node, 'errorFor'):
errorNodes[errorNode.getAttribute('errorFor')] = errorNode
argz={}
# list to figure out which nodes are in the template already and which aren't
hasSubmit = 0
argList = self.model.fmethod.getArgs()
for arg in argList:
if isinstance(arg, formmethod.Submit):
hasSubmit = 1
argz[arg.name] = arg
inNodes = domhelpers.findElements(
node,
lambda n: n.tagName.lower() in ('textarea', 'select', 'input',
'div'))
for inNode in inNodes:
t = inNode.getAttribute("type")
if t and t.lower() == "submit":
hasSubmit = 1
if not inNode.hasAttribute("name"):
continue
nName = inNode.getAttribute("name")
if argz.has_key(nName):
#send an empty content shell - we just want the node
inputNodes[nName] = self.convergeInput(request, lmx(),
argz[nName], inNode)
inNode.parentNode.replaceChild(inputNodes[nName], inNode)
del argz[nName]
# TODO:
# * some arg types should only have a single node (text, string, etc)
# * some should have multiple nodes (choice, checkgroup)
# * some have a bunch of ancillary nodes that are possible values (menu, radiogroup)
# these should all be taken into account when walking through the template
if argz:
shell = self.createShell(request, node, data)
# create inputs, in the same order they were passed to us:
for remArg in [arg for arg in argList if argz.has_key(arg.name)]:
inputNode, errorNode = self.createInput(request, shell, remArg)
errorNodes[remArg.name] = errorNode
inputNodes[remArg.name] = inputNode
if not hasSubmit:
lmn.input(type="submit")
class FormErrorWidget(FormFillerWidget):
def setUp(self, request, node, data):
FormFillerWidget.setUp(self, request, node, data)
for k, f in self.model.err.items():
en = self.errorNodes[k]
tn = self.inputNodes[k]
en.setAttribute('class', 'formError')
tn.setAttribute('class', 'formInputError')
en.childNodes[:]=[] # gurfle, CLEAR IT NOW!@#
if isinstance(f, failure.Failure):
f = f.getErrorMessage()
lmx(en).text(str(f))
class FormDisplayModel(model.MethodModel):
def initialize(self, fmethod, alwaysDefault=False):
self.fmethod = fmethod
self.alwaysDefault = alwaysDefault
class FormErrorModel(FormDisplayModel):
def initialize(self, fmethod, args, err):
FormDisplayModel.initialize(self, fmethod)
self.args = args
if isinstance(err, failure.Failure):
err = err.value
if isinstance(err, Exception):
self.err = getattr(err, "descriptions", {})
self.desc = err
else:
self.err = err
self.desc = "Please try again"
def wmfactory_description(self, request):
return str(self.desc)
class _RequestHack(model.MethodModel):
def wmfactory_hack(self, request):
rv = [[str(a), repr(b)] for (a, b)
in request._outDict.items()]
#print 'hack', rv
return rv
class FormProcessor(resource.Resource):
def __init__(self, formMethod, callback=None, errback=None):
resource.Resource.__init__(self)
self.formMethod = formMethod
if callback is None:
callback = self.viewFactory
self.callback = callback
if errback is None:
errback = self.errorViewFactory
self.errback = errback
def getArgs(self, request):
"""Return the formmethod.Arguments.
Overridable hook to allow pre-processing, e.g. if we want to enable
on them depending on one of the inputs.
"""
return self.formMethod.getArgs()
def render(self, request):
outDict = {}
errDict = {}
for methodArg in self.getArgs(request):
valmethod = getattr(self,"mangle_"+
(methodArg.__class__.__name__.lower()), None)
tmpval = request.args.get(methodArg.name)
if valmethod:
# mangle the argument to a basic datatype that coerce will like
tmpval = valmethod(tmpval)
# coerce it
try:
cv = methodArg.coerce(tmpval)
outDict[methodArg.name] = cv
except:
errDict[methodArg.name] = failure.Failure()
if errDict:
# there were problems processing the form
return self.errback(self.errorModelFactory(
request.args, outDict, errDict)).render(request)
else:
try:
if self.formMethod.takesRequest:
outObj = self.formMethod.call(request=request, **outDict)
else:
outObj = self.formMethod.call(**outDict)
except formmethod.FormException, e:
err = request.errorInfo = self.errorModelFactory(
request.args, outDict, e)
return self.errback(err).render(request)
else:
request._outDict = outDict # CHOMP CHOMP!
# I wanted better default behavior for debugging, so I could
# see the arguments passed, but there is no channel for this in
# the existing callback structure. So, here it goes.
if isinstance(outObj, defer.Deferred):
def _ebModel(err):
if err.trap(formmethod.FormException):
mf = self.errorModelFactory(request.args, outDict,
err.value)
return self.errback(mf)
raise err
(outObj
.addCallback(self.modelFactory)
.addCallback(self.callback)
.addErrback(_ebModel))
return util.DeferredResource(outObj).render(request)
else:
return self.callback(self.modelFactory(outObj)).render(
request)
def errorModelFactory(self, args, out, err):
return FormErrorModel(self.formMethod, args, err)
def errorViewFactory(self, m):
v = view.View(m)
v.template = '''
<html>
<head>
<title> Form Error View </title>
<style>
.formDescription {color: green}
.formError {color: red; font-weight: bold}
.formInputError {color: #900}
</style>
</head>
<body>
Error: <span model="description" />
<form model=".">
</form>
</body>
</html>
'''
return v
def modelFactory(self, outObj):
adapt = interfaces.IModel(outObj, outObj)
# print 'factorizing', adapt
return adapt
def viewFactory(self, model):
# return interfaces.IView(model)
if model is None:
bodyStr = '''
<table model="hack" style="background-color: #99f">
<tr pattern="listItem" view="Widget">
<td model="0" style="font-weight: bold">
</td>
<td model="1">
</td>
</tr>
</table>
'''
model = _RequestHack()
else:
bodyStr = '<div model="." />'
v = view.View(model)
v.template = '''
<html>
<head>
<title> Thank You </title>
</head>
<body>
<h1>Thank You for Using Woven</h1>
%s
</body>
</html>
''' % bodyStr
return v
# manglizers
def mangle_single(self, args):
if args:
return args[0]
else:
return ''
mangle_string = mangle_single
mangle_text = mangle_single
mangle_integer = mangle_single
mangle_password = mangle_single
mangle_integerrange = mangle_single
mangle_float = mangle_single
mangle_choice = mangle_single
mangle_boolean = mangle_single
mangle_hidden = mangle_single
mangle_submit = mangle_single
mangle_file = mangle_single
mangle_radiogroup = mangle_single
def mangle_multi(self, args):
if args is None:
return []
return args
mangle_checkgroup = mangle_multi
mangle_flags = mangle_multi
from twisted.python.formmethod import FormMethod
view.registerViewForModel(FormFillerWidget, FormDisplayModel)
view.registerViewForModel(FormErrorWidget, FormErrorModel)
registerAdapter(FormDisplayModel, FormMethod, interfaces.IModel) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/woven/form.py | form.py |
__version__ = "$Revision: 1.13 $"[11:-2]
from zope.interface import Interface
class IModel(Interface):
"""A MVC Model."""
def addView(view):
"""Add a view for the model to keep track of.
"""
def removeView(view):
"""Remove a view that the model no longer should keep track of.
"""
def notify(changed=None):
"""Notify all views that something was changed on me.
Passing a dictionary of {'attribute': 'new value'} in changed
will pass this dictionary to the view for increased performance.
If you don't want to do this, don't, and just use the traditional
MVC paradigm of querying the model for things you're interested
in.
"""
def getData():
"""Return the raw data contained by this Model object, if it is a
wrapper. If not, return self.
"""
def setData(request, data):
"""Set the raw data referenced by this Model object, if it is a
wrapper. This is done by telling our Parent model to setSubmodel
the new data. If this object is not a wrapper, keep the data
around and return it for subsequent getData calls.
"""
def lookupSubmodel(request, submodelPath):
"""Return an IModel implementor for the given submodel path
string. This path may be any number of elements separated
by /. The default implementation splits on "/" and calls
getSubmodel until the path is exhausted. You will not normally
need to override this behavior.
"""
def getSubmodel(request, submodelName):
"""Return an IModel implementor for the submodel named
"submodelName". If this object contains simple data types,
they can be adapted to IModel using
model.adaptToIModel(m, parent, name) before returning.
"""
def setSubmodel(request, submodelName, data):
"""Set the given data as a submodel of this model. The data
need not implement IModel, since getSubmodel should adapt
the data to IModel before returning it.
"""
class IView(Interface):
"""A MVC View"""
def __init__(model, controller=None):
"""A view must be told what its model is, and may be told what its
controller is, but can also look up its controller if none specified.
"""
def modelChanged(changed):
"""Dispatch changed messages to any update_* methods which
may have been defined, then pass the update notification on
to the controller.
"""
def controllerFactory():
"""Hook for subclasses to customize the controller that is associated
with the model associated with this view.
Default behavior: Look up a component that implements IController
for the self.model instance.
"""
def setController(controller):
"""Set the controller that this view is related to."""
def importViewLibrary(moduleOrObject):
"""Import the given object or module into this View's view namespace
stack. If the given object or module has a getSubview function or
method, it will be called when a node has a view="foo" attribute.
If no getSubview method is defined, a default one will be provided
which looks for the literal name in the namespace.
"""
def getSubview(request, node, model, viewName):
"""Look for a view named "viewName" to handle the node "node".
When a node <div view="foo" /> is present in the template, this
method will be called with viewName set to "foo".
Return None if this View doesn't want to provide a Subview for
the given name.
"""
def setSubviewFactory(name, factory, setup=None):
"""Set the callable "factory", which takes a model and should
return a Widget, to be called by the default implementation of
getSubview when the viewName "name" is present in the template.
This would generally be used like this:
view.setSubviewFactory("foo", MyFancyWidgetClass)
This is equivalent to::
def wvfactory_foo(self, request, node, m):
return MyFancyWidgetClass(m)
Which will cause an instance of MyFancyWidgetClass to be
instanciated when template node <div view="foo" /> is encountered.
If setup is passed, it will be passed to new instances returned
from this factory as a setup method. The setup method is called
each time the Widget is generated. Setup methods take (request,
widget, model) as arguments.
This is equivalent to::
def wvupdate_foo(self, request, widget, model):
# whatever you want
"""
def __adapt__(adaptable, default):
if hasattr(adaptable, 'original'):
return IView(adaptable.original, default)
return default
class IController(Interface):
"""A MVC Controller"""
def setView(view):
"""Set the view that this controller is related to.
"""
def importControllerLibrary(moduleOrObject):
"""Import the given object or module into this Controllers's
controller namespace stack. If the given object or module has a
getSubcontroller function or method, it will be called when a node
has a controller="foo" attribute. If no getSubcontroller method is
defined, a default one will be provided which looks for the literal
name in the namespace.
"""
def getSubcontroller(request, node, model, controllerName):
"""Look for a controller named "controllerName" to handle the node
"node". When a node <div controller="foo" /> is present in the
template, this method will be called with controllerName set to "foo".
Return None if this Controller doesn't want to provide a Subcontroller
for the given name.
"""
def setSubcontrollerFactory(name, factory):
"""Set the callable "factory", which takes a model and should
return an InputHandler, to be called by the default implementation of
getSubview when the controllerName "name" is present in the template.
This would generally be used like this::
view.setSubcontrollerFactory("foo", MyFancyInputHandlerClass)
This is equivalent to::
def wcfactory_foo(self, request, node, m):
return MyFancyInputHandlerClass(m)
Which will cause an instance of MyFancyInputHandlerClass to be
instanciated when template node <div controller="foo" /> is
encountered.
"""
def __adapt__(adaptable, default):
if hasattr(adaptable, 'original'):
return IController(adaptable.original, default)
return default
class IWovenLivePage(Interface):
def getCurrentPage():
"""Return the current page object contained in this session.
"""
def setCurrentPage(page):
"""Set the current page object contained in this session.
"""
def sendJavaScript(js):
"""Send "js" to the live page's persistent output conduit for
execution in the browser. If there is no conduit connected yet,
save the js and write it as soon as the output conduit is
connected.
""" | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/woven/interfaces.py | interfaces.py |
#
"""
A simple guard framework for implementing web sites that only need
'Anonymous' vs 'Logged on' distinction, but nothing more.
If you need
- multiple levels of access, or
- multiple-interface applications, or
- anything else more complex than 'Logged on' and 'Not logged on'
you need to use twisted.web.woven.guard directly.
"""
from twisted.cred import portal, checkers as checkerslib
from twisted.web import resource, util
from twisted.web.woven import guard
from zope.interface import implements
class Authenticated:
def __init__(self, name=None):
self.name = name
def __nonzero__(self):
return bool(self.name)
class MarkAuthenticatedResource:
implements(resource.IResource)
isLeaf = False
def __init__(self, resource, name):
self.authenticated = Authenticated(name)
self.resource = resource
def render(self, request):
request.setComponent(Authenticated, self.authenticated)
return self.resource.render(request)
def getChildWithDefault(self, path, request):
request.setComponent(Authenticated, self.authenticated)
return self.resource.getChildWithDefault(path, request)
class MarkingRealm:
implements(portal.IRealm)
def __init__(self, resource, nonauthenticated=None):
self.resource = resource
self.nonauthenticated = (nonauthenticated or
MarkAuthenticatedResource(resource, None))
def requestAvatar(self, avatarId, mind, *interfaces):
if resource.IResource not in interfaces:
raise NotImplementedError("no interface")
if avatarId:
return (resource.IResource,
MarkAuthenticatedResource(self.resource, avatarId),
lambda:None)
else:
return resource.IResource, self.nonauthenticated, lambda:None
def parentRedirect(_):
return util.ParentRedirect()
def guardResource(resource, checkers, callback=parentRedirect, errback=None,
nonauthenticated=None):
myPortal = portal.Portal(MarkingRealm(resource, nonauthenticated))
for checker in checkers+[checkerslib.AllowAnonymousAccess()]:
myPortal.registerChecker(checker)
un = guard.UsernamePasswordWrapper(myPortal,
callback=callback, errback=errback)
return guard.SessionWrapper(un) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/woven/simpleguard.py | simpleguard.py |
from __future__ import nested_scopes
__version__ = "$Revision: 1.13 $"[11:-2]
import warnings
warnings.warn("The tapestry module is deprecated. Use page instead.", DeprecationWarning, 1)
# System Imports
import sys
import os
# Twisted Imports
from twisted.internet.defer import Deferred
from twisted.web.resource import Resource, IResource
from twisted.web.static import redirectTo, addSlash, File, Data
from twisted.web.server import NOT_DONE_YET
from twisted.web import util
from twisted.python.reflect import qual
# Sibling Imports
from twisted.web.woven.view import View
_ChildJuggler = util.DeferredResource
class ModelLoader(Resource):
"""Resource for loading models. (see loadModel)
"""
def __init__(self, parent, templateFile=None):
Resource.__init__(self)
self.parent = parent
self.templateFile = templateFile
def modelClass(self, other):
return other
def getChild(self, path, request):
d = self.loadModel(path, request)
templateFile = (self.templateFile or self.__class__.__name__+'.html')
d.addCallback(
lambda result: self.parent.makeView(self.modelClass(result),
templateFile, 1))
return util.DeferredResource(d)
def loadModelNow(self, path, request):
"""Override this rather than loadModel if your model-loading is
synchronous.
"""
raise NotImplementedError("%s.loadModelNow" % (reflect.qual(self.__class__)))
def loadModel(self, path, request):
"""Load a model, for the given path and request.
@rtype: L{Deferred}
"""
from twisted.internet.defer import execute
return execute(self.loadModelNow, path, request)
from twisted.web import microdom
from twisted.web import domhelpers
class TapestryView(View):
tapestry = None
parentCount = 0
def lookupTemplate(self, request):
fullFile = os.path.join(self.templateDirectory, self.templateFile)
document = microdom.parse(open(fullFile))
if self.tapestry:
return self.tapestry.templateMutate(document, self.parentCount)
return document
class Tapestry(Resource):
"""
I am a top-level aggregation of Woven objects: a full `site' or
`application'.
"""
viewFactory = TapestryView
def __init__(self, templateDirectory, viewFactory=None, metaTemplate=None):
"""
Create a tapestry with a specified template directory.
"""
Resource.__init__(self)
self.templateDirectory = templateDirectory
if viewFactory is not None:
self.viewFactory = viewFactory
if metaTemplate:
self.metaTemplate = microdom.parse(open(
os.path.join(templateDirectory, metaTemplate)))
else:
self.metaTemplate = None
def templateMutate(self, document, parentCount=0):
if self.metaTemplate:
newDoc = self.metaTemplate.cloneNode(1)
if parentCount:
dotdot = parentCount * '../'
for ddname in 'href', 'src', 'action':
for node in domhelpers.findElementsWithAttribute(newDoc, ddname):
node.setAttribute(ddname, dotdot + node.getAttribute(ddname))
ttl = domhelpers.findNodesNamed(newDoc, "title")[0]
ttl2 = domhelpers.findNodesNamed(document, "title")[0]
ttl.childNodes[:] = []
for n in ttl2.childNodes:
ttl.appendChild(n)
body = domhelpers.findElementsWithAttribute(newDoc, "class", "__BODY__")[0]
body2 = domhelpers.findNodesNamed(document, "body")[0]
ndx = body.parentNode.childNodes.index(body)
body.parentNode.childNodes[ndx:ndx+1] = body2.childNodes
for n in body2.childNodes:
n.parentNode = body.parentNode
f = open("garbage.html", "wb")
f.write(newDoc.toprettyxml())
return newDoc
return document
def makeView(self, model, name, parentCount=0):
v = self.viewFactory(model, name)
v.parentCount = parentCount
v.templateDirectory = self.templateDirectory
v.tapestry = self
v.importViewLibrary(self)
return v
def getSubview(self, request, node, model, viewName):
mod = sys.modules[self.__class__.__module__]
# print "I'm getting a subview", mod, viewName
# try just the name
vm = getattr(mod, viewName, None)
if vm:
return vm(model)
# try the name + a V
vn2 = "V"+viewName.capitalize()
vm = getattr(mod, vn2, None)
if vm:
return vm(model)
vm = getattr(self, 'wvfactory_'+viewName, None)
if vm:
return vm(request, node, model)
def render(self, request):
return redirectTo(addSlash(request), request)
def getChild(self, path, request):
if path == '': path = 'index'
path = path.replace(".","_")
cm = getattr(self, "wchild_"+path, None)
if cm:
p = cm(request)
if isinstance(p, Deferred):
return util.DeferredResource(p)
adapter = IResource(p, None)
if adapter is not None:
return adapter
# maybe we want direct support for ModelLoader?
# cl = getattr(self, "wload_"+path, None) #???
return Resource.getChild(self, path, request) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/woven/tapestry.py | tapestry.py |
from __future__ import nested_scopes
__version__ = "$Revision: 1.67 $"[11:-2]
import os
import cgi
import types
from twisted.python import log
from twisted.python import components
from twisted.python import failure
from zope.interface import implements
from twisted.web import resource, server, static
from twisted.web.woven import interfaces, utils
from twisted.web import woven
from twisted.web import microdom
from twisted.web.static import redirectTo, addSlash
import warnings
from time import time as now
def controllerFactory(controllerClass):
return lambda request, node, model: controllerClass(model)
def controllerMethod(controllerClass):
return lambda self, request, node, model: controllerClass(model)
class Controller(resource.Resource):
"""
A Controller which handles to events from the user. Such events
are `web request', `form submit', etc.
I should be the IResource implementor for your Models (and
L{registerControllerForModel} makes this so).
"""
implements(interfaces.IController)
setupStacks = 1
addSlash = 1 # Should this controller add a slash to the url automatically?
controllerLibraries = []
viewFactory = None
templateDirectory = ""
def __init__(self, m, inputhandlers=None, view=None, controllers=None, templateDirectory = None):
#self.start = now()
resource.Resource.__init__(self)
self.model = m
# It's the responsibility of the calling code to make sure setView is
# called on this controller before it's rendered.
self.view = None
self.subcontrollers = []
if self.setupStacks:
self.setupControllerStack()
if inputhandlers is None and controllers is None:
self._inputhandlers = []
elif inputhandlers:
print "The inputhandlers arg is deprecated, please use controllers instead"
self._inputhandlers = inputhandlers
else:
self._inputhandlers = controllers
if templateDirectory is not None:
self.templateDirectory = templateDirectory
self._valid = {}
self._invalid = {}
self._process = {}
self._parent = None
def setupControllerStack(self):
self.controllerStack = utils.Stack([])
from twisted.web.woven import input
if input not in self.controllerLibraries:
self.controllerLibraries.append(input)
for library in self.controllerLibraries:
self.importControllerLibrary(library)
self.controllerStack.push(self)
def importControllerLibrary(self, namespace):
if not hasattr(namespace, 'getSubcontroller'):
namespace.getSubcontroller = utils.createGetFunction(namespace)
self.controllerStack.push(namespace)
def getSubcontroller(self, request, node, model, controllerName):
controller = None
cm = getattr(self, 'wcfactory_' +
controllerName, None)
if cm is None:
cm = getattr(self, 'factory_' +
controllerName, None)
if cm is not None:
warnings.warn("factory_ methods are deprecated; please use "
"wcfactory_ instead", DeprecationWarning)
if cm:
if cm.func_code.co_argcount == 1 and not type(cm) == types.LambdaType:
warnings.warn("A Controller Factory takes "
"(request, node, model) "
"now instead of (model)", DeprecationWarning)
controller = controllerFactory(model)
else:
controller = cm(request, node, model)
return controller
def setSubcontrollerFactory(self, name, factory, setup=None):
setattr(self, "wcfactory_" + name, lambda request, node, m:
factory(m))
def setView(self, view):
self.view = view
def setNode(self, node):
self.node = node
def setUp(self, request, *args):
"""
@type request: L{twisted.web.server.Request}
"""
pass
def getChild(self, name, request):
"""
Look for a factory method to create the object to handle the
next segment of the URL. If a wchild_* method is found, it will
be called to produce the Resource object to handle the next
segment of the path. If a wchild_* method is not found,
getDynamicChild will be called with the name and request.
@param name: The name of the child being requested.
@type name: string
@param request: The HTTP request being handled.
@type request: L{twisted.web.server.Request}
"""
if not name:
method = "index"
else:
method = name.replace('.', '_')
f = getattr(self, "wchild_%s" % method, None)
if f:
return f(request)
else:
child = self.getDynamicChild(name, request)
if child is None:
return resource.Resource.getChild(self, name, request)
else:
return child
def getDynamicChild(self, name, request):
"""
This method is called when getChild cannot find a matching wchild_*
method in the Controller. Override me if you wish to have dynamic
handling of child pages. Should return a Resource if appropriate.
Return None to indicate no resource found.
@param name: The name of the child being requested.
@type name: string
@param request: The HTTP request being handled.
@type request: L{twisted.web.server.Request}
"""
pass
def wchild_index(self, request):
"""By default, we return ourself as the index.
Override this to provide different behavior
for a URL that ends in a slash.
"""
self.addSlash = 0
return self
def render(self, request):
"""
Trigger any inputhandlers that were passed in to this Page,
then delegate to the View for traversing the DOM. Finally,
call gatheredControllers to deal with any InputHandlers that
were constructed from any controller= tags in the
DOM. gatheredControllers will render the page to the browser
when it is done.
"""
if self.addSlash and request.uri.split('?')[0][-1] != '/':
return redirectTo(addSlash(request), request)
# Handle any inputhandlers that were passed in to the controller first
for ih in self._inputhandlers:
ih._parent = self
ih.handle(request)
self._inputhandlers = []
for key, value in self._valid.items():
key.commit(request, None, value)
self._valid = {}
return self.renderView(request)
def makeView(self, model, templateFile=None, parentCount=0):
if self.viewFactory is None:
self.viewFactory = self.__class__
v = self.viewFactory(model, templateFile=templateFile, templateDirectory=self.templateDirectory)
v.parentCount = parentCount
v.tapestry = self
v.importViewLibrary(self)
return v
def renderView(self, request):
if self.view is None:
if self.viewFactory is not None:
self.setView(self.makeView(self.model, None))
else:
self.setView(interfaces.IView(self.model, None))
self.view.setController(self)
return self.view.render(request, doneCallback=self.gatheredControllers)
def gatheredControllers(self, v, d, request):
process = {}
request.args = {}
for key, value in self._valid.items():
key.commit(request, None, value)
process[key.submodel] = value
self.process(request, **process)
#log.msg("Sending page!")
self.pageRenderComplete(request)
utils.doSendPage(v, d, request)
#v.unlinkViews()
#print "Page time: ", now() - self.start
#return view.View.render(self, request, block=0)
def aggregateValid(self, request, input, data):
self._valid[input] = data
def aggregateInvalid(self, request, input, data):
self._invalid[input] = data
def process(self, request, **kwargs):
if kwargs:
log.msg("Processing results: ", kwargs)
def setSubmodel(self, submodel):
self.submodel = submodel
def handle(self, request):
"""
By default, we don't do anything
"""
pass
def exit(self, request):
"""We are done handling the node to which this controller was attached.
"""
pass
def domChanged(self, request, widget, node):
parent = getattr(self, '_parent', None)
if parent is not None:
parent.domChanged(request, widget, node)
def pageRenderComplete(self, request):
"""Override this to recieve notification when the view rendering
process is complete.
"""
pass
WOVEN_PATH = os.path.split(woven.__file__)[0]
class LiveController(Controller):
"""A Controller that encapsulates logic that makes it possible for this
page to be "Live". A live page can have it's content updated after the
page has been sent to the browser, and can translate client-side
javascript events into server-side events.
"""
pageSession = None
def render(self, request):
"""First, check to see if this request is attempting to hook up the
output conduit. If so, do it. Otherwise, unlink the current session's
View from the MVC notification infrastructure, then render the page
normally.
"""
# Check to see if we're hooking up an output conduit
sess = request.getSession(interfaces.IWovenLivePage)
#print "REQUEST.ARGS", request.args
if request.args.has_key('woven_hookupOutputConduitToThisFrame'):
sess.hookupOutputConduit(request)
return server.NOT_DONE_YET
if request.args.has_key('woven_clientSideEventName'):
try:
request.d = microdom.parseString('<xml/>', caseInsensitive=0, preserveCase=0)
eventName = request.args['woven_clientSideEventName'][0]
eventTarget = request.args['woven_clientSideEventTarget'][0]
eventArgs = request.args.get('woven_clientSideEventArguments', [])
#print "EVENT", eventName, eventTarget, eventArgs
return self.clientToServerEvent(request, eventName, eventTarget, eventArgs)
except:
fail = failure.Failure()
self.view.renderFailure(fail, request)
return server.NOT_DONE_YET
# Unlink the current page in this user's session from MVC notifications
page = sess.getCurrentPage()
#request.currentId = getattr(sess, 'currentId', 0)
if page is not None:
page.view.unlinkViews()
sess.setCurrentPage(None)
#print "PAGE SESSION IS NONE"
self.pageSession = None
return Controller.render(self, request)
def clientToServerEvent(self, request, eventName, eventTarget, eventArgs):
"""The client sent an asynchronous event to the server.
Locate the View object targeted by this event and attempt
to call onEvent on it.
"""
sess = request.getSession(interfaces.IWovenLivePage)
self.view = sess.getCurrentPage().view
#request.d = self.view.d
print "clientToServerEvent", eventTarget
target = self.view.subviews[eventTarget]
print "target, parent", target, target.parent
#target.parent = self.view
#target.controller._parent = self
## From the time we call onEvent until it returns, we want all
## calls to IWovenLivePage.sendScript to be appended to this
## list so we can spit them out in the response, immediately
## below.
scriptOutput = []
orig = sess.sendScript
sess.sendScript = scriptOutput.append
target.onEvent(request, eventName, *eventArgs)
sess.sendScript = orig
scriptOutput.append('parent.woven_clientToServerEventComplete()')
#print "GATHERED JS", scriptOutput
return '''<html>
<body>
<script language="javascript">
%s
</script>
%s event sent to %s (%s) with arguments %s.
</body>
</html>''' % ('\n'.join(scriptOutput), eventName, cgi.escape(str(target)), eventTarget, eventArgs)
def gatheredControllers(self, v, d, request):
Controller.gatheredControllers(self, v, d, request)
sess = request.getSession(interfaces.IWovenLivePage)
self.pageSession = sess
sess.setCurrentPage(self)
sess.currentId = request.currentId
def domChanged(self, request, widget, node):
sess = request.getSession(interfaces.IWovenLivePage)
print "domchanged"
if sess is not None:
if not hasattr(node, 'getAttribute'):
return
page = sess.getCurrentPage()
if page is None:
return
nodeId = node.getAttribute('id')
#logger.warn("DOM for %r is changing to %s", nodeId, node.toprettyxml())
nodeXML = node.toxml()
nodeXML = nodeXML.replace("\\", "\\\\")
nodeXML = nodeXML.replace("'", "\\'")
nodeXML = nodeXML.replace('"', '\\"')
nodeXML = nodeXML.replace('\n', '\\n')
nodeXML = nodeXML.replace('\r', ' ')
nodeXML = nodeXML.replace('\b', ' ')
nodeXML = nodeXML.replace('\t', ' ')
nodeXML = nodeXML.replace('\000', ' ')
nodeXML = nodeXML.replace('\v', ' ')
nodeXML = nodeXML.replace('\f', ' ')
js = "parent.woven_replaceElement('%s', '%s')" % (nodeId, nodeXML)
#for key in widget.subviews.keys():
# view.subviews[key].unlinkViews()
oldNode = page.view.subviews[nodeId]
for id, subview in oldNode.subviews.items():
subview.unlinkViews()
topSubviews = page.view.subviews
#print "Widgetid, subviews", id(widget), widget.subviews
if widget.subviews:
def recurseSubviews(w):
#print "w.subviews", w.subviews
topSubviews.update(w.subviews)
for id, sv in w.subviews.items():
recurseSubviews(sv)
#print "recursing"
recurseSubviews(widget)
#page.view.subviews.update(widget.subviews)
sess.sendScript(js)
def wchild_WebConduit2_js(self, request):
#print "returning js file"
h = request.getHeader("user-agent")
if h.count("MSIE"):
fl = "WebConduit2_msie.js"
else:
fl = "WebConduit2_mozilla.js"
return static.File(os.path.join(WOVEN_PATH, fl))
def wchild_FlashConduit_swf(self, request):
#print "returning flash file"
h = request.getHeader("user-agent")
if h.count("MSIE"):
fl = "FlashConduit.swf"
else:
fl = "FlashConduit.swf"
return static.File(os.path.join(WOVEN_PATH, fl))
def wchild_input_html(self, request):
return BlankPage()
class BlankPage(resource.Resource):
def render(self, request):
return "<html>This space intentionally left blank</html>"
WController = Controller
def registerControllerForModel(controller, model):
"""
Registers `controller' as an adapter of `model' for IController, and
optionally registers it for IResource, if it implements it.
@param controller: A class that implements L{interfaces.IController}, usually a
L{Controller} subclass. Optionally it can implement
L{resource.IResource}.
@param model: Any class, but probably a L{twisted.web.woven.model.Model}
subclass.
"""
components.registerAdapter(controller, model, interfaces.IController)
if resource.IResource.implementedBy(controller):
components.registerAdapter(controller, model, resource.IResource) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/woven/controller.py | controller.py |
__version__ = "$Revision: 1.23 $"[11:-2]
from twisted.python import reflect
from twisted.web import resource
from twisted.web.woven import model, view, controller, interfaces, template
class Page(model.MethodModel, controller.Controller, view.View):
"""
@cvar appRoot: Set this to True if you want me to call
request.rememberRootURL() in my getChild, so you can later use
request.getRootURL() to get the URL to this "application"'s root
resource. (You don't have to worry if there will be multiple
instances of this Page involved in a single request; I'll only
call it for the upper-most instance).
"""
appRoot = False
def __init__(self, *args, **kwargs):
templateFile = kwargs.setdefault('templateFile', None)
inputhandlers = kwargs.setdefault('inputhandlers', None)
controllers = kwargs.setdefault('controllers', None)
templateDirectory = kwargs.setdefault('templateDirectory', None)
template = kwargs.setdefault('template', None)
del kwargs['templateFile']
del kwargs['inputhandlers']
del kwargs['controllers']
del kwargs['templateDirectory']
del kwargs['template']
model.Model.__init__(self, *args, **kwargs)
if len(args):
self.model = args[0]
else:
self.model = self
controller.Controller.__init__(self, self.model,
inputhandlers=inputhandlers,
controllers=controllers)
self.view = self
view.View.__init__(self, self.model, controller=self,
templateFile=templateFile,
templateDirectory = templateDirectory,
template = template)
self.controller = self
self.controllerRendered = 0
def getChild(self, name, request):
# Don't call the rememberURL if we already did once; That way
# we can support an idiom of setting appName as a class
# attribue *even if* the same class is used more than once in
# a hierarchy of Pages.
if self.appRoot and not request.getRootURL():
request.rememberRootURL()
return controller.Controller.getChild(self, name, request)
def renderView(self, request):
return view.View.render(self, request,
doneCallback=self.gatheredControllers)
class LivePage(model.MethodModel, controller.LiveController, view.LiveView):
appRoot = False
def __init__(self, m=None, templateFile=None, inputhandlers=None,
templateDirectory=None, controllers=None, *args, **kwargs):
template = kwargs.setdefault('template', None)
del kwargs['template']
model.Model.__init__(self, *args, **kwargs)
if m is None:
self.model = self
else:
self.model = m
controller.LiveController.__init__(self, self.model,
inputhandlers=inputhandlers,
controllers=controllers)
self.view = self
view.View.__init__(self, self.model, controller=self,
templateFile=templateFile,
templateDirectory=templateDirectory,
template=template)
self.controller = self
self.controllerRendered = 0
def getChild(self, name, request):
# Don't call the rememberPath if we already did once; That way
# we can support an idiom of setting appName as a class
# attribue *even if* the same class is used more than once in
# a hierarchy of Pages.
if self.appRoot and not request.getRootURL():
request.rememberRootURL()
return controller.Controller.getChild(self, name, request)
def renderView(self, request):
return view.View.render(self, request,
doneCallback=self.gatheredControllers) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/woven/page.py | page.py |
# system imports
from os.path import join as joinpath
import urllib, os
# sibling imports
import page, model, widgets, view
# twisted imports
from twisted.web.microdom import lmx
from twisted.web.domhelpers import RawText
from twisted.python.filepath import FilePath
from twisted.web.static import File, getTypeAndEncoding
class DirectoryLister(page.Page):
template = '''
<html>
<head>
<title model="header"> </title>
<style>
.even-dir { background-color: #efe0ef }
.even { background-color: #eee }
.odd-dir {background-color: #f0d0ef }
.odd { background-color: #dedede }
.icon { text-align: center }
.listing {
margin-left: auto;
margin-right: auto;
width: 50%;
padding: 0.1em;
}
body { border: 0; padding: 0; margin: 0; background-color: #efefef; }
h1 {padding: 0.1em; background-color: #777; color: white; border-bottom: thin white dashed;}
</style>
</head>
<body>
<h1 model="header"> </h1>
<table view="List" model="listing">
<tr pattern="listHeader">
<th>Filename</th>
<th>Content type</th>
<th>Content encoding</th>
</tr>
<tr class="even" pattern="listItem">
<td><a model="link" view="Link" /></td>
<td model="type" view="Text"></td>
<td model="encoding" view="Text"></td>
</tr>
<tr class="odd" pattern="listItem">
<td><a model="link" view="Link" /></td>
<td model="type" view="Text"></td>
<td model="encoding" view="Text"></td>
</tr>
</table>
</body>
</html>
'''
def __init__(self, pathname, dirs=None,
contentTypes=File.contentTypes,
contentEncodings=File.contentEncodings,
defaultType='text/html'):
self.contentTypes = contentTypes
self.contentEncodings = contentEncodings
self.defaultType = defaultType
# dirs allows usage of the File to specify what gets listed
self.dirs = dirs
self.path = pathname
page.Page.__init__(self)
def wmfactory_listing(self, request):
if self.dirs is None:
directory = os.listdir(self.path)
directory.sort()
else:
directory = self.dirs
files = []; dirs = []
for path in directory:
url = urllib.quote(path, "/")
if os.path.isdir(os.path.join(self.path, path)):
url = url + '/'
dirs.append({'link':{"text": path + "/", "href":url},
'type': '[Directory]', 'encoding': ''})
else:
mimetype, encoding = getTypeAndEncoding(path, self.contentTypes,
self.contentEncodings,
self.defaultType)
files.append({
'link': {"text": path, "href": url},
'type': '[%s]' % mimetype,
'encoding': (encoding and '[%s]' % encoding or '')})
return files + dirs
def wmfactory_header(self, request):
return "Directory listing for %s" % urllib.unquote(request.uri)
def __repr__(self):
return '<DirectoryLister of %r>' % self.path
__str__ = __repr__ | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/woven/dirlist.py | dirlist.py |
from __future__ import nested_scopes
from types import ClassType
from twisted.web import server
from twisted.web import util as webutil
from twisted.web.woven import interfaces
from twisted.python import failure, log, components
from zope.interface import implements
def renderFailure(fail, request):
if not fail:
fail = failure.Failure()
log.err(fail)
request.write(webutil.formatFailure(fail))
#request.finish()
def doSendPage(self, d, request):
page = str(d.toprettyxml())
request.setHeader('content-length', str(len(page)))
request.write(page)
request.finish()
return page
class Script:
type="javascript1.2"
def __init__(self, script):
self.script = script
class WovenLivePage:
implements(interfaces.IWovenLivePage)
currentPage = None
def __init__(self, session):
self.session = session
self.output = None
self.input = None
self.cached = []
self.inputCache = []
def getCurrentPage(self):
"""Return the current page object contained in this session.
"""
return self.currentPage
def setCurrentPage(self, page):
"""Set the current page object contained in this session.
"""
self.currentPage = page
def write(self, text):
"""Write "text" to the live page's persistent output conduit.
If there is no conduit connected yet, save the text and write it
as soon as the output conduit is connected.
"""
if self.output is None:
self.cached.append(text)
print "CACHING", `self.cached`
else:
if isinstance(text, Script):
if hasattr(self.output, 'writeScript'):
self.output.writeScript(text.script)
return
text = '<script language="%s">%s</script>\r\n' % (text.type, text.script)
print "WRITING", text
if text[-1] != '\n':
text += '\n'
self.output.write(text)
def sendScript(self, js):
self.write(Script(js))
if self.output is not None and not getattr(self.output, 'keepalive', None):
print "## woot, teh connection was open"
## Close the connection; the javascript will have to open it again to get the next event.
self.output.finish()
self.output = None
def hookupOutputConduit(self, request):
"""Hook up the given request as the output conduit for this
session.
"""
print "TOOT! WE HOOKED UP OUTPUT!", `self.cached`
self.output = request
for text in self.cached:
self.write(text)
if self.cached:
self.cached = []
if not getattr(self.output, 'keepalive', None):
## Close the connection; the javascript will have to open it again to get the next event.
request.finish()
self.output = None
def unhookOutputConduit(self):
self.output = None
def hookupInputConduit(self, obj):
"""Hook up the given object as the input conduit for this
session.
"""
print "HOOKING UP", self.inputCache
self.input = obj
for text in self.inputCache:
self.pushThroughInputConduit(text)
self.inputCache = []
print "DONE HOOKING", self.inputCache
def pushThroughInputConduit(self, inp):
"""Push some text through the input conduit.
"""
print "PUSHING INPUT", inp
if self.input is None:
self.inputCache.append(inp)
else:
self.input(inp)
class Stack:
def __init__(self, stack=None):
if stack is None:
self.stack = []
else:
self.stack = stack
def push(self, item):
self.stack.insert(0, item)
def pop(self):
if self.stack:
return self.stack.pop(0)
def peek(self):
for x in self.stack:
if x is not None:
return x
def poke(self, item):
self.stack[0] = item
def clone(self):
return Stack(self.stack[:])
def __len__(self):
return len(self.stack)
def __getitem__(self, item):
return self.stack[item]
class GetFunction:
def __init__(self, namespace):
self.namespace = namespace
def __call__(self, request, node, model, viewName):
"""Get a name from my namespace.
"""
from twisted.web.woven import widgets
if viewName == "None":
return widgets.DefaultWidget(model)
vc = getattr(self.namespace, viewName, None)
# don't call modules and random crap in the namespace, only widgets
if vc and isinstance(vc, (type, ClassType)) and issubclass(vc, widgets.Widget):
return vc(model)
def createGetFunction(namespace):
return GetFunction(namespace)
class SetId:
def __init__(self, theId):
self.theId = theId
def __call__(self, request, wid, data):
id = wid.attributes.get('id', None)
if not id:
wid.setAttribute('id', self.theId)
else:
top = wid
while getattr(top, 'parent', None) is not None:
top = top.parent
if top.subviews.has_key(self.theId):
del top.subviews[self.theId]
top.subviews[id] = wid
if wid.parent.subviews.has_key(self.theId):
del wid.parent.subviews[self.theId]
wid.parent.subviews[id] = wid
def createSetIdFunction(theId):
return SetId(theId)
components.registerAdapter(WovenLivePage, server.Session, interfaces.IWovenLivePage) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/woven/utils.py | utils.py |
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
#
"""Resource protection for Woven. If you wish to use twisted.cred to protect
your Woven application, you are probably most interested in
L{UsernamePasswordWrapper}.
"""
from __future__ import nested_scopes
__version__ = "$Revision: 1.34 $"[11:-2]
import random
import time
import md5
import urllib
# Twisted Imports
from twisted.python import log, components
from twisted.web.resource import Resource, IResource
from twisted.web.util import redirectTo, Redirect, DeferredResource
from twisted.web.static import addSlash
from twisted.internet import reactor
from twisted.cred.error import LoginFailed, UnauthorizedLogin
def _sessionCookie():
return md5.new("%s_%s" % (str(random.random()) , str(time.time()))).hexdigest()
class GuardSession(components.Componentized):
"""A user's session with a system.
This utility class contains no functionality, but is used to
represent a session.
"""
def __init__(self, guard, uid):
"""Initialize a session with a unique ID for that session.
"""
components.Componentized.__init__(self)
self.guard = guard
self.uid = uid
self.expireCallbacks = []
self.checkExpiredID = None
self.setLifetime(60)
self.services = {}
self.portals = {}
self.touch()
def _getSelf(self, interface=None):
self.touch()
if interface is None:
return self
else:
return self.getComponent(interface)
# Old Guard interfaces
def clientForService(self, service):
x = self.services.get(service)
if x:
return x[1]
else:
return x
def setClientForService(self, ident, perspective, client, service):
if self.services.has_key(service):
p, c, i = self.services[service]
p.detached(c, ident)
del self.services[service]
else:
self.services[service] = perspective, client, ident
perspective.attached(client, ident)
# this return value is useful for services that need to do asynchronous
# stuff.
return client
# New Guard Interfaces
def resourceForPortal(self, port):
return self.portals.get(port)
def setResourceForPortal(self, rsrc, port, logout):
self.portalLogout(port)
self.portals[port] = rsrc, logout
return rsrc
def portalLogout(self, port):
p = self.portals.get(port)
if p:
r, l = p
try: l()
except: log.err()
del self.portals[port]
# timeouts and expiration
def setLifetime(self, lifetime):
"""Set the approximate lifetime of this session, in seconds.
This is highly imprecise, but it allows you to set some general
parameters about when this session will expire. A callback will be
scheduled each 'lifetime' seconds, and if I have not been 'touch()'ed
in half a lifetime, I will be immediately expired.
"""
self.lifetime = lifetime
def notifyOnExpire(self, callback):
"""Call this callback when the session expires or logs out.
"""
self.expireCallbacks.append(callback)
def expire(self):
"""Expire/logout of the session.
"""
log.msg("expired session %s" % self.uid)
del self.guard.sessions[self.uid]
for c in self.expireCallbacks:
try:
c()
except:
log.err()
self.expireCallbacks = []
if self.checkExpiredID:
self.checkExpiredID.cancel()
self.checkExpiredID = None
def touch(self):
self.lastModified = time.time()
def checkExpired(self):
self.checkExpiredID = None
# If I haven't been touched in 15 minutes:
if time.time() - self.lastModified > self.lifetime / 2:
if self.guard.sessions.has_key(self.uid):
self.expire()
else:
log.msg("no session to expire: %s" % self.uid)
else:
log.msg("session given the will to live for %s more seconds" % self.lifetime)
self.checkExpiredID = reactor.callLater(self.lifetime,
self.checkExpired)
def __getstate__(self):
d = self.__dict__.copy()
if d.has_key('checkExpiredID'):
del d['checkExpiredID']
return d
def __setstate__(self, d):
self.__dict__.update(d)
self.touch()
self.checkExpired()
INIT_SESSION = 'session-init'
def _setSession(wrap, req, cook):
req.session = wrap.sessions[cook]
req.getSession = req.session._getSelf
def urlToChild(request, *ar, **kw):
pp = request.prepath.pop()
orig = request.prePathURL()
request.prepath.append(pp)
c = '/'.join(ar)
if orig[-1] == '/':
# this SHOULD only happen in the case where the URL is just the hostname
ret = orig + c
else:
ret = orig + '/' + c
args = request.args.copy()
args.update(kw)
if args:
ret += '?'+urllib.urlencode(args)
return ret
def redirectToSession(request, garbage):
rd = Redirect(urlToChild(request, *request.postpath, **{garbage:1}))
rd.isLeaf = 1
return rd
SESSION_KEY='__session_key__'
class SessionWrapper(Resource):
sessionLifetime = 1800
def __init__(self, rsrc, cookieKey=None):
Resource.__init__(self)
self.resource = rsrc
if cookieKey is None:
cookieKey = "woven_session_" + _sessionCookie()
self.cookieKey = cookieKey
self.sessions = {}
def render(self, request):
return redirectTo(addSlash(request), request)
def getChild(self, path, request):
if not request.prepath:
return None
cookie = request.getCookie(self.cookieKey)
setupURL = urlToChild(request, INIT_SESSION, *([path]+request.postpath))
request.setupSessionURL = setupURL
request.setupSession = lambda: Redirect(setupURL)
if path.startswith(SESSION_KEY):
key = path[len(SESSION_KEY):]
if key not in self.sessions:
return redirectToSession(request, '__start_session__')
self.sessions[key].setLifetime(self.sessionLifetime)
if cookie == key:
# /sessionized-url/${SESSION_KEY}aef9c34aecc3d9148/foo
# ^
# we are this getChild
# with a matching cookie
return redirectToSession(request, '__session_just_started__')
else:
# We attempted to negotiate the session but failed (the user
# probably has cookies disabled): now we're going to return the
# resource we contain. In general the getChild shouldn't stop
# there.
# /sessionized-url/${SESSION_KEY}aef9c34aecc3d9148/foo
# ^ we are this getChild
# without a cookie (or with a mismatched cookie)
_setSession(self, request, key)
return self.resource
elif cookie in self.sessions:
# /sessionized-url/foo
# ^ we are this getChild
# with a session
_setSession(self, request, cookie)
return getResource(self.resource, path, request)
elif path == INIT_SESSION:
# initialize the session
# /sessionized-url/session-init
# ^ this getChild
# without a session
newCookie = _sessionCookie()
request.addCookie(self.cookieKey, newCookie, path="/")
sz = self.sessions[newCookie] = GuardSession(self, newCookie)
sz.checkExpired()
rd = Redirect(urlToChild(request, SESSION_KEY+newCookie,
*request.postpath))
rd.isLeaf = 1
return rd
else:
# /sessionized-url/foo
# ^ we are this getChild
# without a session
request.getSession = lambda interface=None: None
return getResource(self.resource, path, request)
def getResource(resource, path, request):
if resource.isLeaf:
request.postpath.insert(0, request.prepath.pop())
return resource
else:
return resource.getChildWithDefault(path, request)
INIT_PERSPECTIVE = 'perspective-init'
DESTROY_PERSPECTIVE = 'perspective-destroy'
from twisted.python import formmethod as fm
from twisted.web.woven import form
newLoginSignature = fm.MethodSignature(
fm.String("username", "",
"Username", "Your user name."),
fm.Password("password", "",
"Password", "Your password."),
fm.Submit("submit", choices=[("Login", "", "")], allowNone=1),
)
from twisted.cred.credentials import UsernamePassword, Anonymous
class UsernamePasswordWrapper(Resource):
"""I bring a C{twisted.cred} Portal to the web. Use me to provide different Resources
(usually entire pages) based on a user's authentication details.
A C{UsernamePasswordWrapper} is a
L{Resource<twisted.web.resource.Resource>}, and is usually wrapped in a
L{SessionWrapper} before being inserted into the site tree.
The L{Realm<twisted.cred.portal.IRealm>} associated with your
L{Portal<twisted.cred.portal.Portal>} should be prepared to accept a
request for an avatar that implements the L{twisted.web.resource.IResource}
interface. This avatar should probably be something like a Woven
L{Page<twisted.web.woven.page.Page>}. That is, it should represent a whole
web page. Once you return this avatar, requests for it's children do not go
through guard.
If you want to determine what unauthenticated users see, make sure your
L{Portal<twisted.cred.portal.Portal>} has a checker associated that allows
anonymous access. (See L{twisted.cred.checkers.AllowAnonymousAccess})
"""
def __init__(self, portal, callback=None, errback=None):
"""Constructs a UsernamePasswordWrapper around the given portal.
@param portal: A cred portal for your web application. The checkers
associated with this portal must be able to accept username/password
credentials.
@type portal: L{twisted.cred.portal.Portal}
@param callback: Gets called after a successful login attempt.
A resource that redirects to "." will display the avatar resource.
If this parameter isn't provided, defaults to a standard Woven
"Thank You" page.
@type callback: A callable that accepts a Woven
L{model<twisted.web.woven.interfaces.IModel>} and returns a
L{IResource<twisted.web.resource.Resource>}.
@param errback: Gets called after a failed login attempt.
If this parameter is not provided, defaults to a the standard Woven
form error (i.e. The original form on a page of its own, with
errors noted.)
@type errback: A callable that accepts a Woven
L{model<twisted.web.woven.interfaces.IModel>} and returns a
L{IResource<twisted.web.resource.Resource>}.
"""
Resource.__init__(self)
self.portal = portal
self.callback = callback
self.errback = errback
def _ebFilter(self, f):
f.trap(LoginFailed, UnauthorizedLogin)
raise fm.FormException(password="Login failed, please enter correct username and password.")
def getChild(self, path, request):
s = request.getSession()
if s is None:
return request.setupSession()
if path == INIT_PERSPECTIVE:
def loginSuccess(result):
interface, avatarAspect, logout = result
s.setResourceForPortal(avatarAspect, self.portal, logout)
def triggerLogin(username, password, submit=None):
return self.portal.login(
UsernamePassword(username, password),
None,
IResource
).addCallback(
loginSuccess
).addErrback(
self._ebFilter
)
return form.FormProcessor(
newLoginSignature.method(
triggerLogin
),
callback=self.callback,
errback=self.errback
)
elif path == DESTROY_PERSPECTIVE:
s.portalLogout(self.portal)
return Redirect(".")
else:
r = s.resourceForPortal(self.portal)
if r:
## Delegate our getChild to the resource our portal says is the right one.
return getResource(r[0], path, request)
else:
return DeferredResource(
self.portal.login(Anonymous(), None, IResource
).addCallback(
lambda (interface, avatarAspect, logout):
getResource(s.setResourceForPortal(avatarAspect,
self.portal, logout),
path, request)))
from twisted.web.woven import interfaces, utils
## Dumb hack until we have an ISession and use interface-to-interface adaption
components.registerAdapter(utils.WovenLivePage, GuardSession, interfaces.IWovenLivePage) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/woven/guard.py | guard.py |
import warnings
try:
import cPickle as pickle
except ImportError:
import pickle
import string, os, sys, stat, types
from twisted.web import microdom
from twisted.python import components
from twisted.web import resource, html
from twisted.web.resource import Resource
from twisted.web.woven import controller, utils, interfaces
from twisted.internet import defer
from twisted.python import failure
from twisted.internet import reactor, defer
from twisted.python import log
from zope.interface import implements, Interface
from twisted.web.server import NOT_DONE_YET
STOP_RENDERING = 1
RESTART_RENDERING = 2
class INodeMutator(Interface):
"""A component that implements NodeMutator knows how to mutate
DOM based on the instructions in the object it wraps.
"""
def generate(request, node):
"""The generate method should do the work of mutating the DOM
based on the object this adapter wraps.
"""
pass
class NodeMutator:
implements(INodeMutator)
def __init__(self, data):
self.data = data
class NodeNodeMutator(NodeMutator):
"""A NodeNodeMutator replaces the node that is passed in to generate
with the node it adapts.
"""
def __init__(self, data):
assert data is not None
NodeMutator.__init__(self, data)
def generate(self, request, node):
if self.data is not node:
parent = node.parentNode
if parent:
parent.replaceChild(self.data, node)
else:
log.msg("Warning: There was no parent for node %s; node not mutated." % node)
return self.data
class NoneNodeMutator(NodeMutator):
def generate(self, request, node):
return node # do nothing
child = request.d.createTextNode("None")
node.parentNode.replaceChild(child, node)
class StringNodeMutator(NodeMutator):
"""A StringNodeMutator replaces the node that is passed in to generate
with the string it adapts.
"""
def generate(self, request, node):
if self.data:
try:
child = microdom.parseString(self.data)
except Exception, e:
log.msg("Error parsing return value, probably invalid xml:", e)
child = request.d.createTextNode(self.data)
else:
child = request.d.createTextNode(self.data)
nodeMutator = NodeNodeMutator(child)
return nodeMutator.generate(request, node)
components.registerAdapter(NodeNodeMutator, microdom.Node, INodeMutator)
components.registerAdapter(NoneNodeMutator, type(None), INodeMutator)
components.registerAdapter(StringNodeMutator, type(""), INodeMutator)
class DOMTemplate(Resource):
"""A resource that renders pages using DOM."""
isLeaf = 1
templateFile = ''
templateDirectory = ''
template = ''
_cachedTemplate = None
def __init__(self, templateFile = None):
"""
@param templateFile: The name of a file containing a template.
@type templateFile: String
"""
Resource.__init__(self)
if templateFile:
self.templateFile = templateFile
self.outstandingCallbacks = 0
self.failed = 0
def render(self, request):
template = self.getTemplate(request)
if template:
self.d = microdom.parseString(template)
else:
if not self.templateFile:
raise AttributeError, "%s does not define self.templateFile to operate on" % self.__class__
self.d = self.lookupTemplate(request)
self.handleDocument(request, self.d)
return NOT_DONE_YET
def getTemplate(self, request):
"""
Override this if you want to have your subclass look up its template
using a different method.
"""
return self.template
def lookupTemplate(self, request):
"""
Use acquisition to look up the template named by self.templateFile,
located anywhere above this object in the heirarchy, and use it
as the template. The first time the template is used it is cached
for speed.
"""
if self.template:
return microdom.parseString(self.template)
if not self.templateDirectory:
mod = sys.modules[self.__module__]
if hasattr(mod, '__file__'):
self.templateDirectory = os.path.split(mod.__file__)[0]
# First see if templateDirectory + templateFile is a file
templatePath = os.path.join(self.templateDirectory, self.templateFile)
# Check to see if there is an already compiled copy of it
templateName = os.path.splitext(self.templateFile)[0]
compiledTemplateName = '.' + templateName + '.pxp'
compiledTemplatePath = os.path.join(self.templateDirectory, compiledTemplateName)
# No? Compile and save it
if (not os.path.exists(compiledTemplatePath) or
os.stat(compiledTemplatePath)[stat.ST_MTIME] < os.stat(templatePath)[stat.ST_MTIME]):
compiledTemplate = microdom.parse(templatePath)
pickle.dump(compiledTemplate, open(compiledTemplatePath, 'wb'), 1)
else:
compiledTemplate = pickle.load(open(compiledTemplatePath, "rb"))
return compiledTemplate
def setUp(self, request, document):
pass
def handleDocument(self, request, document):
"""
Handle the root node, and send the page if there are no
outstanding callbacks when it returns.
"""
try:
request.d = document
self.setUp(request, document)
# Don't let outstandingCallbacks get to 0 until the
# entire tree has been recursed
# If you don't do this, and any callback has already
# completed by the time the dispatchResultCallback
# is added in dispachResult, then sendPage will be
# called prematurely within dispatchResultCallback
# resulting in much gnashing of teeth.
self.outstandingCallbacks += 1
for node in document.childNodes:
request.currentParent = node
self.handleNode(request, node)
self.outstandingCallbacks -= 1
if not self.outstandingCallbacks:
return self.sendPage(request)
except:
self.renderFailure(None, request)
def dispatchResult(self, request, node, result):
"""
Check a given result from handling a node and hand it to a process*
method which will convert the result into a node and insert it
into the DOM tree. Return the new node.
"""
if not isinstance(result, defer.Deferred):
adapter = INodeMutator(result, None)
if adapter is None:
raise NotImplementedError(
"Your factory method returned %s, but there is no "
"INodeMutator adapter registerred for %s." %
(result, getattr(result, "__class__",
None) or type(result)))
result = adapter.generate(request, node)
if isinstance(result, defer.Deferred):
self.outstandingCallbacks += 1
result.addCallback(self.dispatchResultCallback, request, node)
result.addErrback(self.renderFailure, request)
# Got to wait until the callback comes in
return result
def recurseChildren(self, request, node):
"""
If this node has children, handle them.
"""
request.currentParent = node
if not node: return
if type(node.childNodes) == type(""): return
if node.hasChildNodes():
for child in node.childNodes:
self.handleNode(request, child)
def dispatchResultCallback(self, result, request, node):
"""
Deal with a callback from a deferred, dispatching the result
and recursing children.
"""
self.outstandingCallbacks -= 1
node = self.dispatchResult(request, node, result)
self.recurseChildren(request, node)
if not self.outstandingCallbacks:
return self.sendPage(request)
def handleNode(self, request, node):
"""
Handle a single node by looking up a method for it, calling the method
and dispatching the result.
Also, handle all childNodes of this node using recursion.
"""
if not hasattr(node, 'getAttribute'): # text node?
return node
viewName = node.getAttribute('view')
if viewName:
method = getattr(self, "factory_" + viewName, None)
if not method:
raise NotImplementedError, "You specified view name %s on a node, but no factory_%s method was found." % (viewName, viewName)
result = method(request, node)
node = self.dispatchResult(request, node, result)
if not isinstance(node, defer.Deferred):
self.recurseChildren(request, node)
def sendPage(self, request):
"""
Send the results of the DOM mutation to the browser.
"""
page = str(self.d.toxml())
request.write(page)
request.finish()
return page
def renderFailure(self, failure, request):
try:
xml = request.d.toxml()
except:
xml = ""
# if not hasattr(request, 'channel'):
# log.msg("The request got away from me before I could render an error page.")
# log.err(failure)
# return failure
if not self.failed:
self.failed = 1
if failure:
request.write("<html><head><title>%s: %s</title></head><body>\n" % (html.escape(str(failure.type)), html.escape(str(failure.value))))
else:
request.write("<html><head><title>Failure!</title></head><body>\n")
utils.renderFailure(failure, request)
request.write("<h3>Here is the partially processed DOM:</h3>")
request.write("\n<pre>\n")
request.write(html.escape(xml))
request.write("\n</pre>\n")
request.write("</body></html>")
request.finish()
return failure
##########################################
# Deprecation zone
# Wear a hard hat
##########################################
# DOMView is now deprecated since the functionality was merged into domtemplate
DOMView = DOMTemplate
# DOMController is now renamed woven.controller.Controller
class DOMController(controller.Controller, Resource):
"""
A simple controller that automatically passes responsibility on to the view
class registered for the model. You can override render to perform
more advanced template lookup logic.
"""
def __init__(self, *args, **kwargs):
log.msg("DeprecationWarning: DOMController is deprecated; it has been renamed twisted.web.woven.controller.Controller.\n")
controller.Controller.__init__(self, *args, **kwargs)
Resource.__init__(self)
def setUp(self, request):
pass
def render(self, request):
self.setUp(request)
self.view = interfaces.IView(self.model, None)
self.view.setController(self)
return self.view.render(request)
def process(self, request, **kwargs):
log.msg("Processing results: ", kwargs)
return RESTART_RENDERING | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/woven/template.py | template.py |
# DOMWidgets
from __future__ import nested_scopes
import urllib
import warnings
from twisted.web.microdom import parseString, Element, Node
from twisted.web import domhelpers
#sibling imports
import model
import template
import view
import utils
import interfaces
from twisted.python import components, failure
from twisted.python import reflect
from twisted.python import log
from twisted.internet import defer
viewFactory = view.viewFactory
document = parseString("<xml />", caseInsensitive=0, preserveCase=0)
missingPattern = Element("div", caseInsensitive=0, preserveCase=0)
missingPattern.setAttribute("style", "border: dashed red 1px; margin: 4px")
"""
DOMWidgets are views which can be composed into bigger views.
"""
DEBUG = 0
_RAISE = 1
class Dummy:
pass
class Widget(view.View):
"""
A Widget wraps an object, its model, for display. The model can be a
simple Python object (string, list, etc.) or it can be an instance
of L{model.Model}. (The former case is for interface purposes, so that
the rest of the code does not have to treat simple objects differently
from Model instances.)
If the model is-a Model, there are two possibilities:
- we are being called to enable an operation on the model
- we are really being called to enable an operation on an attribute
of the model, which we will call the submodel
@cvar tagName: The tag name of the element that this widget creates. If this
is None, then the original Node will be cloned.
@cvar wantsAllNotifications: Indicate that this widget wants to recieve every
change notification from the main model, not just notifications that affect
its model.
@ivar model: If the current model is an L{model.Model}, then the result of
model.getData(). Otherwise the original object itself.
"""
# wvupdate_xxx method signature: request, widget, data; returns None
# Don't do lots of work setting up my stacks; they will be passed to me
setupStacks = 0
# Should we clear the node before we render the widget?
clearNode = 0
# If some code has to ask if a widget is livePage, the answer is yes
livePage = 1
tagName = None
def __init__(self, model = None, submodel = None, setup = None, controller = None, viewStack=None, *args, **kwargs):
"""
@type model: L{interfaces.IModel}
@param submodel: see L{Widget.setSubmodel}
@type submodel: String
@type setup: Callable
"""
self.errorFactory = Error
self.controller = controller
self.become = None
self._reset()
view.View.__init__(self, model)
self.node = None
self.templateNode = None
if submodel:
self.submodel = submodel
else:
self.submodel = ""
if setup:
self.setupMethods = [setup]
else:
self.setupMethods = []
self.viewStack = viewStack
self.initialize(*args, **kwargs)
def _reset(self):
self.attributes = {}
self.slots = {}
self._children = []
def initialize(self, *args, **kwargs):
"""
Use this method instead of __init__ to initialize your Widget, so you
don't have to deal with calling the __init__ of the superclass.
"""
pass
def setSubmodel(self, submodel):
"""
I use the submodel to know which attribute in self.model I am responsible for
"""
self.submodel = submodel
def getData(self, request=None):
"""
I have a model; however since I am a widget I am only responsible
for a portion of that model. This method returns the portion I am
responsible for.
The return value of this may be a Deferred; if it is, then
L{setData} will be called once the result is available.
"""
return self.model.getData(request)
def setData(self, request=None, data=None):
"""
If the return value of L{getData} is a Deferred, I am called
when the result of the Deferred is available.
"""
self.model.setData(request, data)
def add(self, item):
"""
Add `item' to the children of the resultant DOM Node of this widget.
@type item: A DOM node or L{Widget}.
"""
self._children.append(item)
def appendChild(self, item):
"""
Add `item' to the children of the resultant DOM Node of this widget.
@type item: A DOM node or L{Widget}.
"""
self._children.append(item)
def insert(self, index, item):
"""
Insert `item' at `index' in the children list of the resultant DOM Node
of this widget.
@type item: A DOM node or L{Widget}.
"""
self._children.insert(index, item)
def setNode(self, node):
"""
Set a node for this widget to use instead of creating one programatically.
Useful for looking up a node in a template and using that.
"""
# self.templateNode should always be the original, unmutated
# node that was in the HTML template.
if self.templateNode == None:
self.templateNode = node
self.node = node
def cleanNode(self, node):
"""
Do your part, prevent infinite recursion!
"""
if not DEBUG:
if node.attributes.has_key('model'):
del node.attributes['model']
if node.attributes.has_key('view'):
del node.attributes['view']
if node.attributes.has_key('controller'):
del node.attributes['controller']
return node
def generate(self, request, node):
data = self.getData(request)
if isinstance(data, defer.Deferred):
data.addCallback(self.setDataCallback, request, node)
data.addErrback(utils.renderFailure, request)
return data
return self._regenerate(request, node, data)
def _regenerate(self, request, node, data):
self._reset()
self.setUp(request, node, data)
for setupMethod in self.setupMethods:
setupMethod(request, self, data)
# generateDOM should always get a reference to the
# templateNode from the original HTML
result = self.generateDOM(request, self.templateNode or node)
if DEBUG:
result.attributes['woven_class'] = reflect.qual(self.__class__)
return result
def setDataCallback(self, result, request, node):
if isinstance(self.getData(request), defer.Deferred):
self.setData(request, result)
data = self.getData(request)
if isinstance(data, defer.Deferred):
import warnings
warnings.warn("%r has returned a Deferred multiple times for the "
"same request; this is a potential infinite loop."
% self.getData)
data.addCallback(self.setDataCallback, request, node)
data.addErrback(utils.renderFailure, request)
return data
newNode = self._regenerate(request, node, result)
returnNode = self.dispatchResult(request, node, newNode)
# isinstance(Element) added because I was having problems with
# this code trying to call setAttribute on my RawTexts -radix 2003-5-28
if hasattr(self, 'outgoingId') and isinstance(returnNode, Element):
returnNode.attributes['id'] = self.outgoingId
self.handleNewNode(request, returnNode)
self.handleOutstanding(request)
if self.subviews:
self.getTopModel().subviews.update(self.subviews)
self.controller.domChanged(request, self, returnNode)
## We need to return the result along the callback chain
## so that any other views which added a setDataCallback
## to the same deferred will get the correct data.
return result
def setUp(self, request, node, data):
"""
Override this method to set up your Widget prior to generateDOM. This
is a good place to call methods like L{add}, L{insert}, L{__setitem__}
and L{__getitem__}.
Overriding this method obsoletes overriding generateDOM directly, in
most cases.
@type request: L{twisted.web.server.Request}.
@param node: The DOM node which this Widget is operating on.
@param data: The Model data this Widget is meant to operate upon.
"""
pass
def generateDOM(self, request, node):
"""
@returns: A DOM Node to replace the Node in the template that this
Widget handles. This Node is created based on L{tagName},
L{children}, and L{attributes} (You should populate these
in L{setUp}, probably).
"""
if self.become:
#print "becoming"
become = self.become
self.become = None
parent = node.parentNode
node.parentNode = None
old = node.cloneNode(1)
node.parentNode = parent
gen = become.generateDOM(request, node)
if old.attributes.has_key('model'):
del old.attributes['model']
del old.attributes['controller']
gen.appendChild(old)
self.node = gen
return gen
if DEBUG:
template = node.toxml()
log.msg(template)
if not self.tagName:
self.tagName = self.templateNode.tagName
if node is not self.templateNode or self.tagName != self.templateNode.tagName:
parent = node.parentNode
node = document.createElement(self.tagName, caseInsensitive=0, preserveCase=0)
node.parentNode = parent
else:
parentNode = node.parentNode
node.parentNode = None
if self.clearNode:
new = node.cloneNode(0)
else:
new = node.cloneNode(1)
node.parentNode = parentNode
node = self.cleanNode(new)
#print "NICE CLEAN NODE", node.toxml(), self._children
node.attributes.update(self.attributes)
for item in self._children:
if hasattr(item, 'generate'):
parentNode = node.parentNode
node.parentNode = None
item = item.generate(request, node.cloneNode(1))
node.parentNode = parentNode
node.appendChild(item)
#print "WE GOT A NODE", node.toxml()
self.node = node
return self.node
def modelChanged(self, payload):
request = payload.get('request', None)
if request is None:
request = Dummy()
request.d = document
oldNode = self.node
if payload.has_key(self.submodel):
data = payload[self.submodel]
else:
data = self.getData(request)
newNode = self._regenerate(request, oldNode, data)
returnNode = self.dispatchResult(request, oldNode, newNode)
# shot in the dark: this seems to make *my* code work. probably will
# break if returnNode returns a Deferred, as it's supposed to be able
# to do -glyph
# self.viewStack.push(self)
# self.controller.controllerStack.push(self.controller)
self.handleNewNode(request, returnNode)
self.handleOutstanding(request)
self.controller.domChanged(request, self, returnNode)
def __setitem__(self, item, value):
"""
Convenience syntax for adding attributes to the resultant DOM Node of
this widget.
"""
assert value is not None
self.attributes[item] = value
setAttribute = __setitem__
def __getitem__(self, item):
"""
Convenience syntax for getting an attribute from the resultant DOM Node
of this widget.
"""
return self.attributes[item]
getAttribute = __getitem__
def setError(self, request, message):
"""
Convenience method for allowing a Controller to report an error to the
user. When this is called, a Widget of class self.errorFactory is instanciated
and set to self.become. When generate is subsequently called, self.become
will be responsible for mutating the DOM instead of this widget.
"""
#print "setError called", self
id = self.attributes.get('id', '')
self.become = self.errorFactory(self.model, message)
self.become['id'] = id
# self.modelChanged({'request': request})
def getTopModel(self):
"""Get a reference to this page's top model object.
"""
top = self.model
while top.parent is not None:
top = top.parent
return top
def getAllPatterns(self, name, default=missingPattern, clone=1, deep=1):
"""Get all nodes below this one which have a matching pattern attribute.
"""
if self.slots.has_key(name):
slots = self.slots[name]
else:
sm = self.submodel.split('/')[-1]
slots = domhelpers.locateNodes(self.templateNode, name + 'Of', sm)
if not slots:
# slots = domhelpers.locateNodes(self.templateNode, "pattern", name, noNesting=1)
matcher = lambda n, name=name: isinstance(n, Element) and \
n.attributes.has_key("pattern") and n.attributes["pattern"] == name
recurseMatcher = lambda n: isinstance(n, Element) and not n.attributes.has_key("view") and not n.attributes.has_key('model')
slots = domhelpers.findNodesShallowOnMatch(self.templateNode, matcher, recurseMatcher)
if not slots:
msg = 'WARNING: No template nodes were found '\
'(tagged %s="%s"'\
' or pattern="%s") for node %s (full submodel path %s)' % (name + "Of",
sm, name, self.templateNode, `self.submodel`)
if default is _RAISE:
raise Exception(msg)
if DEBUG:
warnings.warn(msg)
if default is missingPattern:
newNode = missingPattern.cloneNode(1)
newNode.appendChild(document.createTextNode(msg))
return [newNode]
if default is None:
return None
return [default]
self.slots[name] = slots
if clone:
return [x.cloneNode(deep) for x in slots]
return slots
def getPattern(self, name, default=missingPattern, clone=1, deep=1):
"""Get a named slot from the incoming template node. Returns a copy
of the node and all its children. If there was more than one node with
the same slot identifier, they will be returned in a round-robin fashion.
"""
slots = self.getAllPatterns(name, default=default, clone=0)
if slots is None:
return None
slot = slots.pop(0)
slots.append(slot)
if clone:
parentNode = slot.parentNode
slot.parentNode = None
clone = slot.cloneNode(deep)
if clone.attributes.has_key('pattern'):
del clone.attributes['pattern']
elif clone.attributes.has_key(name + 'Of'):
del clone.attributes[name + 'Of']
slot.parentNode = parentNode
if DEBUG:
clone.attributes['ofPattern'] = name + 'Of'
clone.attributes['nameOf'] = self.submodel.split('/')[-1]
return clone
if DEBUG:
slot.attributes['ofPattern'] = name + 'Of'
slot.attributes['nameOf'] = self.submodel.split('/')[-1]
return slot
def addUpdateMethod(self, updateMethod):
"""Add a method to this widget that will be called when the widget
is being rendered. The signature for this method should be
updateMethod(request, widget, data) where widget will be the
instance you are calling addUpdateMethod on.
"""
self.setupMethods.append(updateMethod)
def addEventHandler(self, eventName, handler, *args):
"""Add an event handler to this widget. eventName is a string
indicating which javascript event handler should cause this
handler to fire. Handler is a callable that has the signature
handler(request, widget, *args).
"""
def handlerUpdateStep(request, widget, data):
extraArgs = ''
for x in args:
extraArgs += " ,'" + x.replace("'", "\\'") + "'"
widget[eventName] = "return woven_eventHandler('%s', this%s)" % (eventName, extraArgs)
setattr(self, 'wevent_' + eventName, handler)
self.addUpdateMethod(handlerUpdateStep)
def onEvent(self, request, eventName, *args):
"""Dispatch a client-side event to an event handler that was
registered using addEventHandler.
"""
eventHandler = getattr(self, 'wevent_' + eventName, None)
if eventHandler is None:
raise NotImplementedError("A client side '%s' event occurred,"
" but there was no event handler registered on %s." %
(eventName, self))
eventHandler(request, self, *args)
class DefaultWidget(Widget):
def generate(self, request, node):
"""
By default, we just return the node unchanged
"""
self.cleanNode(node)
if self.become:
become = self.become
self.become = None
parent = node.parentNode
node.parentNode = None
old = node.cloneNode(1)
node.parentNode = parent
gen = become.generateDOM(request, node)
del old.attributes['model']
gen.appendChild(self.cleanNode(old))
return gen
return node
def modelChanged(self, payload):
"""We're not concerned if the model has changed.
"""
pass
class Attributes(Widget):
"""Set attributes on a node.
Assumes model is a dictionary of attributes.
"""
def setUp(self, request, node, data):
for k, v in data.items():
self[k] = v
class Text(Widget):
"""
A simple Widget that renders some text.
"""
def __init__(self, model, raw=0, clear=1, *args, **kwargs):
"""
@param model: The text to render.
@type model: A string or L{model.Model}.
@param raw: A boolean that specifies whether to render the text as
a L{domhelpers.RawText} or as a DOM TextNode.
"""
self.raw = raw
self.clearNode = clear
Widget.__init__(self, model, *args, **kwargs)
def generate(self, request, node):
if self.templateNode is None:
if self.raw:
return domhelpers.RawText(str(self.getData(request)))
else:
return document.createTextNode(str(self.getData(request)))
return Widget.generate(self, request, node)
def setUp(self, request, node, data):
if self.raw:
textNode = domhelpers.RawText(str(data))
else:
textNode = document.createTextNode(str(data))
self.appendChild(textNode)
class ParagraphText(Widget):
"""
Like a normal text widget, but it takes line breaks in the text and
formats them as HTML paragraphs.
"""
def setUp(self, request, node, data):
nSplit = data.split('\n')
for line in nSplit:
if line.strip():
para = request.d.createElement('p', caseInsensitive=0, preserveCase=0)
para.appendChild(request.d.createTextNode(line))
self.add(para)
class Image(Widget):
"""
A simple Widget that creates an `img' tag.
"""
tagName = 'img'
border = '0'
def setUp(self, request, node, data):
self['border'] = self.border
self['src'] = data
class Error(Widget):
tagName = 'span'
def __init__(self, model, message="", *args, **kwargs):
Widget.__init__(self, model, *args, **kwargs)
self.message = message
def generateDOM(self, request, node):
self['style'] = 'color: red'
self.add(Text(" " + self.message))
return Widget.generateDOM(self, request, node)
class Div(Widget):
tagName = 'div'
class Span(Widget):
tagName = 'span'
class Br(Widget):
tagName = 'br'
class Input(Widget):
tagName = 'input'
def setSubmodel(self, submodel):
self.submodel = submodel
self['name'] = submodel
def setUp(self, request, node, data):
if not self.attributes.has_key('name') and not node.attributes.get('name'):
if self.submodel:
id = self.submodel
else:
id = self.attributes.get('id', node.attributes.get('id'))
self['name'] = id
if data is None:
data = ''
if not self.attributes.has_key('value'):
self['value'] = str(data)
class CheckBox(Input):
def setUp(self, request, node, data):
self['type'] = 'checkbox'
Input.setUp(self, request, node, data)
class RadioButton(Input):
def setUp(self, request, node, data):
self['type'] = 'radio'
Input.setUp(self, request, node, data)
class File(Input):
def setUp(self, request, node, data):
self['type'] = 'file'
Input.setUp(self, request, node, data)
class Hidden(Input):
def setUp(self, request, node, data):
self['type'] = 'hidden'
Input.setUp(self, request, node, data)
class InputText(Input):
def setUp(self, request, node, data):
self['type'] = 'text'
Input.setUp(self, request, node, data)
class PasswordText(Input):
"""
I render a password input field.
"""
def setUp(self, request, node, data):
self['type'] = 'password'
Input.setUp(self, request, node, data)
class Button(Input):
def setUp(self, request, node, data):
self['type'] = 'button'
Input.setUp(self, request, node, data)
class Select(Input):
tagName = 'select'
class Option(Widget):
tagName = 'option'
def initialize(self):
self.text = ''
def setText(self, text):
"""
Set the text to be displayed within the select menu.
"""
self.text = text
def setValue(self, value):
self['value'] = str(value)
def setUp(self, request, node, data):
self.add(Text(self.text or data))
if data is None:
data = ''
if not self.attributes.has_key('value'):
self['value'] = str(data)
class Anchor(Widget):
tagName = 'a'
trailingSlash = ''
def initialize(self):
self.baseHREF = ''
self.parameters = {}
self.raw = 0
self.text = ''
def setRaw(self, raw):
self.raw = raw
def setLink(self, href):
self.baseHREF= href
def setParameter(self, key, value):
self.parameters[key] = value
def setText(self, text):
self.text = text
def setUp(self, request, node, data):
href = self.baseHREF
params = urllib.urlencode(self.parameters)
if params:
href = href + '?' + params
self['href'] = href or str(data) + self.trailingSlash
if data is None:
data = ""
self.add(Text(self.text or data, self.raw, 0))
class SubAnchor(Anchor):
def initialize(self):
warnings.warn(
"SubAnchor is deprecated, you might want either Anchor or DirectoryAnchor",
DeprecationWarning)
Anchor.initialize(self)
class DirectoryAnchor(Anchor):
trailingSlash = '/'
def appendModel(newNode, modelName):
if newNode is None: return
curModel = newNode.attributes.get('model')
if curModel is None:
newModel = str(modelName)
else:
newModel = '/'.join((curModel, str(modelName)))
newNode.attributes['model'] = newModel
class List(Widget):
"""
I am a widget which knows how to generateDOM for a python list.
A List should be specified in the template HTML as so::
| <ul model="blah" view="List">
| <li pattern="emptyList">This will be displayed if the list
| is empty.</li>
| <li pattern="listItem" view="Text">Foo</li>
| </ul>
If you have nested lists, you may also do something like this::
| <table model="blah" view="List">
| <tr pattern="listHeader"><th>A</th><th>B</th></tr>
| <tr pattern="emptyList"><td colspan='2'>***None***</td></tr>
| <tr pattern="listItem">
| <td><span view="Text" model="1" /></td>
| <td><span view="Text" model="2" /></td>
| </tr>
| <tr pattern="listFooter"><td colspan="2">All done!</td></tr>
| </table>
Where blah is the name of a list on the model; eg::
| self.model.blah = ['foo', 'bar']
"""
tagName = None
defaultItemView = "DefaultWidget"
def generateDOM(self, request, node):
node = Widget.generateDOM(self, request, node)
listHeaders = self.getAllPatterns('listHeader', None)
listFooters = self.getAllPatterns('listFooter', None)
emptyLists = self.getAllPatterns('emptyList', None)
domhelpers.clearNode(node)
if listHeaders:
node.childNodes.extend(listHeaders)
for n in listHeaders: n.parentNode = node
data = self.getData(request)
if data:
self._iterateData(node, self.submodel, data)
elif emptyLists:
node.childNodes.extend(emptyLists)
for n in emptyLists: n.parentNode = node
if listFooters:
node.childNodes.extend(listFooters)
for n in listFooters: n.parentNode = node
return node
def _iterateData(self, parentNode, submodel, data):
currentListItem = 0
retVal = [None] * len(data)
for itemNum in range(len(data)):
# theory: by appending copies of the li node
# each node will be handled once we exit from
# here because handleNode will then recurse into
# the newly appended nodes
newNode = self.getPattern('listItem')
if newNode.getAttribute('model') == '.':
newNode.removeAttribute('model')
elif not newNode.attributes.get("view"):
newNode.attributes["view"] = self.defaultItemView
appendModel(newNode, itemNum)
retVal[itemNum] = newNode
newNode.parentNode = parentNode
# parentNode.appendChild(newNode)
parentNode.childNodes.extend(retVal)
class KeyedList(List):
"""
I am a widget which knows how to display the values stored within a
Python dictionary..
A KeyedList should be specified in the template HTML as so::
| <ul model="blah" view="KeyedList">
| <li pattern="emptyList">This will be displayed if the list is
| empty.</li>
| <li pattern="keyedListItem" view="Text">Foo</li>
| </ul>
I can take advantage of C{listHeader}, C{listFooter} and C{emptyList}
items just as a L{List} can.
"""
def _iterateData(self, parentNode, submodel, data):
"""
"""
currentListItem = 0
keys = data.keys()
# Keys may be a tuple, if this is not a true dictionary but a dictionary-like object
if hasattr(keys, 'sort'):
keys.sort()
for key in keys:
newNode = self.getPattern('keyedListItem')
if not newNode:
newNode = self.getPattern('item', _RAISE)
if newNode:
warnings.warn("itemOf= is deprecated, "
"please use listItemOf instead",
DeprecationWarning)
appendModel(newNode, key)
if not newNode.attributes.get("view"):
newNode.attributes["view"] = "DefaultWidget"
parentNode.appendChild(newNode)
class ColumnList(Widget):
def __init__(self, model, columns=1, start=0, end=0, *args, **kwargs):
Widget.__init__(self, model, *args, **kwargs)
self.columns = columns
self.start = start
self.end = end
def setColumns(self, columns):
self.columns = columns
def setStart(self, start):
self.start = start
def setEnd(self, end):
self.end = end
def setUp(self, request, node, data):
pattern = self.getPattern('columnListRow', clone=0)
if self.end:
listSize = self.end - self.start
if listSize > len(data):
listSize = len(data)
else:
listSize = len(data)
for itemNum in range(listSize):
if itemNum % self.columns == 0:
row = self.getPattern('columnListRow')
domhelpers.clearNode(row)
node.appendChild(row)
newNode = self.getPattern('columnListItem')
appendModel(newNode, itemNum + self.start)
if not newNode.attributes.get("view"):
newNode.attributes["view"] = "DefaultWidget"
row.appendChild(newNode)
node.removeChild(pattern)
return node
class Bold(Widget):
tagName = 'b'
class Table(Widget):
tagName = 'table'
class Row(Widget):
tagName = 'tr'
class Cell(Widget):
tagName = 'td'
class RawText(Widget):
def generateDOM(self, request, node):
self.node = domhelpers.RawText(self.getData(request))
return self.node
from types import StringType
class Link(Widget):
"""A utility class for generating <a href='foo'>bar</a> tags.
"""
tagName = 'a'
def setUp(self, request, node, data):
# TODO: we ought to support Deferreds here for both text and href!
if isinstance(data, StringType):
node.tagName = self.tagName
node.attributes["href"] = data
else:
data = self.model
txt = data.getSubmodel(request, "text").getData(request)
if not isinstance(txt, Node):
txt = document.createTextNode(txt)
lnk = data.getSubmodel(request, "href").getData(request)
self['href'] = lnk
node.tagName = self.tagName
domhelpers.clearNode(node)
node.appendChild(txt)
class RootRelativeLink(Link):
"""
Just like a regular Link, only it makes the href relative to the
appRoot (that is, request.getRootURL()).
"""
def setUp(self, request, node, data):
# hack, hack: some juggling so I can type less and share more
# code with Link
st = isinstance(data, StringType)
if st:
data = request.getRootURL() + '/' + data
Link.setUp(self, request, node, data)
if not st:
self['href'] = request.getRootURL() + '/' + self['href']
class ExpandMacro(Widget):
"""A Macro expansion widget modeled after the METAL expander
in ZPT/TAL/METAL. Usage:
In the Page that is being rendered, place the ExpandMacro widget
on the node you want replaced with the Macro, and provide nodes
tagged with fill-slot= attributes which will fill slots in the Macro::
def wvfactory_myMacro(self, request, node, model):
return ExpandMacro(
model,
macroFile="MyMacro.html",
macroName="main")
<div view="myMacro">
<span fill-slot="greeting">Hello</span>
<span fill-slot="greetee">World</span>
</div>
Then, in your Macro template file ("MyMacro.html" in the above
example) designate a node as the macro node, and nodes
inside that as the slot nodes::
<div macro="main">
<h3><span slot="greeting" />, <span slot="greetee" />!</h3>
</div>
"""
def __init__(self, model, macroTemplate = "", macroFile="", macroFileDirectory="", macroName="", **kwargs):
self.macroTemplate = macroTemplate
self.macroFile=macroFile
self.macroFileDirectory=macroFileDirectory
self.macroName=macroName
Widget.__init__(self, model, **kwargs)
def generate(self, request, node):
if self.macroTemplate:
templ = view.View(
self.model,
template = self.macroTemplate).lookupTemplate(request)
else:
templ = view.View(
self.model,
templateFile=self.macroFile,
templateDirectory=self.macroFileDirectory).lookupTemplate(request)
## We are going to return the macro node from the metatemplate,
## after replacing any slot= nodes in it with fill-slot= nodes from `node'
macrolist = domhelpers.locateNodes(templ.childNodes, "macro", self.macroName)
assert len(macrolist) == 1, ("No macro or more than "
"one macro named %s found." % self.macroName)
macro = macrolist[0]
del macro.attributes['macro']
slots = domhelpers.findElementsWithAttributeShallow(macro, "slot")
for slot in slots:
slotName = slot.attributes.get("slot")
fillerlist = domhelpers.locateNodes(node.childNodes, "fill-slot", slotName)
assert len(fillerlist) <= 1, "More than one fill-slot found with name %s" % slotName
if len(fillerlist):
filler = fillerlist[0]
filler.tagName = filler.endTagName = slot.tagName
del filler.attributes['fill-slot']
del slot.attributes['slot']
filler.attributes.update(slot.attributes)
slot.parentNode.replaceChild(filler, slot)
return macro
class DeferredWidget(Widget):
def setDataCallback(self, result, request, node):
model = result
view = None
if isinstance(model, components.Componentized):
view = model.getAdapter(interfaces.IView)
if not view and hasattr(model, '__class__'):
view = interfaces.IView(model, None)
if view:
view["id"] = self.attributes.get('id', '')
view.templateNode = node
view.controller = self.controller
return view.setDataCallback(result, request, node)
else:
return Widget.setDataCallback(self, result, request, node)
class Break(Widget):
"""Break into pdb when this widget is rendered. Mildly
useful for debugging template structure, model stacks,
etc.
"""
def setUp(self, request, node, data):
import pdb; pdb.set_trace()
view.registerViewForModel(Text, model.StringModel)
view.registerViewForModel(List, model.ListModel)
view.registerViewForModel(KeyedList, model.DictionaryModel)
view.registerViewForModel(Link, model.Link)
view.registerViewForModel(DeferredWidget, model.DeferredWrapper) | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/woven/widgets.py | widgets.py |
# dominput
import os
import inspect
from twisted.internet import defer
from twisted.python import log
from twisted.python.reflect import qual
from twisted.web import domhelpers
from twisted.web.woven import template, controller, utils
__version__ = "$Revision: 1.34 $"[11:-2]
controllerFactory = controller.controllerFactory
class InputHandler(controller.Controller):
"""
An InputHandler is like a controller, but it operates on something
contained inside of C{self.model} instead of directly on C{self.model}.
For example, a Handler whose C{model} has been set to C{"foo"} will handle
C{self.model.foo}.
The handler's job is to interpret the request and:
1. Check for valid input
2. If the input is valid, update the model
3. Use any special API of the view widget to change the view (other
than what the view updates automatically from the model) e.g. in the
case of an error, tell the view to report an error to the user
4. Return a success value; by default these values are simply recorded
and the page is rendered, but these values could be used to determine
what page to display next, etc.
"""
invalidErrorText = "Error!"
setupStacks = 0
def __init__(self, model=None,
parent=None,
name=None,
check=None,
commit = None,
invalidErrorText = None,
submodel=None,
controllerStack=None):
self.controllerStack = controllerStack
controller.Controller.__init__(self, model)
self._check = check
self._commit = commit
self._errback = None
self._parent = parent
if invalidErrorText is not None:
self.invalidErrorText = invalidErrorText
if submodel is not None:
self.submodel = submodel
if name is not None:
self.inputName = name
def initialize(self):
pass
def setNode(self, node):
self.node = node
def getInput(self, request):
"""
Return the data associated with this handler from the request, if any.
"""
name = getattr(self, 'inputName', self.submodel)
input = request.args.get(name, None)
if input:
return input
def handle(self, request):
self.initialize()
data = self.getInput(request)
success = self.check(request, data)
if isinstance(success, defer.Deferred):
success.addCallback(self.dispatchCheckResult, request, data)
success.addErrback(utils.renderFailure, request)
return success
self.dispatchCheckResult(success, request, data)
def dispatchCheckResult(self, success, request, data):
if success is not None:
if success:
result = self.handleValid(request, data)
else:
result = self.handleInvalid(request, data)
if isinstance(result, defer.Deferred):
return result
def check(self, request, data):
"""
Check whether the input in the request is valid for this handler
and return a boolean indicating validity.
"""
if self._check is None:
raise NotImplementedError(qual(self.__class__)+'.check')
# self._check is probably a bound method or simple function that
# doesn't have a reference to this InputHandler; pass it
return self._check(self, request, data)
def handleValid(self, request, data):
"""
It has been determined that the input for this handler is valid;
however, that does not mean the entire form is valid.
"""
self._parent.aggregateValid(request, self, data)
def aggregateValid(self, request, inputhandler, data):
"""By default we just pass the method calls all the way up to the root
Controller. However, an intelligent InputHandler could override this
and implement a state machine that waits for all data to be collected
and then fires.
"""
self._parent.aggregateValid(request, inputhandler, data)
def handleInvalid(self, request, data):
"""
Once it has been determined that the input is invalid, we should
tell our view to report this fact to the user.
"""
self._parent.aggregateInvalid(request, self, data)
self.view.setError(request, self.invalidErrorText)
def aggregateInvalid(self, request, inputhandler, data):
"""By default we just pass this method call all the way up to the root
Controller.
"""
self._parent.aggregateInvalid(request, inputhandler, data)
def commit(self, request, node, data):
"""
It has been determined that the input for the entire form is completely
valid; it is now safe for all handlers to commit changes to the model.
"""
if self._commit is None:
data = str(data)
if data != self.view.getData():
self.model.setData(data)
self.model.notify({'request': request, self.submodel: data})
else:
func = self._commit
if hasattr(func, 'im_func'):
func = func.im_func
args, varargs, varkw, defaults = inspect.getargspec(func)
if args[1] == 'request':
self._commit(request, data)
else:
self._commit(data)
class DefaultHandler(InputHandler):
def handle(self, request):
"""
By default, we don't do anything
"""
pass
class SingleValue(InputHandler):
def getInput(self, request):
name = getattr(self, 'inputName', self.submodel)
input = request.args.get(name, None)
if input:
return input[0]
class Anything(SingleValue):
"""
Handle anything except for None
"""
def check(self, request, data):
if data is not None:
return 1
return None
class Integer(SingleValue):
"""
Only allow a single integer
"""
def check(self, request, data):
if data is None: return None
try:
int(data)
return 1
except (TypeError, ValueError):
return 0
def handleInvalid(self, request, data):
self.invalidErrorText = "%s is not an integer. Please enter an integer." % data
SingleValue.handleInvalid(self, request, data)
class Float(SingleValue):
"""
Only allow a single float
"""
def check(self, request, data):
if data is None: return None
try:
float(data)
return 1
except (TypeError, ValueError):
return 0
def handleInvalid(self, request, data):
self.invalidErrorText = "%s is not an float. Please enter a float." % data
SingleValue.handleInvalid(self, request, data)
class List(InputHandler):
def check(self, request, data):
return None
class DictAggregator(Anything):
"""An InputHandler for a <form> tag, for triggering a function
when all of the form's individual inputs have been validated.
Also for use gathering a dict of arguments to pass to a parent's
aggregateValid if no commit function is passed.
Usage example::
<form controller="theForm" action="">
<input controller="Integer"
view="InputText" model="anInteger" />
<input controller="Anything"
view="InputText" model="aString" />
<input type="submit" />
</form>
def theCommitFunction(anInteger=None, aString=None):
'''Note how the keyword arguments match up with the leaf model
names above
'''
print "Yay", anInteger, aString
class CMyController(controller.Controller):
def wcfactory_theForm(self, request, node, m):
return input.FormAggregator(m, commit=theCommitFunction)
"""
def aggregateValid(self, request, inputhandler, data):
"""Aggregate valid input from inputhandlers below us, into a dictionary.
"""
self._valid[inputhandler] = data
def aggregateInvalid(self, request, inputhandler, data):
self._invalid[inputhandler] = data
def exit(self, request):
"""This is the node complete message
"""
if self._commit:
# Introspect the commit function to see what
# keyword arguments it takes
func = self._commit
if hasattr(func, 'im_func'):
func = func.im_func
args, varargs, varkw, defaults = inspect.getargspec(
func)
wantsRequest = len(args) > 1 and args[1] == 'request'
if self._invalid:
# whoops error!!!1
if self._errback:
self._errback(request, self._invalid)
elif self._valid:
# We've got all the input
# Gather it into a dict and call the commit function
results = {}
for item in self._valid:
results[item.model.name] = self._valid[item]
if self._commit:
if wantsRequest:
self._commit(request, **results)
else:
self._commit(**results)
else:
self._parent.aggregateValid(request, self, results)
return results
class ListAggregator(Anything):
def aggregateValid(self, request, inputhandler, data):
"""Aggregate valid input from inputhandlers below us into a
list until we have all input from controllers below us to pass
to the commit function that was passed to the constructor or
our parent's aggregateValid.
"""
if not hasattr(self, '_validList'):
self._validList = []
self._validList.append(data)
def aggregateInvalid(self, request, inputhandler, data):
if not hasattr(self, '_invalidList'):
self._invalidList = []
self._invalidList.append(data)
def exit(self, request):
if self._commit:
# Introspect the commit function to see what
#arguments it takes
func = self._commit
if hasattr(func, 'im_func'):
func = func.im_func
args, varargs, varkw, defaults = inspect.getargspec(func)
self.numArgs = len(args)
wantsRequest = args[1] == 'request'
if wantsRequest:
numArgs -= 1
else:
# Introspect the template to see if we still have
# controllers that will be giving us input
# aggregateValid is called before the view renders the node, so
# we can count the number of controllers below us the first time
# we are called
if not hasattr(self, 'numArgs'):
self.numArgs = len(domhelpers.findElementsWithAttributeShallow(
self.view.node, "controller"))
if self._invalidList:
self._parent.aggregateInvalid(request, self, self._invalidList)
else:
if self._commit:
if wantsRequest:
self._commit(request, *self._validList)
else:
self._commit(*self._validList)
self._parent.aggregateValid(request, self, self._invalidList)
def commit(self, request, node, data):
"""If we're using the ListAggregator, we don't want the list of items
to be rerendered
xxx Need to have a "node complete" message sent to the controller
so we can reset state, so controllers can be re-run or ignore input the second time
"""
pass | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/woven/input.py | input.py |
__version__ = "$Revision: 1.53 $"[11:-2]
import types
import weakref
import warnings
from zope.interface import implements
from twisted.python import components, reflect
from twisted.internet import defer
from twisted.web.woven import interfaces
class _Nothing: pass
def adaptToIModel(m, parent=None, submodel=None):
adapted = interfaces.IModel(m, None)
if adapted is None:
adapted = Wrapper(m)
adapted.parent = parent
adapted.name = submodel
return adapted
class Model:
"""
A Model which keeps track of views which are looking at it in order
to notify them when the model changes.
"""
implements(interfaces.IModel)
def __init__(self, *args, **kwargs):
if len(args):
self.original = args[0]
else:
self.original = self
self.name = ''
self.parent = None
self.views = []
self.subviews = {}
self.submodels = {}
self._getter = kwargs.get('getter')
self._setter = kwargs.get('setter')
self.cachedFor = None
self.initialize(*args, **kwargs)
def __getstate__(self):
self.views = []
self.subviews = {}
self.submodels = {}
return self.__dict__
def invalidateCache(self):
"""Invalidate the cache for this object, so the next time
getData is called, it's getter method is called again.
"""
self.cachedFor = None
def initialize(self, *args, **kwargs):
"""
Hook for subclasses to initialize themselves without having to
mess with the __init__ chain.
"""
pass
def addView(self, view):
"""
Add a view for the model to keep track of.
"""
if view not in [ref() for ref in self.views]:
self.views.append(weakref.ref(view))
def addSubview(self, name, subview):
subviewList = self.subviews.get(name, [])
subviewList.append(weakref.ref(subview))
self.subviews[name] = subviewList
def removeView(self, view):
"""
Remove a view that the model no longer should keep track of.
"""
# AM: loop on a _copy_ of the list, since we're changing it!!!
for weakref in list(self.views):
ref = weakref()
if ref is view or ref is None:
self.views.remove(weakref)
def setGetter(self, getter):
self._getter = getter
def setSetter(self, setter):
self._setter = setter
def notify(self, changed=None):
"""
Notify all views that something was changed on me.
Passing a dictionary of {'attribute': 'new value'} in changed
will pass this dictionary to the view for increased performance.
If you don't want to do this, don't, and just use the traditional
MVC paradigm of querying the model for things you're interested
in.
"""
self.cachedFor = None
if changed is None: changed = {}
retVal = []
# AM: loop on a _copy_ of the list, since we're changing it!!!
for view in list(self.views):
ref = view()
if ref is not None:
retVal.append((ref, ref.modelChanged(changed)))
else:
self.views.remove(view)
for key, value in self.subviews.items():
if value.wantsAllNotifications or changed.has_key(key):
for item in list(value):
ref = item()
if ref is not None:
retVal.append((ref, ref.modelChanged(changed)))
else:
value.remove(item)
return retVal
protected_names = ['initialize', 'addView', 'addSubview', 'removeView', 'notify', 'getSubmodel', 'setSubmodel', 'getData', 'setData']
allowed_names = []
def lookupSubmodel(self, request, submodelName):
"""
Look up a full submodel name. I will split on `/' and call
L{getSubmodel} on each element in the 'path'.
Override me if you don't want 'traversing'-style lookup, but
would rather like to look up a model based on the entire model
name specified.
If you override me to return Deferreds, make sure I look up
values in a cache (created by L{setSubmodel}) before doing a
regular Deferred lookup.
XXX: Move bits of this docstring to interfaces.py
"""
if not submodelName:
return None
# Special case: If the first character is /
# Start at the bottom of the model stack
currentModel = self
if submodelName[0] == '/':
while currentModel.parent is not None:
currentModel = currentModel.parent
submodelName = submodelName[1:]
submodelList = submodelName.split('/') #[:-1]
# print "submodelList", submodelList
for element in submodelList:
if element == '.' or element == '':
continue
elif element == '..':
currentModel = currentModel.parent
else:
currentModel = currentModel.getSubmodel(request, element)
if currentModel is None:
return None
return currentModel
def submodelCheck(self, request, name):
"""Check if a submodel name is allowed. Subclass me to implement a
name security policy.
"""
if self.allowed_names:
return (name in self.allowed_names)
else:
return (name and name[0] != '_' and name not in self.protected_names)
def submodelFactory(self, request, name):
warnings.warn("Warning: default Model lookup strategy is changing:"
"use either AttributeModel or MethodModel for now.",
DeprecationWarning)
if hasattr(self, name):
return getattr(self, name)
else:
return None
def getSubmodel(self, request, name):
"""
Get the submodel `name' of this model. If I ever return a
Deferred, then I ought to check for cached values (created by
L{setSubmodel}) before doing a regular Deferred lookup.
"""
if self.submodels.has_key(name):
return self.submodels[name]
if not self.submodelCheck(request, name):
return None
m = self.submodelFactory(request, name)
if m is None:
return None
sm = adaptToIModel(m, self, name)
self.submodels[name] = sm
return sm
def setSubmodel(self, request=None, name=None, value=None):
"""
Set a submodel on this model. If getSubmodel or lookupSubmodel
ever return a Deferred, I ought to set this in a place that
lookupSubmodel/getSubmodel know about, so they can use it as a
cache.
"""
if self.submodelCheck(request, name):
if self.submodels.has_key(name):
del self.submodels[name]
setattr(self, name, value)
def dataWillChange(self):
pass
def getData(self, request):
if self.cachedFor != id(request) and self._getter is not None:
self.cachedFor = id(request)
self.dataWillChange()
self.orig = self.original = self._getter(request)
return self.original
def setData(self, request, data):
if self._setter is not None:
self.cachedFor = None
return self._setter(request, data)
else:
if hasattr(self, 'parent') and self.parent:
self.parent.setSubmodel(request, self.name, data)
self.orig = self.original = data
class MethodModel(Model):
"""Look up submodels with wmfactory_* methods.
"""
def submodelCheck(self, request, name):
"""Allow any submodel for which I have a submodel.
"""
return hasattr(self, "wmfactory_"+name)
def submodelFactory(self, request, name):
"""Call a wmfactory_name method on this model.
"""
meth = getattr(self, "wmfactory_"+name)
return meth(request)
def getSubmodel(self, request=None, name=None):
if name is None:
warnings.warn("Warning! getSubmodel should now take the request as the first argument")
name = request
request = None
cached = self.submodels.has_key(name)
sm = Model.getSubmodel(self, request, name)
if sm is not None:
if not cached:
sm.cachedFor = id(request)
sm._getter = getattr(self, "wmfactory_"+name)
return sm
class AttributeModel(Model):
"""Look up submodels as attributes with hosts.allow/deny-style security.
"""
def submodelFactory(self, request, name):
if hasattr(self, name):
return getattr(self, name)
else:
return None
#backwards compatibility
WModel = Model
class Wrapper(Model):
"""
I'm a generic wrapper to provide limited interaction with the
Woven models and submodels.
"""
parent = None
name = None
def __init__(self, orig):
Model.__init__(self)
self.orig = self.original = orig
def dataWillChange(self):
pass
def __repr__(self):
myLongName = reflect.qual(self.__class__)
return "<%s instance at 0x%x: wrapped data: %s>" % (myLongName,
id(self), self.original)
class ListModel(Wrapper):
"""
I wrap a Python list and allow it to interact with the Woven
models and submodels.
"""
def dataWillChange(self):
self.submodels = {}
def getSubmodel(self, request=None, name=None):
if name is None and type(request) is type(""):
warnings.warn("Warning!")
name = request
request = None
if self.submodels.has_key(name):
return self.submodels[name]
orig = self.original
try:
i = int(name)
except:
return None
if i > len(orig):
return None
sm = adaptToIModel(orig[i], self, name)
self.submodels[name] = sm
return sm
def setSubmodel(self, request=None, name=None, value=None):
if value is None:
warnings.warn("Warning!")
value = name
name = request
request = None
self.original[int(name)] = value
def __len__(self):
return len(self.original)
def __getitem__(self, name):
return self.getSubmodel(None, str(name))
def __setitem__(self, name, value):
self.setSubmodel(None, str(name), value)
def __repr__(self):
myLongName = reflect.qual(self.__class__)
return "<%s instance at 0x%x: wrapped data: %s>" % (myLongName,
id(self), self.original)
class StringModel(ListModel):
""" I wrap a Python string and allow it to interact with the Woven models
and submodels. """
def setSubmodel(self, request=None, name=None, value=None):
raise ValueError("Strings are immutable.")
# pyPgSQL returns "PgResultSet" instances instead of lists, which look, act
# and breathe just like lists. pyPgSQL really shouldn't do this, but this works
try:
from pyPgSQL import PgSQL
components.registerAdapter(ListModel, PgSQL.PgResultSet, interfaces.IModel)
except:
pass
class DictionaryModel(Wrapper):
"""
I wrap a Python dictionary and allow it to interact with the Woven
models and submodels.
"""
def dataWillChange(self):
self.submodels = {}
def getSubmodel(self, request=None, name=None):
if name is None and type(request) is type(""):
warnings.warn("getSubmodel must get a request argument now")
name = request
request = None
if self.submodels.has_key(name):
return self.submodels[name]
orig = self.original
if name not in orig:
return None
sm = adaptToIModel(orig[name], self, name)
self.submodels[name] = sm
return sm
def setSubmodel(self, request=None, name=None, value=None):
if value is None:
warnings.warn("Warning!")
value = name
name = request
request = None
self.original[name] = value
class AttributeWrapper(Wrapper):
"""
I wrap an attribute named "name" of the given parent object.
"""
def __init__(self, parent, name):
self.original = None
parent = ObjectWrapper(parent)
Wrapper.__init__(self, parent.getSubmodel(None, name))
self.parent = parent
self.name = name
class ObjectWrapper(Wrapper):
"""
I may wrap an object and allow it to interact with the Woven models
and submodels. By default, I am not registered for use with anything.
"""
def getSubmodel(self, request=None, name=None):
if name is None and type(request) is type(""):
warnings.warn("Warning!")
name = request
request = None
if self.submodels.has_key(name):
return self.submodels[name]
sm = adaptToIModel(getattr(self.original, name), self, name)
self.submodels[name] = sm
return sm
def setSubmodel(self, request=None, name=None, value=None):
if value is None:
warnings.warn("Warning!")
value = name
name = request
request = None
setattr(self.original, name, value)
class UnsafeObjectWrapper(ObjectWrapper):
"""
I may wrap an object and allow it to interact with the Woven models
and submodels. By default, I am not registered for use with anything.
I am unsafe because I allow methods to be called. In fact, I am
dangerously unsafe. Be wary or I will kill your security model!
"""
def getSubmodel(self, request=None, name=None):
if name is None and type(request) is type(""):
warnings.warn("Warning!")
name = request
request = None
if self.submodels.has_key(name):
return self.submodels[name]
value = getattr(self.original, name)
if callable(value):
return value()
sm = adaptToIModel(value, self, name)
self.submodels = sm
return sm
class DeferredWrapper(Wrapper):
def setData(self, request=None, data=_Nothing):
if data is _Nothing:
warnings.warn("setData should be called with request as first arg")
data = request
request = None
if isinstance(data, defer.Deferred):
self.original = data
else:
views, subviews = self.views, self.subviews
new = adaptToIModel(data, self.parent, self.name)
self.__class__ = new.__class__
self.__dict__ = new.__dict__
self.views, self.subviews = views, subviews
class Link(AttributeModel):
def __init__(self, href, text):
AttributeModel.__init__(self)
self.href = href
self.text = text
try:
components.registerAdapter(StringModel, types.StringType, interfaces.IModel)
components.registerAdapter(ListModel, types.ListType, interfaces.IModel)
components.registerAdapter(ListModel, types.TupleType, interfaces.IModel)
components.registerAdapter(DictionaryModel, types.DictionaryType, interfaces.IModel)
components.registerAdapter(DeferredWrapper, defer.Deferred, interfaces.IModel)
components.registerAdapter(DeferredWrapper, defer.DeferredList, interfaces.IModel)
except ValueError:
# The adapters were already registered
pass | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/woven/model.py | model.py |
var woven_eventQueue = []
woven_eventQueueBusy = 0
woven_clientSideEventNum = 0
woven_requestingEvent = 0
function woven_eventHandler(eventName, node) {
var eventTarget = node.getAttribute('id')
var additionalArguments = ''
for (i = 2; i<arguments.length; i++) {
additionalArguments += '&woven_clientSideEventArguments='
additionalArguments += escape(eval(arguments[i]))
}
var source = '?woven_clientSideEventName=' + eventName + '&woven_clientSideEventTarget=' + eventTarget + additionalArguments + '&woven_clientSideEventNum=' + woven_clientSideEventNum
woven_clientSideEventNum += 1
woven_eventQueue.unshift(source)
if (!woven_eventQueueBusy) {
woven_sendTopEvent()
}
return false
}
function woven_sendTopEvent() {
woven_eventQueueBusy = 1
var url = woven_eventQueue.shift()
var input = document.getElementById('woven_inputConduit')
input.src = url
}
function woven_requestNextEvent() {
var output = document.getElementById('woven_outputConduit')
if (output) { output.src = '?woven_hookupOutputConduitToThisFrame=1&woven_clientSideEventNum=' + woven_clientSideEventNum.toString()}
}
function woven_clientToServerEventComplete() {
woven_requestNextEvent()
if (woven_eventQueue.length) {
woven_sendTopEvent()
} else {
woven_eventQueueBusy = 0
}
var focus = document.getElementById('woven_firstResponder')
focus.focus()
}
function woven_attemptFocus(theNode) {
// focus the first input element in the new node
if (theNode.tagName == 'INPUT') {
theNode.focus()
return 1
} else {
/* for (i=0; i<theNode.childNodes.length; i++) { */
/* if(woven_attemptFocus(theNode.childNodes[i])) { */
/* return 1 */
/* } */
/* } */
return 0
}
}
function woven_replaceElement(theId, htmlStr) {
var oldNode = document.getElementById(theId)
var newNode = document.createElement('span')
newNode.innerHTML = htmlStr
oldNode.parentNode.replaceChild(newNode.firstChild, oldNode)
//woven_attemptFocus(newNode)
woven_requestNextEvent()
//alert('blah')
}
function woven_appendChild(theId, htmlStr) {
woven_requestNextEvent()
var container = document.getElementById(theId)
var newNode = document.createElement('span')
newNode.innerHTML = htmlStr
container.appendChild(newNode.firstChild)
} | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/woven/WebConduit2_mozilla.js | WebConduit2_mozilla.js |
var InternetExplorer = navigator.appName.indexOf('Microsoft') != 1
function FlashConduit_swf_DoFSCommand(command, args) {
eval(args)
}
if (InternetExplorer) {
if (navigator.userAgent.indexOf('Windows') != -1) {
document.write('<SCRIPT LANGUAGE=VBScript\>\n')
document.write('on error resume next\n')
document.write('Sub FlashConduit_swf_FSCommand(ByVal command, ByVal args)\n')
document.write('call FlashConduit_swf_DoFSCommand(command, args)\n')
document.write('end sub\n')
document.write('</SCRIPT\>\n')
}
}
var woven_eventQueue = []
woven_eventQueueBusy = 0
woven_clientSideEventNum = 0
function woven_eventHandler(eventName, node) {
var eventTarget = node.getAttribute('id')
var additionalArguments = ''
for (i = 2; i<arguments.length; i++) {
additionalArguments += '&woven_clientSideEventArguments='
additionalArguments += escape(eval(arguments[i]))
}
var source = '?woven_clientSideEventName=' + eventName + '&woven_clientSideEventTarget=' + eventTarget + additionalArguments + '&woven_clientSideEventNum=' + woven_clientSideEventNum
woven_clientSideEventNum += 1
woven_eventQueue = woven_eventQueue.concat(source)
if (!woven_eventQueueBusy) {
woven_sendTopEvent()
}
return false
}
function woven_sendTopEvent() {
woven_eventQueueBusy = 1
var url = woven_eventQueue[0]
woven_eventQueue = woven_eventQueue.slice(1)
var input = document.getElementById('woven_inputConduit')
input.src = url
}
function woven_clientToServerEventComplete() {
if (this.woven_eventQueue.length) {
this.woven_sendTopEvent()
} else {
this.woven_eventQueueBusy = 0
}
var focus = document.getElementById('woven_firstResponder')
if (focus) {
focus.focus()
if (focus.getAttribute('clearOnFocus')) {
focus.value=''
}
}
document.scrollTop = 999999999
}
function woven_attemptFocus(theNode) {
// focus the first input element in the new node
if (theNode.tagName == 'INPUT') {
theNode.focus()
return 1
} else {
/* for (i=0; i<theNode.childNodes.length; i++) { */
/* if(woven_attemptFocus(theNode.childNodes[i])) { */
/* return 1 */
/* } */
/* } */
return 0
}
}
function woven_replaceElement(theId, htmlStr) {
//alert(woven_eventQueue.length)
var oldNode = document.getElementById(theId)
if (oldNode) {
if (oldNode.parentNode) {
var created = document.createElement('span')
created.innerHTML = htmlStr
if (created.firstChild) {
oldNode.parentNode.replaceChild(created.firstChild, oldNode)
var newNode = document.getElementById(theId)
//woven_attemptFocus(newNode)
}
}
}
}
function woven_appendChild(theId, htmlStr) {
var container = document.getElementById(theId)
var newNode = document.createElement('span')
newNode.innerHTML = htmlStr
container.appendChild(newNode.firstChild)
}
function woven_removeChild(theId) {
var theElement = document.getElementById(theId)
theElement.parentNode.removeChild(theElement)
} | zope.app.twisted | /zope.app.twisted-3.5.0.tar.gz/zope.app.twisted-3.5.0/src/twisted/web/woven/WebConduit2_msie.js | WebConduit2_msie.js |
from zope.interface import Interface
class UndoError(Exception):
pass
class IUndo(Interface):
"""Undo functionality"""
def getTransactions(context=None, first=0, last=-20):
"""Return a sequence of mapping objects describing
transactions, ordered by date, descending:
Keys of mapping objects:
id -> internal id for zodb
principal -> principal that invoked the transaction
datetime -> datetime object of time
description -> description/note (string)
Extended information (not necessarily available):
request_type -> type of request that caused transaction
request_info -> request information, e.g. URL, method
location -> location of the object that was modified
undo -> boolean value, indicated an undo transaction
If 'context' is None, all transactions will be listed,
otherwise only transactions for that location.
It skips the 'first' most recent transactions; i.e. if first
is N, then the first transaction returned will be the Nth
transaction.
If last is less than zero, then its absolute value is the
maximum number of transactions to return. Otherwise if last
is N, then only the N most recent transactions following start
are considered.
"""
def undoTransactions(ids):
"""Undo the transactions specified in the sequence 'ids'.
"""
class IPrincipalUndo(Interface):
"""Undo functionality for one specific principal"""
def getPrincipalTransactions(principal, context=None, first=0, last=-20):
"""Returns transactions invoked by the given principal.
See IUndo.getTransactions() for more information
"""
def undoPrincipalTransactions(principal, ids):
"""Undo the transactions invoked by 'principal' with the given
'ids'. Raise UndoError if a transaction is listed among 'ids'
that does not belong to 'principal'.
"""
class IUndoManager(IUndo, IPrincipalUndo):
"""Utility to provide both global and principal-specific undo
functionality
""" | zope.app.undo | /zope.app.undo-3.5.0.tar.gz/zope.app.undo-3.5.0/src/zope/app/undo/interfaces.py | interfaces.py |
import zope.component
from zope.security.interfaces import ForbiddenAttribute
from zope.publisher.browser import BrowserView
from zope.app.undo.interfaces import IUndoManager
class UndoView(BrowserView):
"""Undo view"""
def principalLastTransactionIsUndo(self):
"""Return True if the authenticated principal's last
transaction is an undo transaction.
"""
request = self.request
undo = zope.component.getUtility(IUndoManager)
txn_info = undo.getPrincipalTransactions(request.principal, first=0,
last=1)
if txn_info:
return txn_info[0].get('undo', False)
return False
def undoPrincipalLastTransaction(self):
"""Undo the authenticated principal's last transaction and
return where he/she came from"""
request = self.request
undo = zope.component.getUtility(IUndoManager)
txn_info = undo.getPrincipalTransactions(request.principal, first=0,
last=1)
if txn_info:
id = txn_info[0]['id']
undo.undoPrincipalTransactions(request.principal, [id])
target = request.get('HTTP_REFERER', '@@SelectedManagementView.html')
request.response.redirect(target)
def undoAllTransactions(self, ids):
"""Undo transactions specified in 'ids'."""
undo = zope.component.getUtility(IUndoManager)
undo.undoTransactions(ids)
self._redirect()
def undoPrincipalTransactions(self, ids):
"""Undo transactions that were issued by the authenticated
user specified in 'ids'."""
undo = zope.component.getUtility(IUndoManager)
undo.undoPrincipalTransactions(self.request.principal, ids)
self._redirect()
def _redirect(self):
target = "@@SelectedManagementView.html"
self.request.response.redirect(target)
def getAllTransactions(self, first=0, last=-20, showall=False):
context = None
if not showall:
context = self.context
undo = zope.component.getUtility(IUndoManager)
return undo.getTransactions(context, first, last)
def getPrincipalTransactions(self, first=0, last=-20, showall=False):
context = None
if not showall:
context = self.context
undo = zope.component.getUtility(IUndoManager)
return undo.getPrincipalTransactions(self.request.principal, context,
first, last) | zope.app.undo | /zope.app.undo-3.5.0.tar.gz/zope.app.undo-3.5.0/src/zope/app/undo/browser.py | browser.py |
__docformat__ = 'restructuredtext'
from datetime import datetime
import transaction
import zope.component
from zope.interface import implements
from zope.traversing.interfaces import IPhysicallyLocatable
from zope.app.undo.interfaces import IUndoManager, UndoError
from zope.app.security.interfaces import IAuthentication, IPrincipal
from zope.app.security.interfaces import PrincipalLookupError
def undoSetup(event):
# setup undo functionality
sm = zope.component.getGlobalSiteManager()
sm.registerUtility(ZODBUndoManager(event.database), IUndoManager)
class Prefix(unicode):
"""A prefix is equal to any string it is a prefix of.
This class can be compared to a string (or arbitrary sequence).
The comparison will return True if the prefix value is a prefix of
the string being compared.
Two prefixes cannot safely be compared.
It does not matter from which side you compare with a prefix:
>>> p = Prefix('str')
>>> p == 'string'
True
>>> 'string' == p
True
You can also test for inequality:
>>> p != 'string'
False
>>> 'string' != p
False
Unicode works, too:
>>> p == u'string'
True
>>> u'string' == p
True
>>> p != u'string'
False
>>> u'string' != p
False
>>> p = Prefix('foo')
>>> p == 'bar'
False
>>> 'bar' == p
False
>>> p != 'bar'
True
>>> 'bar' != p
True
>>> p == None
False
"""
def __eq__(self, other):
return other is not None and other.startswith(self)
def __ne__(self, other):
return not self.__eq__(other)
class ZODBUndoManager(object):
"""Implement the basic undo management API for a single ZODB database."""
implements(IUndoManager)
def __init__(self, db):
self.__db = db
def getTransactions(self, context=None, first=0, last=-20):
"""See zope.app.undo.interfaces.IUndo"""
return self._getUndoInfo(context, None, first, last)
def getPrincipalTransactions(self, principal, context=None,
first=0, last=-20):
"""See zope.app.undo.interfaces.IPrincipal"""
if not IPrincipal.providedBy(principal):
raise TypeError("Invalid principal: %s" % principal)
return self._getUndoInfo(context, principal, first, last)
def _getUndoInfo(self, context, principal, first, last):
specification = {}
if context is not None:
locatable = IPhysicallyLocatable(context, None)
if locatable is not None:
location = Prefix(locatable.getPath())
specification.update({'location': location})
if principal is not None:
# TODO: The 'user' in the transactions is a concatenation
# of 'path' and 'user' (id). 'path' used to be the path
# of the user folder in Zope 2. ZopePublication currently
# does not set a path, so ZODB lets the path default to
# '/'. We should change ZODB3 to set no default path at
# some point
path = '/' # default for now
specification.update({'user_name': path + ' ' + principal.id})
entries = self.__db.undoInfo(first, last, specification)
# We walk through the entries, augmenting the dictionaries
# with some additional items we have promised in the interface
for entry in entries:
entry['datetime'] = datetime.fromtimestamp(entry['time'])
entry['principal'] = None
user_name = entry['user_name']
if user_name:
# TODO: This is because of ZODB3/Zope2 cruft regarding
# the user path (see comment above). This 'if' block
# should go away.
split = user_name.split()
if len(split) == 2:
user_name = split[1]
if user_name:
try:
principal = zope.component.getUtility(
IAuthentication).getPrincipal(user_name)
entry['principal'] = principal
except PrincipalLookupError:
# principals might have passed away
pass
return entries
def undoTransactions(self, ids):
"""See zope.app.undo.interfaces.IUndo"""
self._undo(ids)
def undoPrincipalTransactions(self, principal, ids):
"""See zope.app.undo.interfaces.IPrincipal"""
if not IPrincipal.providedBy(principal):
raise TypeError("Invalid principal: %s" % principal)
# Make sure we only undo the transactions initiated by our
# principal
left_overs = list(ids)
first = 0
batch_size = 20
txns = self._getUndoInfo(None, principal, first, -batch_size)
while txns and left_overs:
for info in txns:
if (info['id'] in left_overs and
info['principal'].id == principal.id):
left_overs.remove(info['id'])
first += batch_size
txns = self._getUndoInfo(None, principal, first, -batch_size)
if left_overs:
raise UndoError("You are trying to undo a transaction that "
"either does not exist or was not initiated "
"by the principal.")
self._undo(ids)
def _undo(self, ids):
for id in ids:
self.__db.undo(id)
transaction.get().setExtendedInfo('undo', True) | zope.app.undo | /zope.app.undo-3.5.0.tar.gz/zope.app.undo-3.5.0/src/zope/app/undo/__init__.py | __init__.py |
__docformat__ = "reStructuredText"
import zope.interface
import zope.component.interfaces
import zope.app.versioncontrol.interfaces
class VersionEvent(zope.component.interfaces.ObjectEvent):
def __init__(self, object, info):
super(VersionEvent, self).__init__(object)
self.info = info
class VersionControlApplied(VersionEvent):
zope.interface.implements(
zope.app.versioncontrol.interfaces.IVersionControlApplied)
def __init__(self, object, info, message):
super(VersionControlApplied, self).__init__(object, info)
self.message = message
def __str__(self):
s = "applied version control to %s" % self.object
if self.message:
s = "%s:\n%s" % (s, self.message)
return s
class VersionCheckedOut(VersionEvent):
zope.interface.implements(
zope.app.versioncontrol.interfaces.IVersionCheckedOut)
def __str__(self):
return "checked out %s, version %s" % (
self.object, self.info.version_id)
class VersionCheckedIn(VersionEvent):
zope.interface.implements(
zope.app.versioncontrol.interfaces.IVersionCheckedIn)
def __init__(self, object, info, message):
super(VersionCheckedIn, self).__init__(object, info)
self.message = message
def __str__(self):
return "checked in %s, version %s" % (
self.object, self.info.version_id)
class VersionReverted(VersionEvent):
zope.interface.implements(
zope.app.versioncontrol.interfaces.IVersionReverted)
def __str__(self):
return "reverted %s to version %s" % (
self.object, self.info.version_id)
class VersionUpdated(VersionEvent):
zope.interface.implements(
zope.app.versioncontrol.interfaces.IVersionReverted)
def __init__(self, object, info, old_version_id):
super(VersionUpdated, self).__init__(object, info)
self.old_version_id = old_version_id
def __str__(self):
return "updated %s from version %s to %s" % (
self.object, self.old_version_id, self.info.version_id)
class VersionRetrieved(VersionEvent):
zope.interface.implements(
zope.app.versioncontrol.interfaces.IVersionRetrieved)
def __str__(self):
return "retrieved %s, version %s" % (
self.object, self.info.version_id)
class VersionLabelled(VersionEvent):
zope.interface.implements(
zope.app.versioncontrol.interfaces.IVersionLabelled)
def __init__(self, object, info, label):
super(VersionLabelled, self).__init__(object, info)
self.label = label
def __str__(self):
return "created label %s from version %s of %s" % (
self.label, self.info.version_id, self.object)
class BranchCreated(VersionEvent):
zope.interface.implements(
zope.app.versioncontrol.interfaces.IVersionReverted)
def __init__(self, object, info, branch_id):
super(BranchCreated, self).__init__(object, info)
self.branch_id = branch_id
def __str__(self):
return "created branch %s from version %s of %s" % (
self.branch_id, self.info.version_id, self.object) | zope.app.versioncontrol | /zope.app.versioncontrol-0.1.tar.gz/zope.app.versioncontrol-0.1/src/zope/app/versioncontrol/event.py | event.py |
import persistent.interfaces
import zope.interface
import zope.schema
import zope.component.interfaces
import zope.annotation.interfaces
from zope.schema.vocabulary import SimpleVocabulary
from zope.i18nmessageid import MessageFactory
_ = MessageFactory('zope.app.versioncontrol')
class VersionControlError(Exception):
pass
class IRepository(zope.interface.Interface):
"""Main API for version control operations.
This interface hides most of the details of version data storage
and retrieval.
In Zope 3, the version control interface will probably be
implemented by a version control utility. In the meantime, it may
be implemented directly by repository implementations (or other
things, like CMF tools).
The goal of this version of the version control interface is to
support simple linear versioning with support for labelled
versions. Future versions or extensions of this interface will
likely support more advanced version control features such as
concurrent lines of descent (activities) and collection
versioning.
"""
def isResourceUpToDate(object, require_branch=False):
"""
Returns true if a resource is based on the latest version. Note
that the latest version is in the context of any branch.
If the require_branch flag is true, this method returns false if
the resource is updated to a particular version, label, or date.
Useful for determining whether a call to checkoutResource()
will succeed.
"""
def isResourceChanged(object):
"""
Return true if the state of a resource has changed in a transaction
*after* the version bookkeeping was saved. Note that this method is
not appropriate for detecting changes within a transaction!
"""
def getVersionInfo(object):
"""
Return the VersionInfo associated with the given object.
The VersionInfo object contains version control bookkeeping
information. If the object is not under version control, a
VersionControlError will be raised.
"""
def applyVersionControl(object, message=None):
"""
Place the given object under version control. A VersionControlError
will be raised if the object is already under version control.
After being placed under version control, the resource is logically
in the 'checked-in' state.
If no message is passed the 'Initial checkin.' message string is
written as the message log entry.
"""
def checkoutResource(object):
"""
Put the given version-controlled object into the 'checked-out'
state, allowing changes to be made to the object. If the object is
not under version control or the object is already checked out, a
VersionControlError will be raised.
"""
def checkinResource(object, message=''):
"""
Check-in (create a new version) of the given object, updating the
state and bookkeeping information of the given object. The optional
message should describe the changes being committed. If the object
is not under version control or is already in the checked-in state,
a VersionControlError will be raised.
"""
def uncheckoutResource(object):
"""
Discard changes to the given object made since the last checkout.
If the object is not under version control or is not checked out,
a VersionControlError will be raised.
"""
def updateResource(object, selector=None):
"""
Update the state of the given object to that of a specific version
of the object. The object must be in the checked-in state to be
updated. The selector must be a string (version id, branch id,
label or date) that is used to select a version from the version
history.
"""
def copyVersion(object, selector):
"""Copy data from an old version to a checked out object
The object's data are updated and it remains checked out and
modified.
"""
def labelResource(object, label, force=None):
"""
Associate the given resource with a label. If force is true, then
any existing association with the given label will be removed and
replaced with the new association. If force is false and there is
an existing association with the given label, a VersionControlError
will be raised.
"""
def getVersionOfResource(history_id, selector):
"""
Given a version history id and a version selector, return the
object as of that version. Note that the returned object has no
acquisition context. The selector must be a string (version id,
branch id, label or date) that is used to select a version
from the version history.
"""
def getVersionIds(object):
"""
Return a sequence of the (string) version ids corresponding to the
available versions of an object. This should be used by UI elements
to populate version selection widgets, etc.
"""
def getLabelsForResource(object):
"""
Return a sequence of the (string) labels corresponding to the
versions of the given object that have been associated with a
label. This should be used by UI elements to populate version
selection widgets, etc.
"""
def getLogEntries(object):
"""
Return a sequence of LogEntry objects (most recent first) that
are associated with a version-controlled object.
"""
def makeBranch(object):
"""Create a new branch, returning the branch id.
The branch is created from the object's version.
A branch id is computed and returned.
"""
CHECKED_OUT = 0
CHECKED_IN = 1
class IVersionInfo(zope.interface.Interface):
"""Version control bookkeeping information."""
# TODO: This *should* be a datetime, but we don't yet know how it's used.
timestamp = zope.schema.Float(
description=_("time value indicating"
" when the bookkeeping information was created"),
required=False)
# TODO: This *should* be an ASCIILine, but there isn't one (yet).
history_id = zope.schema.ASCII(
description=_("""
Id of the version history related to the version controlled resource.
If this isn't set (is None),
"""),
required=False)
# TODO: This *should* be an ASCIILine, but there isn't one (yet).
version_id = zope.schema.ASCII(
description=_(
"version id that the version controlled resource is based upon"))
status = zope.schema.Choice(
description=_("status of the version controlled resource"),
vocabulary=SimpleVocabulary.fromItems([
(_("Checked out"), CHECKED_OUT),
(_("Checked in"), CHECKED_IN)]))
sticky = zope.interface.Attribute(
"tag information used internally by the version control implementation"
)
user_id = zope.schema.TextLine(
description=_("id of the effective user at the time the bookkeeping"
" information was created"))
ACTION_CHECKOUT = 0
ACTION_CHECKIN = 1
ACTION_UNCHECKOUT = 2
ACTION_UPDATE = 3
class ILogEntry(zope.interface.Interface):
"""The ILogEntry interface provides access to the information in an
audit log entry."""
timestamp = zope.schema.Float(
description=_("time that the log entry was created"))
version_id = zope.schema.ASCII(
description=_("version id of the resource related to the log entry"))
action = zope.schema.Choice(
description=_("the action that was taken"),
vocabulary=SimpleVocabulary.fromItems(
[(_("Checkout"), ACTION_CHECKOUT),
(_("Checkin"), ACTION_CHECKIN),
(_("Uncheckout"), ACTION_UNCHECKOUT),
(_("Update"), ACTION_UPDATE)]))
message = zope.schema.Text(
description=_("Message provided by the user at the time of the"
" action. This may be empty."))
user_id = zope.schema.TextLine(
description=_("id of the user causing the audited action"))
path = zope.schema.TextLine(
description=_("path to the object upon which the action was taken"))
class INonVersionedData(zope.interface.Interface):
"""Controls what parts of an object fall outside version control.
Containerish objects implement this interface to allow the items they
contain to be versioned independently of the container.
"""
def listNonVersionedObjects():
"""Returns a list of subobjects that should not be pickled.
The objects in the list must not be wrapped, because only the
identity of the objects will be considered. The version
repository uses this method to avoid cloning subobjects that
will soon be removed by removeNonVersionedData.
"""
def removeNonVersionedData():
"""Removes the non-versioned data from this object.
The version repository uses this method before storing an
object in the version repository.
"""
def getNonVersionedData():
"""Returns an opaque object containing the non-versioned data.
The version repository uses this method before reverting an
object to a revision.
"""
def restoreNonVersionedData(data):
"""Restores non-versioned data to this object.
The version repository uses this method after reverting an
object to a revision. `data` is a value provided by the
`getNonVersionedData()` method of this instance.
??? question:
This should not overwrite data that exists in the object but
that is included in the passed-in data.
"""
# TODO: figure out if we can get rid of this
IVersionedContainer = INonVersionedData
class IVersionable(persistent.interfaces.IPersistent,
zope.annotation.interfaces.IAnnotatable):
"""Version control is allowed for objects that provide this."""
class IVersioned(IVersionable):
"""Version control is in effect for this object."""
class ICheckedIn(IVersioned):
"""Object that has been checked in.
Changes should not be allowed.
An object may be ICheckedIn or ICheckedOut, but not both,
"""
class ICheckedOut(IVersioned):
"""Object that has been checked out.
Changes should be allowed.
An object may be ICheckedIn or ICheckedOut, but not both,
"""
# Events that are raised for interesting occurances:
class IVersionEvent(zope.component.interfaces.IObjectEvent):
"""Base interface for all version-control events."""
info = zope.interface.Attribute("Version info (IVersionInfo)")
class IVersionControlApplied(IVersionEvent):
"""Event fired when version control is initially applied to an object."""
message = zope.schema.Text(
title=_("Message"),
description=_("Message text passed to applyVersionControl()"
" for the object."),
)
info = zope.interface.Attribute(
"VersionInfo object reflecting the action.")
class IVersionCheckedIn(IVersionEvent):
"""Event fired when an object is checked in."""
message = zope.schema.Text(
title=_("Checkin Message"),
)
class IVersionCheckedOut(IVersionEvent):
"""Event fired when an object is checked out."""
class IVersionReverted(IVersionEvent):
"""Event fired when a checked-out object is reverted.
(Fired by the uncheckoutResource() repository method.)
"""
class IVersionUpdated(IVersionEvent):
"""Event fired when an object is updated to the latest version."""
class IVersionRetrieved(IVersionEvent):
"""Event fired when a versioned object is retrieved from the repository."""
class IVersionLabelled(IVersionEvent):
"""Event fired when a label is attached to a version."""
# TODO: should be ASCIILine
label = zope.schema.ASCII(
title=_("Label"),
description=_("Label applied to the version."),
)
class IBranchCreated(IVersionEvent):
"""Event fired when a new branch is created."""
# TODO: should be ASCIILine
branch_id = zope.schema.ASCII(
title=_("Branch Id"),
description=_("Identifier for the new branch."),
) | zope.app.versioncontrol | /zope.app.versioncontrol-0.1.tar.gz/zope.app.versioncontrol-0.1/src/zope/app/versioncontrol/interfaces.py | interfaces.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.